id: git-lfs-pointer-integrity-and-binary-quota-gate
namespace: company.platform
inputs:
- id: git_repository_url
type: STRING
displayName: Git Repository URL
required: true
description: HTTPS URL of the Git repository to inspect for LFS pointer
integrity and untracked binary blobs.
- id: git_branch
type: STRING
displayName: Git Branch
defaults: "main"
description: Branch or reference to check out and evaluate during the audit.
- id: max_raw_blob_mb
type: INT
displayName: Maximum Raw Blob Quota (MB)
defaults: 50
description: Maximum allowable size in megabytes for raw files committed
directly to Git without Git LFS tracking.
- id: enforce_gate
type: BOOL
displayName: Enforce Gate Failure
defaults: true
description: When true, halts the workflow execution with a failure status if
quota breaches, corrupted pointers, or untransformed LFS files are found.
- id: slack_channel
type: STRING
displayName: Slack Notification Channel
defaults: "#gitops-alerts"
description: Destination Slack channel for incident alerts, quota warnings, and
migration instructions.
triggers:
- id: git_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Receives pull request or push webhook events from GitHub or GitLab
to run pre-merge gate validation.
key: "{{ secret('GIT_WEBHOOK_KEY') }}"
inputs:
git_repository_url: replace-with-your-git-repository-url
tasks:
- id: repository_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: Ephemeral working directory sharing the cloned repository tree with
the containerized audit engine.
tasks:
- id: clone_repository
type: io.kestra.plugin.git.Clone
description: Checks out the designated Git repository and branch into the shared
workspace.
url: "{{ trigger.body.repository.clone_url is defined ?
trigger.body.repository.clone_url : inputs.git_repository_url }}"
branch: "{{ trigger.body.ref is defined ? trigger.body.ref : inputs.git_branch
}}"
- id: audit_lfs_and_binary_blobs
type: io.kestra.plugin.scripts.python.Script
description: Parses .gitattributes rules, checks LFS pointer specification
syntax, and audits file sizes against raw blob quotas.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
MAX_RAW_BLOB_MB: "{{ inputs.max_raw_blob_mb }}"
script: |
import os
import re
import fnmatch
import shlex
import json
from pathlib import Path
max_raw_blob_mb = float(os.environ.get("MAX_RAW_BLOB_MB", "50"))
max_raw_blob_bytes = int(max_raw_blob_mb * 1024 * 1024)
# Parse .gitattributes for active Git LFS tracking filters
lfs_patterns = []
gitattributes_path = Path(".gitattributes")
if gitattributes_path.is_file():
try:
with open(gitattributes_path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) > 1 and any(a in {"filter=lfs", "diff=lfs", "merge=lfs"} for a in parts[1:]):
lfs_patterns.append(parts[0])
except Exception as e:
print(f"Warning reading .gitattributes: {e}")
print(f"Discovered {len(lfs_patterns)} LFS pattern(s) in .gitattributes: {lfs_patterns}")
# Git LFS specification regex: https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md
LFS_HEADER = "version https://git-lfs.github.com/spec/v1"
OID_REGEX = re.compile(r"^oid sha256:([a-f0-9]{64})$", re.MULTILINE)
SIZE_REGEX = re.compile(r"^size ([0-9]+)$", re.MULTILINE)
total_files_audited = 0
valid_lfs_pointers = []
corrupted_pointers = []
untransformed_lfs_files = []
untracked_large_blobs = []
def matches_lfs_patterns(filepath_str: str) -> bool:
for pat in lfs_patterns:
if fnmatch.fnmatch(filepath_str, pat) or fnmatch.fnmatch(os.path.basename(filepath_str), pat):
return True
return False
skip_dirs = {".git", ".kestra", "__pycache__", ".github"}
for root, dirs, files in os.walk("."):
dirs[:] = [d for d in dirs if d not in skip_dirs]
for filename in files:
file_path = Path(root) / filename
rel_path = str(file_path.relative_to(".")).replace("\\", "/")
if rel_path in {".gitattributes", ".gitignore"}:
continue
try:
stat_info = file_path.stat()
file_size = stat_info.st_size
except OSError:
continue
total_files_audited += 1
is_lfs_pointer = False
# Valid pointer files are small text stubs under 1KB
if file_size < 1024:
try:
with open(file_path, "rb") as f:
header_bytes = f.read(64)
if header_bytes.startswith(LFS_HEADER.encode("utf-8")):
with open(file_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
oid_match = OID_REGEX.search(content)
size_match = SIZE_REGEX.search(content)
if oid_match and size_match:
valid_lfs_pointers.append({
"path": rel_path,
"oid": oid_match.group(1),
"declared_size_bytes": int(size_match.group(1))
})
is_lfs_pointer = True
else:
corrupted_pointers.append({
"path": rel_path,
"reason": "Malformed pointer stub: missing valid 64-char hex SHA-256 OID or size attribute."
})
continue
except Exception:
pass
if is_lfs_pointer:
continue
# Check if file matches .gitattributes LFS pattern but was committed as raw binary
if matches_lfs_patterns(rel_path):
untransformed_lfs_files.append({
"path": rel_path,
"size_mb": round(file_size / (1024 * 1024), 2),
"size_bytes": file_size
})
continue
# Check if raw untracked file breaches binary threshold
if file_size > max_raw_blob_bytes:
untracked_large_blobs.append({
"path": rel_path,
"size_mb": round(file_size / (1024 * 1024), 2),
"threshold_mb": max_raw_blob_mb,
"extension": file_path.suffix or "none"
})
# Determine classification verdict
if corrupted_pointers:
verdict = "CORRUPTED_POINTER"
elif untransformed_lfs_files:
verdict = "UNTRANSFORMED_LFS_FILE"
elif untracked_large_blobs:
verdict = "UNTRACKED_LARGE_BLOB"
else:
verdict = "COMPLIANT"
remediation_command = "none"
if verdict == "UNTRACKED_LARGE_BLOB":
exts = sorted(list({b["extension"] for b in untracked_large_blobs if b["extension"] != "none"}))
globs = [f"*{ext}" for ext in exts] if exts else ["*.bin"]
track_args = " ".join(shlex.quote(g) for g in globs)
include_arg = shlex.quote(",".join(globs))
remediation_command = f"git lfs track {track_args} && git lfs migrate import --include={include_arg} --everything"
elif verdict == "UNTRANSFORMED_LFS_FILE":
sample_files = " ".join(shlex.quote(f["path"]) for f in untransformed_lfs_files[:5])
remediation_command = f"git lfs install && git rm --cached {sample_files} && git add {sample_files} && git commit -m 'chore: convert raw binaries to LFS pointers'"
elif verdict == "CORRUPTED_POINTER":
sample_corrupted = " ".join(shlex.quote(f["path"]) for f in corrupted_pointers[:3])
remediation_command = f"git lfs fsck --pointers ; git rm --cached {sample_corrupted} && git add {sample_corrupted}"
audit_summary = {
"verdict": verdict,
"total_files_audited": total_files_audited,
"lfs_pointers_count": len(valid_lfs_pointers),
"large_blobs_count": len(untracked_large_blobs),
"large_blobs": untracked_large_blobs[:20],
"untransformed_count": len(untransformed_lfs_files),
"untransformed_files": untransformed_lfs_files[:20],
"corrupted_count": len(corrupted_pointers),
"corrupted_pointers": corrupted_pointers[:20],
"remediation_command": remediation_command
}
print(f"Audit completed with verdict '{verdict}'. Scanned {total_files_audited} files: {len(valid_lfs_pointers)} valid LFS pointer(s), {len(untracked_large_blobs)} untracked large blob(s), {len(untransformed_lfs_files)} untransformed LFS file(s), {len(corrupted_pointers)} corrupted pointer(s).")
print("::" + json.dumps({"outputs": audit_summary}) + "::")
- id: evaluate_audit_verdict
type: io.kestra.plugin.core.flow.Switch
description: Routes execution based on the Git LFS pointer integrity and raw
binary quota verdict.
value: "{{ outputs.audit_lfs_and_binary_blobs.vars.verdict }}"
cases:
"COMPLIANT":
- id: log_compliance
type: io.kestra.plugin.core.log.Log
description: Logs clean compliance audit details in execution history.
message: "COMPLIANCE VERIFIED: Repository passed Git LFS and binary quota
checks. Audited {{
outputs.audit_lfs_and_binary_blobs.vars.total_files_audited }}
files, {{ outputs.audit_lfs_and_binary_blobs.vars.lfs_pointers_count
}} valid LFS pointers. No untracked blobs exceed {{
inputs.max_raw_blob_mb }} MB."
"UNTRACKED_LARGE_BLOB":
- id: alert_untracked_large_blobs
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatches high-priority Slack notification containing offending
blobs and exact migration command.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "🚨 *Git LFS Quota Breach Detected*",
"attachments": [
{
"color": "#E24A4A",
"fields": [
{"title": "Repository", "value": {{ (trigger.body.repository.full_name is defined ? trigger.body.repository.full_name : inputs.git_repository_url) | toJson }}, "short": true},
{"title": "Branch", "value": {{ (trigger.body.ref is defined ? trigger.body.ref : inputs.git_branch) | toJson }}, "short": true},
{"title": "Violations", "value": {{ ((outputs.audit_lfs_and_binary_blobs.vars.large_blobs_count | string) ~ " untracked file(s) exceed " ~ (inputs.max_raw_blob_mb | string) ~ " MB") | toJson }}, "short": false},
{"title": "Migration Command", "value": {{ outputs.audit_lfs_and_binary_blobs.vars.remediation_command | toJson }}, "short": false},
{"title": "Execution", "value": {{ execution.id | toJson }}, "short": true}
]
}
]
}
- id: check_gate_enforcement_quota
type: io.kestra.plugin.core.flow.If
description: Halts the pipeline when enforce_gate is enabled to prevent merging
repository-bloating binaries.
condition: "{{ inputs.enforce_gate }}"
then:
- id: fail_on_blob_quota_breach
type: io.kestra.plugin.core.execution.Fail
description: Halts execution to block PR merge or CI progression.
errorMessage: "GATE HALTED: {{
outputs.audit_lfs_and_binary_blobs.vars.large_blobs_count }}
untracked large binary file(s) exceed {{ inputs.max_raw_blob_mb
}} MB. Migrate files to Git LFS using: {{
outputs.audit_lfs_and_binary_blobs.vars.remediation_command }}"
"UNTRANSFORMED_LFS_FILE":
- id: alert_untransformed_lfs_files
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts Slack when files matching .gitattributes LFS rules were
committed as raw binary.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "🚨 *Untransformed Raw Binary in LFS Path*",
"attachments": [
{
"color": "#E24A4A",
"fields": [
{"title": "Repository", "value": {{ (trigger.body.repository.full_name is defined ? trigger.body.repository.full_name : inputs.git_repository_url) | toJson }}, "short": true},
{"title": "Branch", "value": {{ (trigger.body.ref is defined ? trigger.body.ref : inputs.git_branch) | toJson }}, "short": true},
{"title": "Details", "value": {{ ((outputs.audit_lfs_and_binary_blobs.vars.untransformed_count | string) ~ " file(s) match .gitattributes LFS rules but were committed as raw binary") | toJson }}, "short": false},
{"title": "Remediation", "value": {{ outputs.audit_lfs_and_binary_blobs.vars.remediation_command | toJson }}, "short": false},
{"title": "Execution", "value": {{ execution.id | toJson }}, "short": true}
]
}
]
}
- id: check_gate_enforcement_untransformed
type: io.kestra.plugin.core.flow.If
description: Halts pipeline on untransformed LFS files when gate enforcement is
active.
condition: "{{ inputs.enforce_gate }}"
then:
- id: fail_on_untransformed_files
type: io.kestra.plugin.core.execution.Fail
description: Halts execution due to untransformed raw binaries committed to LFS
paths.
errorMessage: "GATE HALTED: Untransformed raw binary detected in LFS-tracked
path. Git LFS clean filter was bypassed during commit. Remediate
with: {{
outputs.audit_lfs_and_binary_blobs.vars.remediation_command }}"
"CORRUPTED_POINTER":
- id: alert_corrupted_lfs_pointer
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alerts Slack when an invalid or corrupted Git LFS pointer file is
detected.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": {{ inputs.slack_channel | toJson }},
"text": "🚨 *Corrupted Git LFS Pointer Detected*",
"attachments": [
{
"color": "#E24A4A",
"fields": [
{"title": "Repository", "value": {{ (trigger.body.repository.full_name is defined ? trigger.body.repository.full_name : inputs.git_repository_url) | toJson }}, "short": true},
{"title": "Branch", "value": {{ (trigger.body.ref is defined ? trigger.body.ref : inputs.git_branch) | toJson }}, "short": true},
{"title": "Details", "value": {{ ((outputs.audit_lfs_and_binary_blobs.vars.corrupted_count | string) ~ " file(s) have malformed LFS pointer stubs (invalid header, SHA-256 OID or size)") | toJson }}, "short": false},
{"title": "Remediation", "value": {{ outputs.audit_lfs_and_binary_blobs.vars.remediation_command | toJson }}, "short": false},
{"title": "Execution", "value": {{ execution.id | toJson }}, "short": true}
]
}
]
}
- id: check_gate_enforcement_corrupted
type: io.kestra.plugin.core.flow.If
description: Halts pipeline on corrupted LFS pointer files when gate enforcement
is active.
condition: "{{ inputs.enforce_gate }}"
then:
- id: fail_on_corrupted_pointers
type: io.kestra.plugin.core.execution.Fail
description: Halts execution due to corrupted Git LFS pointer files.
errorMessage: "GATE HALTED: Corrupted Git LFS pointer detected. Files contain
malformed LFS headers or invalid SHA256 checksums."
defaults:
- id: log_unrecognized_verdict
type: io.kestra.plugin.core.log.Log
description: Fallback log for unanticipated audit verdict states.
message: "Auditor produced unhandled verdict state: {{
outputs.audit_lfs_and_binary_blobs.vars.verdict }}."