Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Tutorials

SQL access, SDKs, versioning, encryption, annotations and multi-step S3 workflows.

Complete the Quick start first. Keep the silo database, the attachments bucket, the app-s3 user and the trusted gateway CA certificate for these tutorials.

TutorialScope
Objects from SQLCommit or roll back objects together with business rows; grant silo_api and silo_bucket permissions; paginate and stream segments (Preview)
Use an S3 SDKConnect AWS CLI, boto3 and browsers with presigned URLs and bucket CORS
VersioningEnable versioning, read historical versions, and configure lifecycle rules and hard bucket quotas
EncryptionConfigure static-key SSE-S3, use client-held SSE-C keys, and understand key recovery and SQL boundaries
Annotations and ZIPAttach UTF-8 annotations to object versions and read or list ZIP archive members with SigV4 requests (Preview)
Multipart, Object Lock and STSUpload parts with cleanup, apply retention and legal hold, deliver bucket notifications or SQL outbox events, and issue service accounts or STS credentials

Use the root account only for administration. Use restricted IAM policies for S3 applications, and manage PostgreSQL login roles separately from S3 access keys.

1 - Objects from SQL

Write and read objects inside a PostgreSQL transaction with silo_api.
Note

The SQL transaction API (silo_api) and PostgreSQL native authorization (silo_bucket) are Preview features in the MVP scope.

This tutorial writes an invoice row and its attachment in one PostgreSQL transaction, verifies both from SQL and S3, rolls back a second transaction, and reads paginated lists and object segments. Complete the Quick start first so the silo database and plaintext attachments bucket exist.

Create an application SQL role

Connect to silo as a database administrator and create an unprivileged login role (app_sql) and application schema (app_demo):

CREATE ROLE app_sql LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
\password app_sql
CREATE SCHEMA app_demo AUTHORIZATION app_sql;

The application role needs no superuser rights, no membership in silo_owner, and no direct access to the private silo schema.

Next, connect to silo as the installation owner (silo_owner) and grant EXECUTE on the required silo_api functions plus SELECT and INSERT on the ACL relation for attachments:

GRANT USAGE ON SCHEMA silo_api, silo_bucket TO app_sql;
GRANT EXECUTE ON FUNCTION
  silo_api.put_object(text,text,bytea,text,jsonb,boolean,text),
  silo_api.get_object(text,text,uuid),
  silo_api.stat_object(text,text,uuid),
  silo_api.read_object(text,text,bigint,bigint,uuid,bigint),
  silo_api.list_objects(text,text,text,integer)
TO app_sql;
SELECT format('GRANT SELECT, INSERT ON TABLE %I.%I TO %I',
              n.nspname, c.relname, 'app_sql')
FROM silo.bucket_acl AS a
JOIN silo.buckets AS b ON b.id = a.bucket_id
JOIN pg_catalog.pg_class AS c ON c.oid = a.relation_oid
JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace
WHERE b.name = 'attachments' AND n.nspname = 'silo_bucket' \gexec

In psql, \gexec executes the generated GRANT statement. Because a bucket’s ACL relation name in silo_bucket is decoupled from the bucket name, silo_owner looks it up through silo.bucket_acl. See Authorization for the complete permission mapping.

Reconnect as app_sql and create the business table:

psql 'host=pg.example.net port=5432 dbname=silo user=app_sql sslmode=verify-full sslrootcert=/path/to/pg-ca.crt' -W
\set ON_ERROR_STOP on
SELECT session_user, current_user;
CREATE TABLE app_demo.invoices (
    invoice_id bigint PRIMARY KEY,
    object_key text NOT NULL,
    object_id bigint NOT NULL,
    object_version uuid,
    amount numeric(12,2) NOT NULL
);

silo_api checks the login-time session_user and rejects SET ROLE impersonation.

Commit a business row and object together

In the app_sql session, write an object and insert the referencing invoice row in one Read Committed transaction:

