Skip to content

Multipart, Object Lock and STS

Multipart uploads, retention and legal hold, and temporary credentials.
Note

Multipart uploads, S3 bucket notifications and IAM service accounts are Supported MVP features. Object Lock (retention and legal hold), the silo_api SQL transactional outbox and Basic AssumeRole STS are Preview features.

This tutorial covers five multi-step workflows: multipart uploads with failure cleanup, Object Lock retention and legal hold, S3 bucket webhook notifications, a transactional SQL outbox committed with an object, and service accounts / Basic AssumeRole STS credentials. Complete Use an S3 SDK first.

Multipart uploads and failure cleanup

Every multipart part except the final part must be at least 5 MiB, and the assembled object must fit within the store’s maximum object size (256 MiB by default, up to 1 GiB if configured at initialization).

The script below uploads a 5 MiB part and a short final part, lists the uploaded parts, completes the upload in part-number order, and aborts the upload in finally if completion did not succeed:

import os
import boto3
from botocore.config import Config

session = boto3.Session(profile_name="silo-admin", region_name="us-east-1")
s3 = session.client(
    "s3",
    endpoint_url=os.environ["SILO_ENDPOINT"],
    verify=os.environ["AWS_CA_BUNDLE"],
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)

bucket, key = "attachments", "workflows/multipart.bin"
chunks = [b"A" * (5 * 1024 * 1024), b"last part\n"]
upload_id = s3.create_multipart_upload(Bucket=bucket, Key=key)["UploadId"]
completed = False
try:
    parts = []
    for number, chunk in enumerate(chunks, start=1):
        part = s3.upload_part(
            Bucket=bucket, Key=key, UploadId=upload_id, PartNumber=number, Body=chunk
        )
        parts.append({"PartNumber": number, "ETag": part["ETag"]})
    listed = s3.list_parts(Bucket=bucket, Key=key, UploadId=upload_id)
    assert [p["PartNumber"] for p in listed["Parts"]] == [1, 2]
    s3.complete_multipart_upload(
        Bucket=bucket, Key=key, UploadId=upload_id, MultipartUpload={"Parts": parts}
    )
    completed = True
finally:
    if not completed:
        s3.abort_multipart_upload(Bucket=bucket, Key=key, UploadId=upload_id)

response = s3.get_object(Bucket=bucket, Key=key)
try:
    assert response["Body"].read() == b"".join(chunks)
    print("Multipart upload verified")
finally:
    response["Body"].close()

In addition to s3:PutObject and s3:GetObject, application policies need s3:AbortMultipartUpload for cleanup and s3:ListMultipartUploadParts to list parts (plus s3:ListBucketMultipartUploads to list active uploads in a bucket). Because a process crash can skip finally, also configure an AbortIncompleteMultipartUpload lifecycle rule (see Versioning).

Object Lock, retention and legal hold

Enabling Object Lock when creating a bucket also enables versioning. The script below creates lock-demo with 1 day of default GOVERNANCE retention, writes a version, extends its retention to 2 days, enables legal hold, verifies that deleting the version returns AccessDenied, and then clears the legal hold:

import base64
import hashlib
import os
from datetime import datetime, timedelta, timezone
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError

session = boto3.Session(profile_name="silo-admin", region_name="us-east-1")
s3 = session.client(
    "s3",
    endpoint_url=os.environ["SILO_ENDPOINT"],
    verify=os.environ["AWS_CA_BUNDLE"],
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)

bucket, key = "lock-demo", "retained.txt"
s3.create_bucket(Bucket=bucket, ObjectLockEnabledForBucket=True)
s3.put_object_lock_configuration(
    Bucket=bucket,
    ObjectLockConfiguration={
        "ObjectLockEnabled": "Enabled",
        "Rule": {"DefaultRetention": {"Mode": "GOVERNANCE", "Days": 1}},
    },
)
body = b"retain this version\n"
created = s3.put_object(
    Bucket=bucket,
    Key=key,
    Body=body,
    ContentMD5=base64.b64encode(hashlib.md5(body, usedforsecurity=False).digest()).decode("ascii"),
)
version = created["VersionId"]
s3.put_object_retention(
    Bucket=bucket,
    Key=key,
    VersionId=version,
    Retention={
        "Mode": "GOVERNANCE",
        "RetainUntilDate": datetime.now(timezone.utc) + timedelta(days=2),
    },
)
s3.put_object_legal_hold(
    Bucket=bucket, Key=key, VersionId=version, LegalHold={"Status": "ON"}
)
print(s3.get_object_retention(Bucket=bucket, Key=key, VersionId=version)["Retention"])
print(s3.get_object_legal_hold(Bucket=bucket, Key=key, VersionId=version)["LegalHold"])
try:
    s3.delete_object(Bucket=bucket, Key=key, VersionId=version)
except ClientError as error:
    if error.response["Error"]["Code"] != "AccessDenied":
        raise
    print("Protected version deletion denied")
else:
    raise AssertionError("Protected version was unexpectedly deleted")
s3.put_object_legal_hold(
    Bucket=bucket, Key=key, VersionId=version, LegalHold={"Status": "OFF"}
)

Calling delete_object without VersionId creates a delete marker without removing the protected version. Bypassing GOVERNANCE retention requires the explicit bypass header and s3:BypassGovernanceRetention; active COMPLIANCE retention cannot be bypassed. The silo_api SQL interface enforces retention and legal hold on mutations and provides no governance bypass.

