id: s3-approved-deleted-object-recovery
namespace: company.infrastructure
inputs:
- id: bucket
type: STRING
- id: key
type: STRING
description: Exact object key, not a prefix.
- id: version_id
type: STRING
description: Explicit data version to restore; never select a version automatically.
- id: region
type: STRING
defaults: us-east-1
- id: endpoint_url
type: STRING
defaults: ""
description: Leave empty for AWS. Compatible services must enforce conditional
PutObject.
concurrency:
limit: 1
behavior: QUEUE
tasks:
- id: inspect
type: io.kestra.plugin.scripts.python.Script
description: Read the selected version and save a bounded, SHA256-fingerprinted
recovery plan.
containerImage: python:3.13-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
beforeCommands:
- pip install --disable-pip-version-check boto3==1.43.115
env:
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
AWS_DEFAULT_REGION: "{{ inputs.region }}"
S3_ENDPOINT: "{{ inputs.endpoint_url }}"
BUCKET: "{{ inputs.bucket }}"
OBJECT_KEY: "{{ inputs.key }}"
VERSION_ID: "{{ inputs.version_id }}"
outputFiles:
- recovery-plan.json
- source.bin
- put-request.json
script: |
import hashlib
import json
import os
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
s3 = boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT") or None,
config=Config(s3={"addressing_style": "path"}))
bucket, key, version = (os.environ[k] for k in ("BUCKET", "OBJECT_KEY", "VERSION_ID"))
if not bucket or not key or not version or version == "null":
raise ValueError("Provide an exact bucket, key and non-null data version ID")
if s3.get_bucket_versioning(Bucket=bucket).get("Status") != "Enabled":
raise ValueError("Bucket versioning must be Enabled")
try:
s3.head_object(Bucket=bucket, Key=key)
except ClientError as error:
headers = error.response.get("ResponseMetadata", {}).get("HTTPHeaders", {})
marker = headers.get("x-amz-version-id")
if (error.response["ResponseMetadata"]["HTTPStatusCode"] != 404
or headers.get("x-amz-delete-marker") != "true" or not marker
or marker == "null"):
raise ValueError("Current version must be a versioned delete marker") from error
else:
raise ValueError("Object already exists; refusing to replace live data")
source = s3.get_object(Bucket=bucket, Key=key, VersionId=version)
with source["Body"] as body, open("source.bin", "wb") as snapshot:
size = source["ContentLength"]
if size > 32 * 1024 * 1024:
raise ValueError("This single-object recovery is limited to 32 MiB")
digest = hashlib.sha256()
read = 0
for chunk in iter(lambda: body.read(1024 * 1024), b""):
read += len(chunk)
if read > 32 * 1024 * 1024:
raise ValueError("Source exceeds the recovery size limit")
digest.update(chunk)
snapshot.write(chunk)
if read != size or source.get("VersionId") != version:
raise ValueError("Source version or byte count changed")
plan = {"bucket": bucket, "key": key, "version_id": version,
"delete_marker_id": marker, "size": size, "sha256": digest.hexdigest()}
request = {"Bucket": bucket, "Key": key, "Metadata": source.get("Metadata", {})}
for field in ("ContentType", "CacheControl", "ContentDisposition", "ContentEncoding", "ContentLanguage"):
if field in source:
request[field] = source[field]
with open("put-request.json", "w") as file:
json.dump(request, file)
with open("recovery-plan.json", "w") as file:
json.dump(plan, file, indent=2)
print("Review recovery-plan.json before approving. No object has been written.")
- id: approve
type: io.kestra.plugin.core.flow.Pause
description: Review the plan artifact; approval defaults to false and expires
after one hour.
pauseDuration: PT1H
behavior: FAIL
onResume:
- id: restore
type: BOOL
defaults: false
description: Restore precisely the bucket/key/version shown in recovery-plan.json.
- id: approved
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve.onResume.restore }}"
then:
- id: recheck
type: io.kestra.plugin.scripts.python.Script
description: Refuse a stale approval if the current delete marker changed during
the pause.
containerImage: python:3.13-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
beforeCommands:
- pip install --disable-pip-version-check boto3==1.43.115
env:
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
AWS_DEFAULT_REGION: "{{ inputs.region }}"
S3_ENDPOINT: "{{ inputs.endpoint_url }}"
inputFiles:
plan.json: "{{ outputs.inspect.outputFiles['recovery-plan.json'] }}"
script: |
import json
import os
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
plan = json.load(open("plan.json"))
s3 = boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT") or None,
config=Config(s3={"addressing_style": "path"}))
if s3.get_bucket_versioning(Bucket=plan["bucket"]).get("Status") != "Enabled":
raise ValueError("Bucket versioning changed; start a new recovery")
try:
s3.head_object(Bucket=plan["bucket"], Key=plan["key"])
except ClientError as error:
headers = error.response.get("ResponseMetadata", {}).get("HTTPHeaders", {})
if (error.response["ResponseMetadata"]["HTTPStatusCode"] != 404
or headers.get("x-amz-delete-marker") != "true"
or headers.get("x-amz-version-id") != plan["delete_marker_id"]):
raise ValueError("Delete marker changed; start a new recovery") from error
else:
raise ValueError("Another writer restored the object; refusing to overwrite it")
print("Approved delete marker is still current.")
- id: restore_version
type: io.kestra.plugin.aws.cli.AwsCLI
description: Conditional upload creates a new current version only while the key
is absent.
containerImage: amazon/aws-cli:2.38.2
accessKeyId: "{{ secret('AWS_ACCESS_KEY_ID') }}"
secretKeyId: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
region: "{{ inputs.region }}"
inputFiles:
source.bin: "{{ outputs.inspect.outputFiles['source.bin'] }}"
put-request.json: "{{ outputs.inspect.outputFiles['put-request.json'] }}"
env:
S3_ENDPOINT: "{{ inputs.endpoint_url }}"
AWS_MAX_ATTEMPTS: "1"
AWS_PAGER: ""
outputFiles:
- copy-result.json
commands:
- |
set -eu
if [ -n "$S3_ENDPOINT" ]; then export AWS_ENDPOINT_URL="$S3_ENDPOINT"; fi
aws s3api put-object --cli-input-json file://put-request.json \
--body source.bin --if-none-match '*' \
--query '{version_id:VersionId}' --output json > copy-result.json
printf '::{"outputs":%s}::\n' "$(tr -d '\n' < copy-result.json)"
- id: verify
type: io.kestra.plugin.scripts.python.Script
description: Hash the copied version and verify it is current; save the recovery
receipt.
containerImage: python:3.13-slim
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
beforeCommands:
- pip install --disable-pip-version-check boto3==1.43.115
inputFiles:
plan.json: "{{ outputs.inspect.outputFiles['recovery-plan.json'] }}"
env:
AWS_ACCESS_KEY_ID: "{{ secret('AWS_ACCESS_KEY_ID') }}"
AWS_SECRET_ACCESS_KEY: "{{ secret('AWS_SECRET_ACCESS_KEY') }}"
AWS_DEFAULT_REGION: "{{ inputs.region }}"
S3_ENDPOINT: "{{ inputs.endpoint_url }}"
RESTORED_VERSION: "{{ outputs.restore_version.vars.version_id }}"
outputFiles:
- recovery-receipt.json
script: |
import hashlib
import json
import os
import boto3
from botocore.config import Config
plan = json.load(open("plan.json"))
version = os.environ["RESTORED_VERSION"]
if not version or version in ("null", "None", plan["version_id"], plan["delete_marker_id"]):
raise ValueError("Upload did not return a new, non-null version ID")
s3 = boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT") or None,
config=Config(s3={"addressing_style": "path"}))
restored = s3.get_object(Bucket=plan["bucket"], Key=plan["key"], VersionId=version)
digest = hashlib.sha256()
size = 0
with restored["Body"] as body:
for chunk in iter(lambda: body.read(1024 * 1024), b""):
size += len(chunk)
if size > 32 * 1024 * 1024:
raise ValueError("Restored version exceeds recovery size limit")
digest.update(chunk)
if size != plan["size"] or digest.hexdigest() != plan["sha256"]:
raise ValueError("Restored content differs from the approved source")
current = s3.head_object(Bucket=plan["bucket"], Key=plan["key"])
if current.get("VersionId") != version:
raise ValueError("Another writer changed the current object after recovery")
receipt = {**plan, "restored_version_id": version, "verified": True}
with open("recovery-receipt.json", "w") as file:
json.dump(receipt, file, indent=2)
print("Restored version is current and its SHA256 matches the approved source.")
else:
- id: declined
type: io.kestra.plugin.core.log.Log
message: Recovery declined. No object was written.
outputs:
- id: plan
type: FILE
required: false
value: "{{ outputs.inspect.outputFiles['recovery-plan.json'] ?? null }}"
- id: receipt
type: FILE
required: false
value: "{{ outputs.verify.outputFiles['recovery-receipt.json'] ?? null }}"
triggers:
- id: recovery_request
type: io.kestra.plugin.core.trigger.Webhook
key: "{{ secret('S3_RECOVERY_WEBHOOK_KEY') }}"
inputs:
bucket: "{{ trigger.body.bucket }}"
key: "{{ trigger.body.key }}"
version_id: "{{ trigger.body.version_id }}"
region: "{{ trigger.body.region ?? 'us-east-1' }}"
endpoint_url: "{{ trigger.body.endpoint_url ?? '' }}"