BEGIN ISOLATION LEVEL READ COMMITTED;
WITH written AS (
  SELECT * FROM silo_api.put_object(
    'attachments', 'invoices/1001.txt',
    convert_to('invoice 1001 amount 199.00', 'UTF8'),
    'text/plain', '{"invoice_id":"1001"}'::jsonb
  )
)
INSERT INTO app_demo.invoices
  (invoice_id, object_key, object_id, object_version, amount)
SELECT 1001, 'invoices/1001.txt', object_id, version_id, 199.00
FROM written;
COMMIT;

Read the committed object body and metadata from SQL:

SELECT convert_from(
  silo_api.get_object('attachments', 'invoices/1001.txt'), 'UTF8'
);
SELECT i.invoice_id, i.amount, o.object_id, o.version_id, o.size, o.etag
FROM app_demo.invoices AS i
CROSS JOIN LATERAL silo_api.stat_object('attachments', i.object_key) AS o
WHERE i.invoice_id = 1001;

Read the same object over S3:

mcli_pg cat pg-app/attachments/invoices/1001.txt

get_object returns bytea. Use convert_from only when the payload is known UTF-8 text.

Roll back a business row and object together

Start a second transaction, write both the object and the invoice row, and roll back:

BEGIN ISOLATION LEVEL READ COMMITTED;
WITH written AS (
  SELECT * FROM silo_api.put_object(
    'attachments', 'invoices/1002.txt',
    convert_to('this invoice will be rolled back', 'UTF8'), 'text/plain'
  )
)
INSERT INTO app_demo.invoices
  (invoice_id, object_key, object_id, object_version, amount)
SELECT 1002, 'invoices/1002.txt', object_id, version_id, 299.00
FROM written;
ROLLBACK;
SELECT count(*) FROM app_demo.invoices WHERE invoice_id = 1002;
SELECT count(*) FROM silo_api.list_objects('attachments', 'invoices/1002.txt');

Both counts return 0. Neither the relational row nor the S3 object is published.

If your application needs a permanent reference to an immutable object body, enable bucket versioning and pass the saved version_id when calling get_object, stat_object or read_object. Overwriting an unversioned object replaces its body.

Paginate listings and read segments

List the first page of objects under the invoices/ prefix:

SELECT key, size, etag FROM silo_api.list_objects(
  'attachments', 'invoices/', NULL, 100
);

To fetch the next page, pass the final key of the current page as the third argument (start_after). Each call returns at most 1,000 live objects in C byte order and omits delete markers.

To read a large object in bounded chunks without materializing the full body in one call, open a read-only Repeatable Read snapshot and call read_object:

BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT object_id, version_id, offset_bytes, octet_length(data)
FROM silo_api.read_object('attachments', 'invoices/1001.txt', 0, 8388608);
-- Advance offset_bytes on subsequent calls within the same transaction.
COMMIT;

read_object returns at most 8 MiB (8388608 bytes) per call. Use REPEATABLE READ only for read-only transactions; SQL writes through silo_api require READ COMMITTED.

Direct SQL writes do not emit S3 bucket notifications. To publish events atomically with SQL object writes, insert into a transactional outbox table in the same transaction; see Multipart, Object Lock and STS and the SQL API reference.

2 - Use an S3 SDK

Connect AWS SDKs and mc-compatible clients to the gateway.

This tutorial connects the AWS CLI and the Python SDK (boto3) to a Silo PostgreSQL gateway, generates a presigned download URL, and configures bucket CORS for browser requests. Complete the Quick start first so the attachments bucket, app-s3 user and local hello.txt file exist.

Set the endpoint and working directory in your terminal:

export SILO_ENDPOINT='https://s3.example.net:9000'
export SILO_TUTORIAL_DIR="$HOME/.local/share/silo-tutorial/files"
export AWS_CA_BUNDLE='/path/to/s3-ca.crt'

AWS CLI and Python SDK

