We are designing a vulnerability triage workflow that automatically tags severity, owner, and remediation SLA in an issue tracker. We must consider:
- Inputs: The vulnerability report (could be a new issue, a vulnerability scan result, or a report from a tool). We assume the input is an issue in an issue tracker (like GitHub, Jira, etc.) but we design a system that can be integrated with multiple trackers via API.
- Auto-tagging: We need to assign:
- Severity: e.g., Critical, High, Medium, Low, Informational.
- Owner: The team or individual responsible (e.g., frontend team, backend team, security team, etc.)
- Remediation SLA: Timeframe for fixing (e.g., 1 day, 1 week, 1 month, etc.) based on severity and possibly other factors.
- We need to define the rules for auto-tagging. These rules could be based on:
- The vulnerability type (e.g., SQL injection, XSS, misconfiguration).
- The affected component (e.g., URL, file, package).
- The CVSS score if available.
- The asset criticality (e.g., production vs. staging, public-facing vs. internal).
- We also need to consider that the workflow may involve multiple steps: ingestion, classification, assignment, and notification.
- We must design it as an automated system that can run on new issues or periodically.
We'll outline the system architecture:
- Data Sources: Issue tracker (provide new/updated issues). Possibly also external vulnerability feeds or scan results.
- Processing Engine: A service that fetches issues, applies rules to determine tags, and updates the issue.
- Rules Engine: Where we define the mapping logic. This could be a configurable set of rules (e.g., YAML file, database) so that we can adjust without code changes.
- Integration Layer: Adapters for different issue trackers (GitHub, Jira, GitLab, etc.) to fetch and update issues.
- Scheduler: To run periodically or trigger on webhook events.
We'll produce a step-by-step workflow:
- Ingestion: The system is notified of a new issue (via webhook or polling). It retrieves the issue details (description, labels, comments, custom fields, etc.).
- Enrichment: Possibly fetch additional data like asset inventory, vulnerability database (CVE details), CVSS if not present. But for simplicity, we assume issue contains enough info.
- Classification:
- Determine severity: Could be based on CVSS score if present, else based on rules (e.g., if "SQL injection" => High, if "missing security header" => Low).
- Determine owner: Based on the affected component (e.g., file path contains "/frontend/" => frontend team), or based on CODEOWNERS file if using GitHub, or a mapping table.
- Determine remediation SLA: Could be a function of severity and maybe the owner's capacity or policy. E.g., Critical: 1 day, High: 1 week, Medium: 1 month, Low: 3 months. But also could depend on asset criticality (production = faster).
- Tagging: Apply the tags (labels) to the issue. Possibly also assign to a specific user or team.
- Notification: Notify the owner and stakeholders (e.g., via email, Slack) with the triage results and SLA.
- Escalation: If the issue is not addressed within SLA, automatically escalate (e.g., add a comment, change priority, notify manager).
We must also consider:
- False positives: The system might misclassify. Could have a review step? Maybe initially manual validation before auto-tagging? But the requirement says auto-tag, so we'll assume rules are good.
- Exceptions: Some issues may have overrides (e.g., a critical issue with a known mitigation might get lower SLA). Could have a list of exceptions (e.g., based on CVE IDs).
- Change management: If the issue is updated (e.g., CVSS added), re-run triage.
We'll design the rules as a priority list. Each rule has conditions and outputs. Example rule:
Condition: Issue contains "sql injection" and "production"
severity: Critical
owner: backend-team
SLA: 1 day
Implementation:
- We can write the classification as a series of if-else checks, but better to have a rule engine where we can add rules without code change. We can define rules in a config file (YAML/JSON) and parse.
Example rule config:
rules:
- id: rule1
conditions:
all:
- field: description
contains: "SQL injection"
- field: environment
equals: "production"
severity: "Critical"
owner: "backend-team"
sla: "1 day"
But we may also have different condition types (regex, in list, etc.)
We also need to handle default fallback.
Let's design a simplified but functional workflow in code (pseudocode or Python). Since we need to produce an answer that is "engineered", we should provide a design with code snippets.
We'll assume integration with GitHub Issues for concreteness. We'll use PyGithub or GitHub API.
Steps:
- Set up a GitHub App or personal access token to access issues.
- Listen to webhook events for issues (opened, edited) or poll.
- For each relevant issue, run triage.
We'll create a function triage_issue(issue) that:
- Fetches issue details.
- Extracts features: description, labels, body, maybe custom fields like
environment? Could use issue title, labels, or comments. We'll define a feature extractor that can be customized.
- Applies rule engine to get severity, owner, sla.
- Updates issue with new labels (e.g.,
severity:critical, owner:backend, sla:1d) and maybe assigns to team.
- Posts a comment summarizing.
We also need to consider that the issue may already have these tags; we might skip or update if changed.
We'll provide a rule engine that loads from a YAML file.
Let's draft the YAML rules structure.
Alternatively, we could use a more advanced approach with decision tables or scoring. But simple rule-based is fine.
We'll also incorporate CVSS scoring. If issue has a CVSS vector, we can compute severity from that. We can use cvss library to parse.
Plan:
- Extract CVSS: Look for a pattern like "CVSS:3.1/AV:N/AC:L/..." in body or label.
- If found, compute base score and map to severity: >=9.0 Critical, 7.0-8.9 High, 4.0-6.9 Medium, 0.1-3.9 Low, 0 Informational.
Simplify: if we have a CVSS score, we'll use that as severity mapping. But the requirement is auto-tag severity, so we can rely on CVSS if present else fallback to rules.
Owner mapping: We could have a mapping based on file paths (if the issue includes file paths) or based on a component label. In GitHub, we could use CODEOWNERS to infer owner. But implementing CODEOWNERS parsing is complex. We can have a simple mapping: e.g., if file path contains "/src/frontend/" then owner=frontend-team. Or if issue has label "component:api" then owner=backend-team.
SLA: We define a mapping from severity to SLA days: Critical: 1, High: 7, Medium: 30, Low: 90. But could also vary by owner (some teams have different SLAs). We can have SLA rule separate: based on severity and owner.
Simplify: SLA rule similar to severity; we can have a table.
Implementation steps:
- Create a config file
rules.yaml:
Rules for severity:
severity_rules:
- conditions:
description_contains: "sql injection"
severity: "Critical"
- conditions:
description_contains: "xss"
severity: "High"
- conditions:
description_contains: "information disclosure"
severity: "Medium"
- conditions:
default: true
severity: "Low"
But we want to support multiple condition types: maybe regex on description, label presence, etc. Could define conditions as a list of field checks.
We'll create a generic rule structure:
rule:
conditions:
- field: description
operator: contains
value: "sql injection"
- field: labels
operator: contains
value: "prod"
actions:
severity: "Critical"
owner: "backend"
sla: "1d"
We need to combine conditions with AND by default, maybe OR? We'll do AND.
We'll also allow a default rule with no conditions.
We'll have separate rule sets for each tag? Could have one rule set that sets all three. That's simpler.
So one rule that when matches, sets severity, owner, sla.
We'll design as:
rules:
- name: "SQL injection in production"
conditions:
all:
- field: description
contains: "SQL injection"
- field: environment
equals: "production"
results:
severity: "Critical"
owner: "backend"
sla: "1d"
- name: "XSS in any environment"
conditions:
all:
- field: description
contains: "XSS"
results:
severity: "High"
owner: "frontend"
sla: "7d"
- name: "default"
conditions: {}
results:
severity: "Low"
owner: "security"
sla: "90d"
In code, we'll evaluate rules in order and take first match. Or we can have a priority field.
Now, we need to define what fields we extract from the issue. We'll define a feature extractor that takes issue and returns a dict with keys like 'description', 'labels', 'environment', etc. We can preprocess environment: maybe from labels or from body? Could be not present. We could leave environment unknown.
Maybe we can derive from issue labels like "env:prod". We can standardize: we'll have known fields: 'description' (body lowercased), 'title', 'labels' (list of label names), 'component' maybe from label that starts with "component:".
We'll let the rule conditions use these fields. We'll define a set of operators: contains, equals, in, etc.
We'll implement a simple rule engine.
Algorithm:
def apply_rules(features, rules):
for rule in rules:
if rule_conditions_match(rule['conditions'], features):
return rule['results']
return None
If no rule matches, we could return default if there's a rule with empty conditions. Or we can have a default fallback.
Now for the SLA: we can define SLA as a string like "1d" meaning 1 day. We might compute due date: datetime.now() + timedelta(days=1). But we may want to set a label with that duration. Or we can set a due date in the issue tracker. We'll decide to set a label "sla:1d" and also include a comment with due date and maybe assign a date field.
We'll keep it simple: add labels.
Now we need to produce a complete design and sample code.
We'll produce:
- Architecture diagram (text description).
- Rule configuration.
- Implementation in Python with GitHub API (using PyGithub). We'll write a script that can be run as a service or cron.
We'll also consider that we might want to handle multiple trackers. So we abstract the issue tracker interface.
We'll define an abstract class IssueTracker with methods get_issues(query), update_issue(issue_id, labels, assignee, etc.). Then implement GitHubIssueTracker. But for brevity we'll just show GitHub.
We'll also need to store state to avoid re-processing same issue? We can store last processed issue ID, or use webhook with idempotency. For simplicity, we'll assume we process only newly opened issues and skip if already has severity label.
We'll write code that:
- Authenticates to GitHub.
- Fetches issues from a repo with a certain label (e.g., "vulnerability") or all open issues.
- For each issue without
severity label (or if forced), run triage.
- Apply labels and comment.
Let's write sample code.
We'll need to parse rules from YAML. We'll use ruamel.yaml or PyYAML.
We'll define condition operators: we'll support:
- contains: substring in string value (case insensitive)
- equals: exact match (case insensitive for strings)
- in: value in a list (provided in rule as a list)
- regex: match regex
We'll implement condition checking:
def check_condition(condition, features):
field = condition['field']
op = condition['operator']
expected = condition['value']
actual = features.get(field)
if actual is None:
return False
if op == 'contains':
return expected.lower() in actual.lower()
elif op == 'equals':
return actual.lower() == expected.lower()
elif op == 'in':
return actual in expected # expected is list
elif op == 'regex':
return re.match(expected, actual) is not None
else:
raise ValueError(f"Unknown operator {op}")
But conditions grouping: we might have 'all' and 'any'. We'll design rule conditions like:
conditions:
all:
- field: description
operator: contains
value: "sql"
- field: labels
operator: contains
value: "prod"
So conditions is a dict with keys 'all' or 'any' containing list of conditions. We can support nested.
Simpler: we assume at rule top-level we have conditions as a list and combine with AND. But we need OR sometimes. We'll start with AND only.
We'll do:
conditions:
- field: description
operator: contains
value: "sql"
- field: labels
operator: contains
value: "prod"
All must match.
If we want OR, we can define separate rules.
That's acceptable.
Now feature extraction: We'll produce a dictionary:
features = {
'description': issue.body or '',
'title': issue.title,
'labels': [label.name for label in issue.labels],
'environment': detect_environment(features), # maybe from labels or body
'component': detect_component(...),
}
We can define helper functions to extract environment: if any label starts with "env:" then take the rest. Or if body contains "Environment: production". We'll keep simple: environment label.
Similarly component: look for label "component:xxx". Could also parse file paths if we include them as feature. But we need to get file paths: maybe from issue body if it includes code snippets. That's too complex. For MVP, assume issue has labels for env and component.
We'll let rule conditions refer to fields that we extract. We can also include raw fields like 'description', 'title', 'labels'.
Now for owner: we could have a separate mapping based on component label. For simplicity, we'll have the rule set the owner directly. But we could have rules that set owner based on component. So we can have a rule that says if component is "frontend" then owner = "frontend-team". That's fine.
Now SLA: we might compute based on severity and owner. But we can also define directly in rule. We'll just set in rule results. Or we can have a separate SLA table that maps severity to days, and optionally overrides per owner.
We'll keep simple: rule results include sla string.
Now we must also consider that sometimes CVSS is provided. We'll include a step: if issue body contains a CVSS vector (pattern CVSS:3.1/...), then we compute severity from that and ignore other rules? Or use CVSS as authoritative. We could have a rule that says if CVSS present, use mapping. But we can implement a prioritized step: first check for CVSS; if found, compute severity and set owner based on other factors? Possibly we want to use CVSS for severity but still need owner and SLA. We could have rules that fire based on other fields even if CVSS present. Or we could have a rule that says if CVSS present, severity from CVSS, owner from component, etc.
Better: we treat CVSS as just another feature. We can have a condition that matches if CVSS exists. But we may want to auto-detect and set severity based on CVSS regardless of other conditions, because CVSS is standard. That could be a high-priority rule: if CVSS score >=9 => Critical, etc. We'll include a CVSS extraction function that returns a numeric score. Then we can have a default rule that sets severity if score is set? Actually, we can have the rule engine handle it: we can define a field 'cvss_score' and have rules that check that. But we need to compute it first.
So in feature extraction, we do:
cvss_vector = extract_cvss(issue.body) # regex for CVSS:3.1/...
if cvss_vector:
score = compute_cvss_score(cvss_vector) # need a library? We can approximate with a simple mapping if we don't want to compute precisely? But we want accurate.
features['cvss_score'] = score
But computing CVSS base score from vector requires a library. We can use cvss package (pip install cvss). But to keep simple, we could just use the vector string and have rules that check for specific ranges? That's messy. Alternatively, we could ignore CVSS and rely on the issue's own severity label if present? But requirement is auto-tag, so we need to assign. But if the issue already has a severity label, we might not want to override. We'll check: if issue already has a severity label that matches our known set, we can skip or keep. But we want to ensure consistency. We'll say: if the issue already has any severity label, we skip auto-tagging? Or we could compare and if different, we could override. Better to only auto-tag if no severity label exists, or if a force flag is set. That's safe.
Thus: if issue has existing severity label (matching pattern like "severity:.*"), we skip. That prevents overriding human decisions.
But requirement says "auto-tag severity, owner, and remediation SLA directly in issue trackers." Could be on creation only. So we'll only tag issues that lack these tags.
Implementation: For each issue, check if it has a label that starts with "severity:" (or "severity-" etc.). If not, then triage.
Now we'll write code.
Let's outline:
- Load config (rules.yaml)
- Initialize GitHub client.
- Get open issues from a repository (or multiple). Maybe we can filter by label "triage" or "vulnerability" but assume we process all open issues that are not yet triaged.
- For each issue:
- if any label matches severity pattern, skip.
- else:
features = extract_features(issue)
results = apply_rules(features, rules)
if results:
add labels: f"severity:{results['severity']}", f"owner:{results['owner']}", f"sla:{results['sla']}"
comment = f"Auto-triage:\n- Severity: {results['severity']}\n- Owner: {results['owner']}\n- SLA: {results['sla']}"
issue.create_comment(comment)
else:
comment = "Auto-triage: No matching rule found. Please assign severity, owner, and SLA manually."
issue.create_comment(comment)
But we also need to assign the issue to the owner? Could assign to a team or user. In GitHub, we can assign by login name. We could have a mapping from owner names to GitHub usernames or team slugs. But that's extra. We'll just tag.
Now extraction: We'll parse body and title for CVSS vector. Use regex: r'CVSS:3\.[01]/[A-Za-z0-9:/=]+' typical.
We'll use cvss library to compute score. But we might not want to add dependency. For sample code, we can implement a simple scoring? Not accurate. We'll include library and handle import gracefully.
But as we are "engineering" we can mention using cvss library. We'll provide code that uses it.
Alternatively, we can skip CVSS and rely on rule-based severity.
Given the instruction "Engineer a web security vulnerability triage workflow that auto-tags severity, owner, and remediation SLA directly in issue trackers." We need to produce a design and code. We'll provide a robust solution.
We'll structure answer:
- Overview
- System Architecture
- Rule Configuration (YAML)
- Feature Extraction
- Rule Engine
- Integration with Issue Tracker (GitHub example)
- Handling CVSS (if any)
- SLA Management (due date calculation)
- Escalation (cron job to check overdue issues)
- Security considerations (least privilege for token, etc.)
- Example Implementation (Python code)
Let's draft.
We'll start with a high-level flowchart: Ingestion -> Feature Extraction -> Rule Matching -> Apply Tags -> Notification -> (Periodically) Escalation Check.
Now we'll write the answer.
We'll produce a comprehensive solution.
Web Security Vulnerability Triage Workflow
1. Overview
This solution automates the triage of vulnerability reports submitted to issue trackers (e.g., GitHub, Jira). It automatically assigns:
- Severity (Critical, High, Medium, Low, Informational)
- Owner (team or individual responsible)
- Remediation SLA (timeframe for fixing, e.g., "1d", "7d")
The system is rule‑driven, extensible, and works with multiple issue trackers via a common abstraction layer.
2. Architecture
┌─────────────────────┐ webhook/poll ┌──────────────────────┐
│ Issue Tracker │──────────────────────▶│ Triage Service │
│ (GitHub, Jira, etc.) │ │ (Python) │
└─────────────────────┘ └─────────┬────────────┘
│
▼
┌─────────────────────────────┐
│ Rule Engine │
│ (YAML‑configurable) │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ Feature Extractor │
│ (CVSS, labels, etc.) │
└─────────────┬───────────────┘
│
┌─────────────▼───────────────┐
│ Issue Updater │
│ (adds tags, comments) │
└─────────────────────────────┘
Components:
- Ingestion: Listens for new/updated issues via webhook or periodic polling.
- Feature Extractor: Normalizes issue data (description, labels, CVSS, custom fields) into a feature dictionary.
- Rule Engine: Matches features against a prioritized rule set to determine severity, owner, and SLA.
- Issue Updater: Applies labels, assigns owners, posts a summary comment, and sets a due date.
- Escalation Scheduler: Periodically checks for overdue issues and notifies/ escalates.
3. Rule Configuration (rules.yaml)
# Rule format: first match wins.
rules:
# 1. CVSS‑based severity (highest priority)
- name: "CVSS Critical"
conditions:
- field: cvss_score
operator: gte
value: 9.0
results:
severity: "Critical"
sla: "1d"
- name: "CVSS High"
conditions:
- field: cvss_score
operator: gte
value: 7.0
results:
severity: "High"
sla: "7d"
- name: "CVSS Medium"
conditions:
- field: cvss_score
operator: gte
value: 4.0
results:
severity: "Medium"
sla: "30d"
- name: "CVSS Low"
conditions:
- field: cvss_score
operator: gte
value: 0.1
results:
severity: "Low"
sla: "90d"
# 2. Specific vulnerability patterns
- name: "SQL Injection in Production"
conditions:
- field: description
operator: contains
value: "SQL injection"
- field: environment
operator: equals
value: "production"
results:
severity: "Critical"
owner: "backend-team"
sla: "1d"
- name: "XSS Anywhere"
conditions:
- field: description
operator: regex
value: "(?i)cross[- ]?site scripting|xss"
results:
severity: "High"
owner: "frontend-team"
sla: "7d"
- name: "Missing Security Headers"
conditions:
- field: description
operator: contains
value: "security header"
results:
severity: "Low"
owner: "infra-team"
sla: "90d"
# 3. Default fallback
- name: "Default Triage"
conditions: [] # matches everything
results:
severity: "Informational"
owner: "security-team"
sla: "180d"
Supported Operators:
contains – substring (case‑insensitive)
equals – exact string match (case‑insensitive)
regex – Python regex
gte – numeric greater‑or‑equal (for CVSS score)
in – value in provided list (e.g., field: labels, operator: in, value: ["env:prod","env:stage"])
4. Feature Extraction
From the raw issue object we derive:
| Feature Key | Source |
|---|
description | Issue body (lowercased) |
title | Issue title |
labels | List of label names (e.g., ["env:prod", "component:api"]) |
environment | Extracted from label env:* (default unknown) |
component | Extracted from label component:* (default unknown) |
cvss_vector | Regex match of CVSS:3.[01]/… in body/title/comments |
cvss_score | Computed via cvss library (if vector found) |
has_existing_triage | True if any label matches severity:, owner:, or sla: pattern |
Extractor Pseudocode:
import re
from cvss import CVSS3
def extract_features(issue):
body = issue.body or ""
title = issue.title or ""
full_text = f"{title}\n{body}".lower()
features = {
"description": full_text,
"title": title,
"labels": [lbl.name for lbl in issue.labels],
}
# Environment (e.g., env:production)
env_labels = [lbl for lbl in features["labels"] if lbl.startswith("env:")]
features["environment"] = env_labels[0].split(":", 1)[1] if env_labels else "unknown"
# Component (e.g., component:backend)
comp_labels = [lbl for lbl in features["labels"] if lbl.startswith("component:")]
features["component"] = comp_labels[0].split(":", 1)[1] if comp_labels else "unknown"
# CVSS vector and score
cvss_match = re.search(r'CVSS:3\.1/([A-Za-z0-9:/=]+)', full_text, re.IGNORECASE)
if cvss_match:
vector = f"CVSS:3.1/{cvss_match.group(1)}"
try:
cvss_obj = CVSS3(vector)
features["cvss_score"] = cvss_obj.scores()[0] # base score
except Exception:
features["cvss_score"] = None
else:
features["cvss_score"] = None
# Already has triage?
triage_labels = any(lbl.startswith(("severity:", "owner:", "sla:")) for lbl in features["labels"])
features["has_existing_triage"] = triage_labels
return features
5. Rule Engine
Loads rules from rules.yaml, iterates in order, and returns the first matching result set.
import yaml
from typing import Dict, List, Any
class RuleEngine:
def __init__(self, rules_path: str):
with open(rules_path) as f:
self.rules = yaml.safe_load(f)["rules"]
def evaluate(self, features: Dict[str, Any]) -> Dict[str, str]:
for rule in self.rules:
if self._match_conditions(rule.get("conditions", []), features):
return rule["results"]
return None
def _match_conditions(self, conditions: List[Dict], features: Dict) -> bool:
# All conditions must match (AND)
for cond in conditions:
field = cond["field"]
op = cond["operator"]
expected = cond["value"]
actual = features.get(field)
if actual is None:
return False
# Type‑specific handling
if op == "contains":
if expected.lower() not in str(actual).lower():
return False
elif op == "equals":
if str(actual).lower() != expected.lower():
return False
elif op == "regex":
if not re.match(expected, str(actual), re.IGNORECASE):
return False
elif op == "in":
if actual not in expected:
return False
elif op == "gte":
try:
if float(actual) < float(expected):
return False
except (TypeError, ValueError):
return False
else:
raise ValueError(f"Unsupported operator: {op}")
return True
6. Issue Tracker Integration (GitHub Example)
from github import Github, NamedUser
from datetime import datetime, timedelta
class GitHubIssueTracker:
def __init__(self, token: str, repo_name: str):
self.g = Github(token)
self.repo = self.g.get_repo(repo_name)
def get_untriaged_issues(self):
# Return open issues that lack any triage label
issues = self.repo.get_issues(state="open")
untriaged = []
for issue in issues:
labels = [lbl.name for lbl in issue.labels]
if not any(lbl.startswith(("severity:", "owner:", "sla:")) for lbl in labels):
untriaged.append(issue)
return untriaged
def apply_triage(self, issue, results: Dict[str, str]):
# Build new labels
new_labels = []
if "severity" in results:
new_labels.append(f"severity:{results['severity'].lower()}")
if "owner" in results:
new_labels.append(f"owner:{results['owner']}")
if "sla" in results:
new_labels.append(f"sla:{results['sla']}")
# Add labels (preserving existing)
current_labels = [lbl.name for lbl in issue.labels]
issue.edit(labels=current_labels + new_labels)
# Compute due date from SLA
sla_days = self._parse_sla_days(results.get("sla", "0d"))
due_date = datetime.utcnow() + timedelta(days=sla_days)
# Post comment
comment = f"""## 🚦 Auto‑Triage Results
- **Severity**: {results.get('severity', 'N/A')}
- **Owner**: {results.get('owner', 'N/A')}
- **SLA**: {results.get('sla', 'N/A')} (due by {due_date.strftime('%Y-%m-%d')})
"""
# Optionally assign to a team/user if owner mapping exists
if "owner" in results:
# Map owner string to GitHub team/login (example mapping)
assignee = self._map_owner_to_login(results["owner"])
if assignee:
issue.add_to_assignees(assignee)
issue.create_comment(comment)
def _parse_sla_days(self, sla_str: str) -> int:
# Simple parser: "1d" => 1, "7d" => 7, "30d" => 30
match = re.match(r"(\d+)([dwmy]?)", sla_str)
if not match:
return 0
num = int(match.group(1))
unit = match.group(2)
if unit == "w":
return num * 7
elif unit == "m":
return num * 30
elif unit == "y":
return num * 365
return num # days
def _map_owner_to_login(self, owner_key: str) -> str:
# Placeholder: integrate with your org's mapping (e.g., from config or directory)
mapping = {
"backend-team": "backend-bot",
"frontend-team": "frontend-bot",
"infra-team": "infra-bot",
"security-team": "security-bot",
}
return mapping.get(owner_key)
7. Complete Triage Loop
import os
import logging
logging.basicConfig(level=logging.INFO)
def main():
token = os.environ["GITHUB_TOKEN"]
repo_name = os.getenv("TRIAGE_REPO", "org/vulnerabilities")
rules_path = os.getenv("RULES_PATH", "rules.yaml")
tracker = GitHubIssueTracker(token, repo_name)
engine = RuleEngine(rules_path)
issues = tracker.get_untriaged_issues()
logging.info(f"Found {len(issues)} untriaged issues.")
for issue in issues:
try:
features = extract_features(issue)
if features["has_existing_triage"]:
continue # skip if already has any triage label (defensive)
results = engine.evaluate(features)
if results:
tracker.apply_triage(issue, results)
logging.info(f"Triage applied to issue #{issue.number}")
else:
issue.create_comment("⚠️ Auto‑triage could not determine severity/owner/SLA. Manual review required.")
logging.warning(f"No rule matched for issue #{issue.number}")
except Exception as e:
logging.exception(f"Error processing issue #{issue.number}: {e}")
if __name__ == "__main__":
main()
Run as a cron job (e.g., every 5 minutes) or as a web‑hook server that triggers on issues events.
8. Escalation Workflow
A separate scheduled job (escalate.py) queries for issues whose SLA due date has passed and still remain open.
def check_overdue():
overdue = []
for issue in repo.get_issues(state="open"):
sla_label = next((lbl for lbl in issue.labels if lbl.name.startswith("sla:")), None)
if not sla_label:
continue
sla_days = parse_sla(sla_label.name.split(":",1)[1])
due = issue.created_at + timedelta(days=sla_days)
if due < datetime.utcnow() and not issue.closed_at:
overdue.append(issue)
# Escalate: add "overdue" label, comment, notify owner/manager
issue.add_to_labels("overdue")
issue.create_comment(f"⚠️ This vulnerability has exceeded its SLA ({sla_label.name}). Please prioritize.")
# Optionally raise priority or send Slack/email
return overdue
9. Security & Operational Considerations
- Least‑privilege token: The bot token should only have
issues:read, issues:write, and possibly contents:read to fetch CODEOWNERS if used.
- Idempotency: The script skips issues that already have a
severity:* label, preventing duplicate tagging.
- Audit trail: All auto‑triage actions are recorded as comments.
- Rule testing: Maintain a test suite for rule evaluation using sample issues.
- Performance: Use conditional API requests (e.g., GitHub’s
application/vnd.github+json with per_page=100) to reduce load.
- Multi‑tracker support: Implement adapters for Jira, GitLab by conforming to the
IssueTracker interface.
10. Extensions
- Dynamic owner lookup: Use a
CODEOWNERS parser or integrate with LDAP/HR systems.
- Machine learning fallback: If no rule matches, send to a human or use a classifier.
- SLA calendar: Exclude weekends/holidays using a working‑day calendar.
- Bi‑directional sync: Push changes back to a central CMDB.
This workflow provides a robust, customizable, and fully automated triage pipeline that integrates directly into existing issue‑tracking ecosystems, ensuring vulnerabilities are consistently prioritized and owned.