id: leaver-access-revocation-verification-gate
namespace: company.team
labels:
team: security
use-case: leaver-access-revocation-verification
description: |
Prove a leaver is actually gone instead of trusting that offboarding
happened. Existing offboarding flows trigger deprovisioning; this gate
independently checks every named system after the fact and blocks sign-off
while any residual access remains. GitHub org membership, Slack activity,
Google Workspace status and AWS IAM login access are each checked read-only,
the per-system verdicts are recorded as one evidence record, and any residual
or inconclusive result alerts Security instead of passing quietly. When the
verdict is BLOCKED, the execution itself fails: a green run can never be read
as sign-off for a leaver who still holds access.
triggers:
- id: leaver_offboarded
type: io.kestra.plugin.core.trigger.Webhook
description: Triggered by the HRIS or ITSM offboarding workflow when an
employee's status changes to terminated.
key: "{{ secret('LEAVER_GATE_WEBHOOK_KEY') }}"
inputs:
leaver_username: "{{ trigger.body.leaver_username }}"
leaver_email: "{{ trigger.body.leaver_email }}"
- id: weekly_reverification
type: io.kestra.plugin.core.trigger.Schedule
description: Weekly safety net that re-runs the gate for leavers still under
watch. Shipped disabled so the check list and credentials can be reviewed
before it ever runs unattended. Set its inputs to the leaver under watch
before enabling it; the placeholder values below never run while the
trigger is disabled. Re-run the flow at T+24h and T+7d after offboarding,
either from this schedule or by re-triggering the webhook.
cron: "0 6 * * 1"
disabled: true
inputs:
leaver_username: "REPLACE_WITH_LEAVER_USERNAME"
leaver_email: "REPLACE_WITH_LEAVER_EMAIL"
inputs:
- id: leaver_username
type: STRING
description: Username of the leaver, as it appears in GitHub and AWS IAM.
validator: ^[A-Za-z0-9._-]+$
- id: leaver_email
type: STRING
description: Work email of the leaver, used for the Slack and Google Workspace checks.
- id: github_org
type: STRING
defaults: example-org
description: GitHub organization the leaver must no longer belong to.
- id: aws_region
type: STRING
defaults: us-east-1
description: AWS region used to sign the IAM request. IAM is global, us-east-1
is the standard signing region.
- id: systems
type: ARRAY
itemType: STRING
defaults:
- github
- slack
- google-workspace
- aws-iam
description: Systems to verify, one check each. Remove a system here and it is
reported as skipped instead of checked.
- id: fail_on_inconclusive
type: BOOL
defaults: true
description: When true, a system that cannot be checked (network or auth error)
blocks sign-off just like residual access does. The gate fails closed. Set
it to false only while a system is known to be down for maintenance.
tasks:
- id: run_system_checks
type: io.kestra.plugin.scripts.python.Script
description: Check every named system read-only and emit one verdict per system.
A system passes only when the leaver is provably gone, meaning not a
GitHub org member, deactivated or absent in Slack, suspended or absent in
Google Workspace, with no IAM login profile in AWS. Anything still present
fails, anything uncheckable is inconclusive, and the verdict, the residual
count and the full evidence record are printed through the outputs
protocol.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
env:
LEAVER_USERNAME: "{{ inputs.leaver_username }}"
LEAVER_EMAIL: "{{ inputs.leaver_email }}"
GITHUB_ORG: "{{ inputs.github_org }}"
AWS_REGION: "{{ inputs.aws_region }}"
SYSTEMS_JSON: "{{ inputs.systems | toJson }}"
FAIL_ON_INCONCLUSIVE: "{{ inputs.fail_on_inconclusive }}"
GITHUB_TOKEN: "{{ secret('GITHUB_TOKEN') }}"
SLACK_TOKEN: "{{ secret('SLACK_TOKEN') }}"
GOOGLE_TOKEN: "{{ secret('GOOGLE_TOKEN') }}"
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
script: |
import hashlib
import hmac
import json
import os
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
def http_request(method, url, headers=None, timeout=30):
request = urllib.request.Request(url, method=method, headers=headers or {})
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
body = response.read().decode("utf-8", "replace")
return response.status, body, None
except urllib.error.HTTPError as err:
return err.code, err.read().decode("utf-8", "replace"), None
except Exception as err: # noqa: BLE001 - any transport failure is inconclusive
return None, "", str(err)
def json_body(body):
try:
parsed = json.loads(body)
except ValueError:
return {}
return parsed if isinstance(parsed, dict) else {}
def check_github(username, org, token):
if not token:
return "ERROR", "GITHUB_TOKEN secret is empty"
url = "https://api.github.com/orgs/%s/members/%s" % (
urllib.parse.quote(org), urllib.parse.quote(username))
status, _body, error = http_request("GET", url, {
"Authorization": "Bearer " + token,
"Accept": "application/vnd.github+json",
"User-Agent": "kestra-leaver-gate",
})
if error is not None:
return "ERROR", error
if status == 204:
return "FAIL", "still a member of org " + org
if status == 404:
return "PASS", "not a member of org " + org
return "ERROR", "unexpected GitHub status %s" % status
def check_slack(email, token):
if not token:
return "ERROR", "SLACK_TOKEN secret is empty"
url = "https://slack.com/api/users.lookupByEmail?email=" + urllib.parse.quote(email)
status, body, error = http_request("GET", url, {
"Authorization": "Bearer " + token,
})
if error is not None or status != 200:
return "ERROR", error or ("unexpected Slack status %s" % status)
data = json_body(body)
if data.get("ok") is False and data.get("error") == "users_not_found":
return "PASS", "no Slack user for this email"
if data.get("ok") is True:
user = data.get("user") or {}
if user.get("deleted") is True:
return "PASS", "Slack user is deactivated"
return "FAIL", "Slack user still active"
return "ERROR", "unexpected Slack response: " + data.get("error", "unknown")
def check_google(email, token):
if not token:
return "ERROR", "GOOGLE_TOKEN secret is empty"
url = "https://admin.googleapis.com/admin/directory/v1/users/" + urllib.parse.quote(email)
status, body, error = http_request("GET", url, {
"Authorization": "Bearer " + token,
})
if error is not None:
return "ERROR", error
if status == 404:
return "PASS", "no Google Workspace user for this email"
if status == 200:
data = json_body(body)
if data.get("suspended") is True:
return "PASS", "Google Workspace user is suspended"
return "FAIL", "Google Workspace user still active"
return "ERROR", "unexpected Google status %s" % status
def sign_iam_request(username, region, access_key, secret_key):
now = datetime.now(timezone.utc)
amz_date = now.strftime("%Y%m%dT%H%M%SZ")
date_stamp = now.strftime("%Y%m%d")
params = {
"Action": "GetLoginProfile",
"UserName": username,
"Version": "2010-05-08",
}
query = "&".join("%s=%s" % (key, urllib.parse.quote(params[key], safe=""))
for key in sorted(params))
canonical_headers = "host:iam.amazonaws.com\nx-amz-date:%s\n" % amz_date
payload_hash = hashlib.sha256(b"").hexdigest()
canonical_request = "\n".join([
"GET", "/", query, canonical_headers,
"host;x-amz-date", payload_hash,
])
scope = "%s/%s/iam/aws4_request" % (date_stamp, region)
string_to_sign = "\n".join([
"AWS4-HMAC-SHA256", amz_date, scope,
hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
])
def sign(key, message):
return hmac.new(key, message.encode("utf-8"), hashlib.sha256).digest()
signing_key = sign(("AWS4" + secret_key).encode("utf-8"), date_stamp)
signing_key = sign(signing_key, region)
signing_key = sign(signing_key, "iam")
signing_key = sign(signing_key, "aws4_request")
signature = hmac.new(signing_key, string_to_sign.encode("utf-8"),
hashlib.sha256).hexdigest()
auth = ("AWS4-HMAC-SHA256 Credential=%s/%s, "
"SignedHeaders=host;x-amz-date, Signature=%s") % (
access_key, scope, signature)
return ("https://iam.amazonaws.com/?" + query,
{"Authorization": auth, "X-Amz-Date": amz_date})
def check_aws_iam(username, region, access_key, secret_key):
if not access_key or not secret_key:
return "ERROR", "AWS access key secrets are empty"
url, headers = sign_iam_request(username, region, access_key, secret_key)
status, body, error = http_request("GET", url, headers)
if error is not None:
return "ERROR", error
if status == 200 and "<LoginProfile>" in body:
return "FAIL", "IAM login profile still exists"
if "NoSuchEntity" in body:
return "PASS", "no IAM login profile for this user"
return "ERROR", "unexpected IAM status %s" % status
username = os.environ.get("LEAVER_USERNAME", "")
email = os.environ.get("LEAVER_EMAIL", "")
org = os.environ.get("GITHUB_ORG", "")
region = os.environ.get("AWS_REGION", "us-east-1")
try:
wanted = json.loads(os.environ.get("SYSTEMS_JSON", "[]"))
except ValueError:
wanted = []
if not isinstance(wanted, list):
wanted = []
fail_on_inconclusive = os.environ.get("FAIL_ON_INCONCLUSIVE", "true") == "true"
checks = {
"github": lambda: check_github(username, org, os.environ.get("GITHUB_TOKEN", "")),
"slack": lambda: check_slack(email, os.environ.get("SLACK_TOKEN", "")),
"google-workspace": lambda: check_google(email, os.environ.get("GOOGLE_TOKEN", "")),
"aws-iam": lambda: check_aws_iam(username, region,
os.environ.get("AWS_ACCESS_KEY_ID", ""),
os.environ.get("AWS_SECRET_ACCESS_KEY", "")),
}
evidence = []
for name in ("github", "slack", "google-workspace", "aws-iam"):
if name not in wanted:
evidence.append({"system": name, "status": "SKIPPED",
"detail": "not in the systems input"})
continue
status, detail = checks[name]()
evidence.append({"system": name, "status": status, "detail": detail})
failing = [row for row in evidence if row["status"] == "FAIL"]
inconclusive = [row for row in evidence if row["status"] == "ERROR"]
if failing:
verdict = "BLOCKED"
elif inconclusive and fail_on_inconclusive:
verdict = "BLOCKED"
elif inconclusive:
verdict = "INCONCLUSIVE"
else:
verdict = "PASS"
print("leaver=%s verdict=%s failing=%d inconclusive=%d" % (
username, verdict, len(failing), len(inconclusive)))
print("::" + json.dumps({"outputs": {
"verdict": verdict,
"residual_count": len(failing),
"inconclusive_count": len(inconclusive),
"evidence": evidence,
}}) + "::")
- id: alert_on_residual
type: io.kestra.plugin.core.flow.If
description: Alert Security whenever the gate does not pass, naming the verdict
and the evidence record, so a blocked sign-off is visible instead of
silent. When every checked system passes, record the clean result in the
execution log.
condition: "{{ outputs.run_system_checks.vars.verdict != 'PASS' }}"
then:
- id: alert_security
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the security channel the leaver sign-off is blocked, with the
verdict, the residual count and the full per-system evidence record.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Leaver gate BLOCKED for {{ inputs.leaver_username }} ({{ inputs.leaver_email }}): verdict {{ outputs.run_system_checks.vars.verdict }}, {{ outputs.run_system_checks.vars.residual_count }} system(s) still admit the leaver, {{ outputs.run_system_checks.vars.inconclusive_count }} inconclusive. Evidence: {{ outputs.run_system_checks.vars.evidence | toJson }}. Execution {{ execution.id }}. Do not sign off offboarding until every system passes."
}
- id: fail_when_blocked
type: io.kestra.plugin.core.flow.If
description: Fail the execution when the gate is BLOCKED, so residual access can
never read as a passing run. An INCONCLUSIVE verdict with
fail_on_inconclusive set to false only alerts, by operator choice.
condition: "{{ outputs.run_system_checks.vars.verdict == 'BLOCKED' }}"
then:
- id: fail_gate
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so a leaver with residual access is never signed
off by a green run.
errorMessage: "Leaver gate BLOCKED for {{ inputs.leaver_username }}: {{
outputs.run_system_checks.vars.residual_count }} system(s) still
admit the leaver. See the Slack alert and the evidence record.
Sign-off requires verdict PASS."
else:
- id: log_gate_clear
type: io.kestra.plugin.core.log.Log
description: Record the clean result so the execution history proves every
checked system was verified gone for this leaver.
message: "Leaver gate clear for {{ inputs.leaver_username }}: verdict {{
outputs.run_system_checks.vars.verdict }}, 0 residual systems,
evidence {{ outputs.run_system_checks.vars.evidence | toJson }}."
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure of the gate itself to the security channel,
because a gate that dies silently looks exactly like a clean leaver.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "FAILED: leaver gate {{ flow.id }} execution {{ execution.id }} for {{ inputs.leaver_username }}. The gate did not complete, so offboarding sign-off stays blocked until it is re-run."
}
outputs:
- id: verdict
type: STRING
description: PASS when every checked system proves the leaver gone, BLOCKED when
any system still admits the leaver or (with fail_on_inconclusive) cannot
be checked, INCONCLUSIVE when only uncheckable systems remain and
fail_on_inconclusive is false.
value: "{{ outputs.run_system_checks.vars.verdict }}"
- id: residual_count
type: INT
description: Number of systems that still admit the leaver. Sign-off requires zero.
value: "{{ outputs.run_system_checks.vars.residual_count }}"