Configure an AWS CLI profile (silo-app) with the app-s3 credentials, region us-east-1 and path-style addressing:

aws configure --profile silo-app
aws configure set s3.addressing_style path --profile silo-app
aws --profile silo-app --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api list-objects-v2 --bucket attachments
aws --profile silo-app --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3 cp "$SILO_TUTORIAL_DIR/hello.txt" s3://attachments/hello.txt

Create a Python 3.10+ virtual environment and install boto3:

python3 -m venv "$HOME/.local/share/silo-tutorial/venv"
"$HOME/.local/share/silo-tutorial/venv/bin/pip" install 'boto3==1.43.108' 'botocore==1.43.108'

Save the following script as ~/.local/share/silo-tutorial/sdk.py:

import os
import boto3
from botocore.config import Config

session = boto3.Session(profile_name="silo-app", 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"}),
)
s3.put_object(Bucket="attachments", Key="sdk.txt", Body=b"hello from Python\n")
response = s3.get_object(Bucket="attachments", Key="sdk.txt")
try:
    print(response["Body"].read().decode("utf-8"))
finally:
    response["Body"].close()

Run "$HOME/.local/share/silo-tutorial/venv/bin/python" "$HOME/.local/share/silo-tutorial/sdk.py". It prints hello from Python.

Keep default SDK checksums and TLS verification enabled. When uploading larger files with SDK multipart helpers, the completed object must fit within the store’s maximum object size (256 MiB by default, up to 1 GiB if configured at initialization).

Presigned URLs and bucket CORS

Generate a presigned GET URL valid for 15 minutes (900 seconds) using the s3 client from above:

url = s3.generate_presigned_url(
    "get_object", Params={"Bucket": "attachments", "Key": "sdk.txt"}, ExpiresIn=900
)
print(url)

A presigned URL carries the signing principal’s permissions and cannot grant access that the signer lacks. If signed by temporary STS credentials, the URL stops working when the session expires even if ExpiresIn is longer.

To allow browser uploads or downloads from another origin, configure a bucket CORS rule with an administrative profile (silo-admin):

aws configure --profile silo-admin
aws configure set s3.addressing_style path --profile silo-admin
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-bucket-cors \
  --bucket attachments \
  --cors-configuration '{"CORSRules":[{"AllowedOrigins":["https://app.example.net"],"AllowedMethods":["GET","PUT","HEAD"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag"],"MaxAgeSeconds":600}]}'
curl --cacert "$AWS_CA_BUNDLE" -i -X OPTIONS "$SILO_ENDPOINT/attachments/cors-demo.txt" \
  -H 'Origin: https://app.example.net' \
  -H 'Access-Control-Request-Method: PUT' \
  -H 'Access-Control-Request-Headers: content-type'

A matching preflight request returns the allowed origin and methods in the response headers; a rejected preflight returns HTTP 403 (AccessForbidden). CORS headers do not bypass SigV4 signing or IAM authorization.

3 - Versioning

Enable versioning, read old versions and work with delete markers.
Note

Bucket versioning is a Supported MVP feature. Lifecycle rules, Object Lock and hard bucket quotas described in the second half of this page are Preview features.

This tutorial enables bucket versioning, writes multiple versions of an object, reads a historical version by VersionId, and configures lifecycle expiration and a hard bucket quota. Use the silo-admin profile and mcli_pg alias from the Quick start and Use an S3 SDK.

Retain and read historical versions

Create a dedicated version-demo bucket, enable versioning, write two versions of note.txt, and fetch the first version by its VersionId:

aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api create-bucket --bucket version-demo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-bucket-versioning \
  --bucket version-demo --versioning-configuration Status=Enabled