S3 bucket event notifications

To send S3 request-path events to an HTTPS webhook receiver, configure the same webhook target ID (APP) in /etc/default/silo on every writable gateway and restart the gateways:

MINIO_NOTIFY_WEBHOOK_ENABLE_APP="on"
MINIO_NOTIFY_WEBHOOK_ENDPOINT_APP="https://events.example.net/silo"
MINIO_NOTIFY_WEBHOOK_AUTH_TOKEN_APP="REPLACE_WITH_RECEIVER_TOKEN"

Then attach a notification rule using the QueueArn arn:minio:sqs:<region>:<target-id>:webhook:

import os
import boto3
from botocore.config import Config

session = boto3.Session(profile_name="silo-admin", region_name="us-east-1")
s3 = session.client(
    "s3",
    endpoint_url=os.environ["SILO_ENDPOINT"],
    verify=os.environ["AWS_CA_BUNDLE"],
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)

bucket = "notification-demo"
s3.create_bucket(Bucket=bucket)
s3.put_bucket_notification_configuration(
    Bucket=bucket,
    NotificationConfiguration={
        "QueueConfigurations": [
            {
                "Id": "application-events",
                "QueueArn": "arn:minio:sqs:us-east-1:APP:webhook",
                "Events": ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"],
                "Filter": {"Key": {"FilterRules": [{"Name": "suffix", "Value": ".txt"}]}},
            }
        ],
    },
)
s3.put_object(Bucket=bucket, Key="event.txt", Body=b"notification example\n")
s3.delete_object(Bucket=bucket, Key="event.txt")

S3 webhook delivery runs asynchronously after S3 HTTP requests commit; receivers must tolerate retries and duplicates. Direct SQL writes through silo_api do not trigger S3 bucket notifications.

Commit an SQL outbox with the object

When an event must commit or roll back atomically with a business row and an object, write to an application-owned outbox table in the same Read Committed SQL transaction (continuing the app_sql setup from Objects from SQL):

CREATE TABLE app_demo.outbox (
  event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  event_type text NOT NULL,
  payload jsonb NOT NULL,
  created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  delivered_at timestamptz
);

BEGIN ISOLATION LEVEL READ COMMITTED;
WITH written AS (
  SELECT * FROM silo_api.put_object(
    'attachments', 'invoices/1003.txt',
    convert_to('invoice 1003 amount 399.00', 'UTF8'), 'text/plain'
  )
), invoice AS (
  INSERT INTO app_demo.invoices
    (invoice_id, object_key, object_id, object_version, amount)
  SELECT 1003, 'invoices/1003.txt', object_id, version_id, 399.00 FROM written
  RETURNING invoice_id, object_key, object_version
)
INSERT INTO app_demo.outbox (event_type, payload)
SELECT 'invoice.ready', jsonb_build_object(
  'invoice_id', invoice_id, 'bucket', 'attachments',
  'key', object_key, 'version_id', object_version
) FROM invoice;
COMMIT;

An application worker polls app_demo.outbox, delivers the event idempotently by event_id, and sets delivered_at.

Service accounts and temporary STS identities

To issue a scoped service account under app-s3 without sharing the parent user’s secret key:

(
  umask 077
  set -o noclobber
  mcli_pg --json admin user svcacct add pg-admin app-s3 --name attachments-service > "$SILO_CLIENT_CONFIG/attachments-service.json"
)
mcli_pg admin user svcacct list pg-admin app-s3

To request 15-minute (900-second) temporary credentials over Basic AssumeRole STS, sign AssumeRole with an ordinary IAM user (silo-app). Service accounts and existing STS credentials cannot call Basic AssumeRole, and lifetimes below 900 seconds are rejected:

import json
import os
import boto3
from botocore.config import Config

parent = boto3.Session(profile_name="silo-app", region_name="us-east-1")
endpoint, ca = os.environ["SILO_ENDPOINT"], os.environ["AWS_CA_BUNDLE"]
sts = parent.client(
    "sts", endpoint_url=endpoint, verify=ca, config=Config(signature_version="v4")
)
limited_policy = {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["s3:GetObject"],
            "Resource": ["arn:aws:s3:::attachments/sdk.txt"],
        }
    ],
}
credentials = sts.assume_role(
    RoleArn="arn:aws:iam::123456789012:role/silo-session",
    RoleSessionName="read-sdk-object",
    DurationSeconds=900,
    Policy=json.dumps(limited_policy),
)["Credentials"]
temporary = boto3.client(
    "s3",
    endpoint_url=endpoint,
    region_name="us-east-1",
    verify=ca,
    aws_access_key_id=credentials["AccessKeyId"],
    aws_secret_access_key=credentials["SecretAccessKey"],
    aws_session_token=credentials["SessionToken"],
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
response = temporary.get_object(Bucket="attachments", Key="sdk.txt")
try:
    print(response["Body"].read().decode("utf-8"))
finally:
    response["Body"].close()
print("Expires:", credentials["Expiration"].isoformat())

The inline session Policy further narrows the parent user’s effective permissions; it never expands them. RoleArn is accepted for S3/STS wire compatibility and does not reference an external AWS IAM role.

Scan to open this page
https://mimus.pgsty.com/docs/s3/tutorial/workflows/