id: supabase-storage-bandwidth-and-quota-guardrail
namespace: company.finops
inputs:
- id: project_ref
type: STRING
displayName: "Supabase Project Reference"
description: "The unique alphanumeric reference identifier of your Supabase
project (e.g. abcdefghijklmnopqrst)."
defaults: "abcdefghijklmnopqrst"
- id: bandwidth_cap_gb
type: INT
displayName: "Monthly Bandwidth Cap (GB)"
description: "Allocated monthly storage egress bandwidth quota in gigabytes
according to your Supabase tier plan (e.g. 50 GB for Pro tier, 5 GB for
Free tier)."
defaults: 50
- id: warning_threshold_pct
type: INT
displayName: "Warning Quota Threshold (%)"
description: "Bandwidth utilization percentage threshold that triggers proactive
warning alerts and defensive CDN caching (default: 80%)."
defaults: 80
- id: critical_threshold_pct
type: INT
displayName: "Critical Quota Threshold (%)"
description: "Bandwidth utilization percentage threshold that triggers emergency
rate limiting and incident escalation (default: 95%)."
defaults: 95
- id: auto_remediate
type: BOOL
displayName: "Enable Proactive CDN / Rate-Limiting Remediation"
description: "When true, automatically updates storage bucket transfer limits
and caching policies on high-risk public buckets upon quota breach."
defaults: true
- id: slack_channel
type: STRING
displayName: "Slack Alert Channel"
description: "Target Slack channel for storage egress warnings and quota
guardrail incident alerts."
defaults: "#finops-storage-alerts"
tasks:
- id: fetch_billing_usage
type: io.kestra.plugin.core.http.Request
description: "Queries Supabase Management API billing usage endpoint to inspect
current egress bandwidth consumption."
uri: "https://api.supabase.com/v1/projects/{{ inputs.project_ref
}}/billing/usage"
method: GET
headers:
Authorization: "Bearer {{ secret('SUPABASE_ACCESS_TOKEN') }}"
Content-Type: "application/json"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT30S
- id: fetch_storage_buckets
type: io.kestra.plugin.core.http.Request
description: "Queries Supabase Management API to retrieve all storage buckets
and public asset configurations."
uri: "https://api.supabase.com/v1/projects/{{ inputs.project_ref
}}/storage/buckets"
method: GET
headers:
Authorization: "Bearer {{ secret('SUPABASE_ACCESS_TOKEN') }}"
Content-Type: "application/json"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT30S
- id: evaluate_egress_and_buckets
type: io.kestra.plugin.scripts.python.Script
description: "Evaluates egress consumption against tier quotas, audits bucket
public exposure, and computes guardrail actions."
containerImage: python:3.12-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
env:
USAGE_DATA: "{{ outputs.fetch_billing_usage.body | toJson }}"
BUCKETS_DATA: "{{ outputs.fetch_storage_buckets.body | toJson }}"
USAGE_STATUS: "{{ outputs.fetch_billing_usage.code }}"
BUCKETS_STATUS: "{{ outputs.fetch_storage_buckets.code }}"
BANDWIDTH_CAP_GB: "{{ inputs.bandwidth_cap_gb }}"
WARNING_THRESHOLD_PCT: "{{ inputs.warning_threshold_pct }}"
CRITICAL_THRESHOLD_PCT: "{{ inputs.critical_threshold_pct }}"
PROJECT_REF: "{{ inputs.project_ref }}"
script: |
import os
import json
import sys
from datetime import datetime, timezone
raw_usage = os.environ.get("USAGE_DATA", "{}")
usage_status = int(os.environ.get("USAGE_STATUS", "0"))
raw_buckets = os.environ.get("BUCKETS_DATA", "[]")
buckets_status = int(os.environ.get("BUCKETS_STATUS", "0"))
bandwidth_cap_gb = float(os.environ.get("BANDWIDTH_CAP_GB", "50"))
warning_threshold_pct = float(os.environ.get("WARNING_THRESHOLD_PCT", "80"))
critical_threshold_pct = float(os.environ.get("CRITICAL_THRESHOLD_PCT", "95"))
project_ref = os.environ.get("PROJECT_REF", "unknown")
try:
if isinstance(raw_usage, str):
usage_payload = json.loads(raw_usage) if raw_usage.strip() else {}
else:
usage_payload = raw_usage or {}
except Exception:
usage_payload = {}
egress_bytes = 0
egress_limit_bytes = int(bandwidth_cap_gb * (1024 ** 3))
if isinstance(usage_payload, dict):
usages_list = usage_payload.get("usages")
if isinstance(usages_list, list):
for item in usages_list:
metric_name = str(item.get("metric", "")).upper()
if "STORAGE_EGRESS" in metric_name or "EGRESS" in metric_name:
egress_bytes = int(item.get("usage", 0))
if item.get("limit"):
egress_limit_bytes = int(item.get("limit"))
elif item.get("pricing_free_units"):
egress_limit_bytes = int(item.get("pricing_free_units"))
break
elif "storage_egress" in usage_payload:
se = usage_payload["storage_egress"]
if isinstance(se, dict):
egress_bytes = int(se.get("usage", 0))
if se.get("limit"):
egress_limit_bytes = int(se.get("limit"))
elif isinstance(se, (int, float)):
egress_bytes = int(se)
elif "usage" in usage_payload and isinstance(usage_payload["usage"], (int, float)):
egress_bytes = int(usage_payload["usage"])
try:
if isinstance(raw_buckets, str):
buckets_list = json.loads(raw_buckets) if raw_buckets.strip() else []
else:
buckets_list = raw_buckets or []
except Exception:
buckets_list = []
if not isinstance(buckets_list, list):
if isinstance(buckets_list, dict) and "buckets" in buckets_list:
buckets_list = buckets_list["buckets"]
else:
buckets_list = []
public_buckets = []
private_buckets = []
high_risk_buckets = []
for b in buckets_list:
if not isinstance(b, dict):
continue
b_id = b.get("id") or b.get("name") or "unknown"
is_public = bool(b.get("public", False))
file_size_limit = b.get("file_size_limit")
if is_public:
public_buckets.append(b_id)
if file_size_limit is None or file_size_limit > 52428800:
high_risk_buckets.append(b_id)
else:
private_buckets.append(b_id)
total_buckets = len(public_buckets) + len(private_buckets)
egress_gb = round(egress_bytes / (1024 ** 3), 3)
quota_gb = round(egress_limit_bytes / (1024 ** 3), 2)
usage_percentage = round((egress_bytes / egress_limit_bytes) * 100, 2) if egress_limit_bytes > 0 else 0.0
if usage_percentage >= critical_threshold_pct:
severity = "CRITICAL"
threshold_exceeded = True
recommended_action = "EMERGENCY_RATE_LIMIT_AND_CDN_LOCKDOWN"
action_summary = (
f"Critical egress quota reached ({usage_percentage}% >= {critical_threshold_pct}%). "
f"Imminent bandwidth cap exhaustion on project '{project_ref}'. "
f"Defensive rate limiting and restrictive bucket policies triggered."
)
elif usage_percentage >= warning_threshold_pct:
severity = "WARNING"
threshold_exceeded = True
recommended_action = "ENHANCE_CDN_CACHING_AND_THROTTLE"
action_summary = (
f"Warning egress threshold breached ({usage_percentage}% >= {warning_threshold_pct}%). "
f"Potential hotlinking or viral download surge detected. "
f"Extended edge CDN caching (Cache-Control max-age) applied."
)
else:
severity = "NOMINAL"
threshold_exceeded = False
recommended_action = "MAINTAIN_STANDARD_POLICY"
action_summary = (
f"Storage egress bandwidth is nominal ({usage_percentage}% of {quota_gb} GB quota). "
f"Public buckets: {len(public_buckets)}, Private buckets: {len(private_buckets)}."
)
target_bucket = high_risk_buckets[0] if high_risk_buckets else (public_buckets[0] if public_buckets else "none")
telemetry = {
"project_ref": project_ref,
"timestamp": datetime.now(timezone.utc).isoformat(),
"severity": severity,
"usage_percentage": usage_percentage,
"egress_bytes": egress_bytes,
"egress_gb": egress_gb,
"quota_gb": quota_gb,
"quota_bytes": egress_limit_bytes,
"warning_threshold_pct": warning_threshold_pct,
"critical_threshold_pct": critical_threshold_pct,
"total_buckets": total_buckets,
"public_buckets_count": len(public_buckets),
"private_buckets_count": len(private_buckets),
"public_buckets": public_buckets,
"private_buckets": private_buckets,
"high_risk_buckets": high_risk_buckets,
"target_remediation_bucket": target_bucket,
"recommended_action": recommended_action,
"action_summary": action_summary
}
outputs = {
"severity": severity,
"threshold_exceeded": threshold_exceeded,
"usage_percentage": usage_percentage,
"egress_gb": egress_gb,
"quota_gb": quota_gb,
"total_buckets": total_buckets,
"public_buckets_count": len(public_buckets),
"private_buckets_count": len(private_buckets),
"public_bucket_names": public_buckets,
"high_risk_buckets": high_risk_buckets,
"target_remediation_bucket": target_bucket,
"recommended_action": recommended_action,
"summary": action_summary,
"telemetry_json": json.dumps(telemetry)
}
print(f"Egress Audit: {usage_percentage}% ({egress_gb} GB / {quota_gb} GB) - Severity: {severity}")
print("::" + json.dumps({"outputs": outputs}) + "::")
- id: persist_usage_telemetry
type: io.kestra.plugin.core.kv.Set
description: "Stores storage egress metrics and audit telemetry in Kestra KV
store for historical trend analysis."
key: "supabase_storage_egress_{{ inputs.project_ref }}"
value: "{{ outputs.evaluate_egress_and_buckets.vars.telemetry_json }}"
kvType: JSON
- id: guardrail_decision_gate
type: io.kestra.plugin.core.flow.If
description: "Evaluates whether bandwidth usage exceeded warning (80%) or
critical (95%) guardrails to trigger defensive policies and Slack alerts."
condition: "{{ outputs.evaluate_egress_and_buckets.vars.threshold_exceeded }}"
then:
- id: apply_cdn_caching_guardrail
type: io.kestra.plugin.core.flow.If
description: "Deploys defensive bucket rate limiting and caching policies when
auto-remediation is enabled."
condition: "{{ inputs.auto_remediate and
outputs.evaluate_egress_and_buckets.vars.target_remediation_bucket !=
'none' }}"
then:
- id: update_bucket_policy
type: io.kestra.plugin.core.http.Request
description: "Updates bucket configuration to enforce per-asset size limits and
defensive caching against viral downloads."
uri: "https://api.supabase.com/v1/projects/{{ inputs.project_ref
}}/storage/buckets/{{
outputs.evaluate_egress_and_buckets.vars.target_remediation_bucket
}}"
method: PUT
headers:
Authorization: "Bearer {{ secret('SUPABASE_ACCESS_TOKEN') }}"
Content-Type: "application/json"
body: |
{
"public": true,
"file_size_limit": 5242880
}
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT30S
- id: log_remediation_action
type: io.kestra.plugin.core.log.Log
description: "Logs the guardrail remediation event executed against the target
storage bucket."
message: "Proactive storage egress policy applied to bucket '{{
outputs.evaluate_egress_and_buckets.vars.target_remediation_bucket
}}': {{
outputs.evaluate_egress_and_buckets.vars.recommended_action }}."
- id: notify_slack_guardrail_breach
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Sends high-priority quota alert to the engineering team on Slack."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "🚨 *Supabase Storage Egress Bandwidth Guardrail Alert*\n• *Project Ref:* `{{ inputs.project_ref }}`\n• *Severity:* `{{ outputs.evaluate_egress_and_buckets.vars.severity }}`\n• *Bandwidth Egress:* `{{ outputs.evaluate_egress_and_buckets.vars.egress_gb }} GB` / `{{ outputs.evaluate_egress_and_buckets.vars.quota_gb }} GB` (`{{ outputs.evaluate_egress_and_buckets.vars.usage_percentage }}%`)\n• *Public Buckets:* `{{ outputs.evaluate_egress_and_buckets.vars.public_buckets_count }}` (Total: `{{ outputs.evaluate_egress_and_buckets.vars.total_buckets }}`)\n• *High Risk Buckets:* `{{ outputs.evaluate_egress_and_buckets.vars.high_risk_buckets }}`\n• *Recommended Action:* `{{ outputs.evaluate_egress_and_buckets.vars.recommended_action }}`\n• *Auto-Remediation:* `{{ inputs.auto_remediate }}`"
}
- id: enforce_critical_quota_escalation
type: io.kestra.plugin.core.flow.If
description: "Fails execution to trigger downstream incident escalation if
bandwidth usage reached critical tier limits."
condition: "{{ outputs.evaluate_egress_and_buckets.vars.severity == 'CRITICAL' }}"
then:
- id: fail_on_critical_quota
type: io.kestra.plugin.core.execution.Fail
description: "Halts workflow with failure to alert on-call responders of
imminent quota exhaustion."
else:
- id: log_nominal_storage_metrics
type: io.kestra.plugin.core.log.Log
description: "Logs nominal storage egress usage when consumption is below
warning threshold."
message: "Supabase storage egress is nominal: {{
outputs.evaluate_egress_and_buckets.vars.usage_percentage }}% ({{
outputs.evaluate_egress_and_buckets.vars.egress_gb }} GB / {{
outputs.evaluate_egress_and_buckets.vars.quota_gb }} GB). Monitored
buckets: {{ outputs.evaluate_egress_and_buckets.vars.total_buckets
}}."
- id: return_telemetry_summary
type: io.kestra.plugin.core.debug.Return
description: "Emits structured egress and bucket metrics for downstream
pipelines or reporting."
format:
project_ref: "{{ inputs.project_ref }}"
severity: "{{ outputs.evaluate_egress_and_buckets.vars.severity }}"
usage_percentage: "{{ outputs.evaluate_egress_and_buckets.vars.usage_percentage }}"
egress_gb: "{{ outputs.evaluate_egress_and_buckets.vars.egress_gb }}"
quota_gb: "{{ outputs.evaluate_egress_and_buckets.vars.quota_gb }}"
total_buckets: "{{ outputs.evaluate_egress_and_buckets.vars.total_buckets }}"
public_buckets_count: "{{ outputs.evaluate_egress_and_buckets.vars.public_buckets_count }}"
private_buckets_count: "{{ outputs.evaluate_egress_and_buckets.vars.private_buckets_count }}"
recommended_action: "{{ outputs.evaluate_egress_and_buckets.vars.recommended_action }}"
triggers:
- id: periodic_egress_guardrail_schedule
type: io.kestra.plugin.core.trigger.Schedule
description: "Evaluates Supabase storage egress bandwidth every 6 hours to
detect runaway consumption."
cron: "0 */6 * * *"
disabled: true
errors:
- id: notify_guardrail_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Dispatches failure alert if the Supabase egress sentinel fails
unexpectedly."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"channel": "{{ inputs.slack_channel }}",
"text": "❌ *Supabase Storage Guardrail Workflow Failure*\nExecution `{{ execution.id }}` failed during quota audit for project `{{ inputs.project_ref }}`. Check Kestra execution logs."
}