printf 'version one\n' > "$SILO_TUTORIAL_DIR/version-one.txt"
printf 'version two\n' > "$SILO_TUTORIAL_DIR/version-two.txt"
SILO_VERSION_1="$(aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-object \
  --bucket version-demo --key note.txt --body "$SILO_TUTORIAL_DIR/version-one.txt" --query VersionId --output text)"
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-object \
  --bucket version-demo --key note.txt --body "$SILO_TUTORIAL_DIR/version-two.txt"
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api list-object-versions --bucket version-demo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api get-object \
  --bucket version-demo --key note.txt --version-id "$SILO_VERSION_1" "$SILO_TUTORIAL_DIR/version-one.download.txt"
cmp "$SILO_TUTORIAL_DIR/version-one.txt" "$SILO_TUTORIAL_DIR/version-one.download.txt"

In a versioned bucket, calling delete-object without --version-id inserts a delete marker while preserving prior versions. Permanently deleting a specific version requires passing --version-id and holding s3:DeleteObjectVersion. Reading a historical version requires s3:GetObjectVersion.

Suspending versioning (Status=Suspended) switches new writes to null-version semantics without deleting existing historical versions.

Lifecycle rules and bucket quotas

Create a lifecycle-demo bucket and apply a lifecycle rule that expires current objects under tmp/ after 7 days and aborts incomplete multipart uploads after 1 day:

aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api create-bucket --bucket lifecycle-demo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-bucket-lifecycle-configuration \
  --bucket lifecycle-demo \
  --lifecycle-configuration '{"Rules":[{"ID":"temporary-files","Status":"Enabled","Filter":{"Prefix":"tmp/"},"Expiration":{"Days":7},"AbortIncompleteMultipartUpload":{"DaysAfterInitiation":1}}]}'

A background worker on a writable gateway scans for eligible objects under a database lease. Expiring historical versions requires a NoncurrentVersionExpiration rule. Remote storage-class transition rules (Transition / NoncurrentVersionTransition) are not supported and are rejected.

Hard bucket quotas count the committed object bodies and annotations of all live and historical versions (excluding delete markers). Unfinished multipart parts consume physical table space immediately, but count toward the logical bucket quota only when CompleteMultipartUpload publishes the object:

mcli_pg quota set pg-admin/attachments --size 1GiB
mcli_pg quota info pg-admin/attachments

Deleting versions releases logical quota immediately, whereas physical disk space is reclaimed and reused asynchronously by PostgreSQL VACUUM. See Storage layout for details.

4 - Encryption

SSE-C and static-key SSE-S3, and what they protect.

This tutorial configures static-key SSE-S3 (AES256) on a gateway and bucket, then runs a round-trip write and read with a client-supplied SSE-C customer key. Complete Install and Use an S3 SDK first.

Configure static-key SSE-S3

Generate a 32-byte key file once on the gateway host (refusing to overwrite an existing key file):

sudo sh -c 'set -eu; umask 027; test ! -e /etc/silo/kms.key; set -C; { printf "silo-key-1:"; openssl rand -base64 32; } > /etc/silo/kms.key; chown root:silo /etc/silo/kms.key; chmod 0640 /etc/silo/kms.key'

Back up the exact key ID (silo-key-1) and raw key bytes outside the database, and copy the identical /etc/silo/kms.key file to every gateway that connects to this PostgreSQL database.

Add MINIO_KMS_SECRET_KEY_FILE to /etc/default/silo (do not set MINIO_KMS_SECRET_KEY at the same time):

MINIO_KMS_SECRET_KEY_FILE="/etc/silo/kms.key"

Restart the gateway, enable default AES256 encryption on a new encrypted-demo bucket, and verify an encrypted upload and download:

sudo systemctl restart silo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api create-bucket --bucket encrypted-demo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-bucket-encryption \
  --bucket encrypted-demo \
  --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-object \
  --bucket encrypted-demo --key hello.txt --body "$SILO_TUTORIAL_DIR/hello.txt"
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api get-object \
  --bucket encrypted-demo --key hello.txt "$SILO_TUTORIAL_DIR/encrypted.download.txt"
cmp "$SILO_TUTORIAL_DIR/hello.txt" "$SILO_TUTORIAL_DIR/encrypted.download.txt"

If the static key is missing or wrong, encryption and decryption requests fail closed; the gateway never falls back to plaintext. Losing the external key makes encrypted objects in PostgreSQL unrecoverable. See Backup and restore.

External KMS integration and SSE-KMS (aws:kms) are not supported. The silo_api SQL interface cannot decrypt SSE-S3 or SSE-C bodies, and buckets with default encryption reject SQL put_object writes.

Use a client-held SSE-C key

With SSE-C, the client supplies the 32-byte key on every write and read over HTTPS. Save the following script as ~/.local/share/silo-tutorial/sse-c.py:

import base64
import hashlib
import os
from pathlib import Path

import boto3
from botocore.config import Config

key_path = Path.home() / ".local/share/silo-tutorial/sse-c.key"
key_path.parent.mkdir(parents=True, exist_ok=True)
if key_path.exists():
    key = key_path.read_bytes()
else:
    key = os.urandom(32)
    descriptor = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "wb") as output:
        output.write(key)
if len(key) != 32:
    raise ValueError("SSE-C key must contain exactly 32 bytes")

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"}),
)
customer_headers = {
    "SSECustomerAlgorithm": "AES256",
    "SSECustomerKey": base64.b64encode(key).decode("ascii"),
    "SSECustomerKeyMD5": base64.b64encode(
        hashlib.md5(key, usedforsecurity=False).digest()
    ).decode("ascii"),
}
s3.create_bucket(Bucket="customer-key-demo")
s3.put_object(
    Bucket="customer-key-demo",
    Key="private.txt",
    Body=b"protected by a client-held key\n",
    **customer_headers,
)
response = s3.get_object(
    Bucket="customer-key-demo", Key="private.txt", **customer_headers
)
try:
    assert response["Body"].read() == b"protected by a client-held key\n"
    print("SSE-C round trip succeeded")
finally:
    response["Body"].close()

Run "$HOME/.local/share/silo-tutorial/venv/bin/python" "$HOME/.local/share/silo-tutorial/sse-c.py". It prints SSE-C round trip succeeded.

SSE-C requests require verified HTTPS; HTTP SSE-C requests are rejected. Back up the 32 bytes in sse-c.key independently — the gateway’s static SSE-S3 key cannot decrypt SSE-C objects.

5 - Annotations and ZIP

Attach annotations to objects and extract ZIP archives on upload.
Note

Object annotations (?annotation) and ZIP member extraction (x-minio-extract) are Preview features in the MVP scope. Annotations also depend on four silo-pkg policy actions (s3:*ObjectAnnotation*) that have not been published to the public silo-pkg repository yet, and the general Silo Console (2.6.0) does not include an annotation UI.

This tutorial uses SigV4-signed Python requests to write, read, list and delete object annotations, and to list and read members inside an uploaded ZIP archive without unpacking it into separate S3 objects. Complete Use an S3 SDK first.

Interfaces and permissions

An annotation is attached to a specific parent object version. Each annotation body must be valid UTF-8 text between 1 byte and 1 MiB, and each parent version accepts at most 1,000 annotation names. Updating or deleting an annotation leaves the parent object’s body, ETag and Last-Modified timestamp unchanged.

OperationSigV4-signed HTTP requestRequired IAM action
Create or replacePUT /attachments/<key>?annotation=&annotationName=labels.jsons3:PutObjectAnnotation
Read bodyGET /attachments/<key>?annotation=&annotationName=labels.jsons3:GetObjectAnnotation
List namesGET /attachments/<key>?annotation=s3:ListObjectAnnotations
DeleteDELETE /attachments/<key>?annotation=&annotationName=labels.jsons3:DeleteObjectAnnotation

Standard object actions (s3:GetObject, s3:PutObject) do not grant annotation access. Pass versionId in the query string to target a historical version, or x-amz-object-if-match on PUT/DELETE to require a matching parent ETag. Annotation bodies inherit the parent object’s server-side encryption mode.

To read or list members inside a ZIP archive stored as an S3 object, include header x-minio-extract: true:

  • Read or stat a member: GET or HEAD /attachments/demo.zip/readme.txt with x-minio-extract: true.
  • List archive members: GET /attachments?list-type=2&prefix=demo.zip/ with x-minio-extract: true.

ZIP extraction reads directly from the parent object snapshot without persisting member objects or an index table. It supports Store and Deflate compression (plus bounded ZIP64), up to 10,000 central-directory entries, and up to 256 MiB per uncompressed member. Range and partNumber requests on ZIP members are not supported.

Complete Python example

Because standard S3 SDKs do not have built-in methods for ?annotation or x-minio-extract, sign the requests with botocore.auth.SigV4Auth. Save the script below as ~/.local/share/silo-tutorial/extensions.py:

import hashlib
import io
import json
import os
import ssl
import urllib.request
import zipfile
from urllib.parse import quote, urlencode

import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.config import Config

endpoint = os.environ["SILO_ENDPOINT"].rstrip("/")
ca = os.environ["AWS_CA_BUNDLE"]
region = "us-east-1"
session = boto3.Session(profile_name="silo-admin", region_name=region)
credentials = session.get_credentials().get_frozen_credentials()
context = ssl.create_default_context(cafile=ca)

def signed_request(method, key, query=None, body=None, headers=None):
    url = endpoint + "/attachments/" + quote(key, safe="/")
    if query is not None:
        url += "?" + urlencode(query)
    request_headers = dict(headers or {})
    request_headers["x-amz-content-sha256"] = hashlib.sha256(body or b"").hexdigest()
    signed = AWSRequest(method=method, url=url, data=body, headers=request_headers)
    SigV4Auth(credentials, "s3", region).add_auth(signed)
    prepared = signed.prepare()
    request = urllib.request.Request(
        prepared.url, data=body, headers=dict(prepared.headers), method=method
    )
    with urllib.request.urlopen(request, context=context, timeout=60) as response:
        return response.status, response.read()

s3 = session.client(
    "s3",
    endpoint_url=endpoint,
    verify=ca,
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
parent = "extensions/invoice.txt"
s3.put_object(Bucket="attachments", Key=parent, Body=b"invoice 1001\n")
query = {"annotation": "", "annotationName": "labels.json"}
body = json.dumps({"invoice_id": 1001, "status": "paid"}).encode("utf-8")
print(signed_request("PUT", parent, query, body, {"Content-Type": "application/json"})[0])
print(signed_request("GET", parent, query)[1].decode("utf-8"))
print(signed_request("GET", parent, {"annotation": ""})[1].decode("utf-8"))
print(signed_request("DELETE", parent, query)[0])

archive = io.BytesIO()
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED) as output:
    output.writestr("readme.txt", "hello from ZIP\n")
s3.put_object(Bucket="attachments", Key="demo.zip", Body=archive.getvalue())
print(signed_request("GET", "demo.zip/readme.txt", headers={"x-minio-extract": "true"})[1].decode("utf-8"))
print(signed_request("HEAD", "demo.zip/readme.txt", headers={"x-minio-extract": "true"})[0])
print(signed_request("GET", "", {"list-type": "2", "prefix": "demo.zip/"},
                     headers={"x-minio-extract": "true"})[1].decode("utf-8"))

Run the script:

"$HOME/.local/share/silo-tutorial/venv/bin/python" "$HOME/.local/share/silo-tutorial/extensions.py"

The script prints the PUT status (200), the annotation JSON, the annotation list XML, the DELETE status (204), the extracted hello from ZIP member content, the HEAD status (200), and the ListObjectsV2 XML for demo.zip/. See Annotations and ZIP extraction for full protocol rules and error codes.

6 - 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.