# S3 client protocol guide ## Purpose This document defines the S3 protocol contract implemented by `@okikio/opfs/s3`. It is written for maintainers who need to change signing, upload, copy, listing, conditional-write, or compatibility behavior without silently changing the public filesystem guarantees. The client is intentionally not a replacement for the complete AWS SDK. It implements the S3 REST operations needed by the S3 object driver and keeps a low-level signed `request()` method for S3-compatible features that do not belong in the portable filesystem API. The implementation is direct: ```text S3ClientType | +--> direct protocol use | `--> S3 object driver -> object adapter -> FileSystemType request construction | v AWS Signature Version 4 | v Web Fetch | +--> Amazon S3 `--> S3-compatible endpoint ``` The protocol code uses Web Crypto for SHA-256 and HMAC-SHA256. `@std/encoding` owns hexadecimal encoding, `@std/async/pool` owns bounded multipart concurrency, `@std/xml` owns XML parsing/serialization, and `@std/bytes` supports the shared chunk layer. No AWS SDK package is imported. This document distinguishes three evidence classes: - **Implemented** means the current source contains the behavior. - **Protocol** means the behavior is required or described by current AWS S3 documentation. - **Provider-dependent** means an S3-compatible service can intentionally differ and the client exposes configuration for that difference. The current implementation was reviewed against AWS S3 REST documentation on August 14, 2026. The authoritative source remains AWS documentation when this file and the service specification disagree. ## The client owns a focused S3 contract `S3ClientType` implements the object-backend operations consumed by `driver/s3`, while retaining S3-specific protocol methods. The object operations used by the driver are: | Object operation | S3 REST operation | Current behavior | | ----------------- | -------------------------- | --------------------------------------------------- | | `head()` | `HeadObject` | Exact-key metadata or `null` for `404` | | `get()` | `GetObject` | Complete object or one `Range` | | `put(Uint8Array)` | `PutObject` | One materialized request up to 5 GB | | `put(stream)` | Multipart upload | Bounded concurrent parts and explicit completion | | `delete()` | `DeleteObject` | Missing object is already removed | | `list()` | `ListObjectsV2` | Prefix, delimiter, limit, continuation token | | `copy()` small | `CopyObject` | Server-side copy through the 5 GB single-copy limit | | `copy()` large | Multipart `UploadPartCopy` | Server-side ranged copy without JS body transfer | The S3-specific surface also exposes: ```text request() createUpload() uploadPart() completeUpload() abortUpload() ``` Those operations are public because an S3 consumer can need storage class, checksums, encryption, object lock, tagging, or another provider extension that is not a filesystem concern. The low-level request method signs the request but does not interpret every S3 feature on the caller's behalf. The driver remains a separate public layer: ```ts import { createS3Client } from "@okikio/opfs/s3"; import { createS3DriverFromClient } from "@okikio/opfs/driver/s3"; import { createObjectAdapter } from "@okikio/opfs/adapter/object"; const client = createS3Client(options); const driver = createS3DriverFromClient(client); const adapter = createObjectAdapter(driver); ``` The driver adds provider requirements, hard limits, optimization state, deterministic planning, and physical request metrics. The adapter then translates object prefixes and values into canonical filesystem primitives. ## Optimizations are independently controllable The S3 client currently exposes two optimization switches. Both are visible through the S3 driver inspection. `delayedMultipart` : Defaults to true. For an unknown-length stream, the client buffers the first bounded multipart chunk before creating an upload. If EOF arrives while the object can use one `PutObject`, the client avoids multipart initiation. If more data arrives, or the first chunk is already above the single-PUT ceiling, it starts multipart and replays the retained bytes into the multipart lane. Set this to false when exact multipart request lifecycle is required for testing or application policy. `signingKeyCache` : Defaults to true. The client caches the derived SigV4 signing key for the current credentials/date/region/service tuple. The cache is per client and invalidates when the tuple changes. Disabling it forces key derivation on every signed request. The optimization changes CPU work but not the canonical request or resulting signature. The client reports both switches through `client.optimizations`, while `driver.inspect().optimizations` exposes the same state in the generic driver model. Any future optimization that changes request count, provider resource lifetime, failure timing, or storage layout must also be independently disableable. ## Addressing and canonical request construction The client supports path-style and virtual-hosted-style addressing. Path style: ```text https://endpoint.example/bucket/path/to/object ``` Virtual-hosted style: ```text https://bucket.endpoint.example/path/to/object ``` `addressing: "path"` is the compatibility-oriented default because many local and third-party S3 implementations expose one HTTP endpoint without wildcard DNS for buckets. The client preserves slash separators in object keys while percent-encoding each path segment. Signature Version 4 is sensitive to exact path and query serialization. The implementation therefore does not use locale-sensitive sorting and does not normalize the canonical URI after object-key construction. For the canonical query string, the client: 1. expands repeated query values; 2. URI-encodes each name and value; 3. sorts the encoded names and then encoded values by code-unit order; 4. joins the pairs with `&`. For canonical headers, the client: 1. lowercases header names; 2. normalizes internal whitespace; 3. sorts the signed header names; 4. includes the request authority as `host` even though browser Fetch controls the actual Host or HTTP/2 `:authority` field; 5. includes required `x-amz-*` headers. The signing flow is: ```text method + canonical URI + canonical query + canonical headers + signed-header names + payload SHA-256 | v canonical request SHA-256 | v AWS4-HMAC-SHA256 string to sign | v kDate -> kRegion -> kService(s3) -> kSigning | v Authorization signature ``` Credential sources can be static or refreshable. Refreshable credentials are resolved immediately before each signed request. Session credentials add `x-amz-security-token` before canonical signing. The client uses Web Crypto directly because browser-compatible SHA-256 and HMAC are already platform APIs. `@std/crypto` does not implement S3 Signature Version 4, so adding it would not remove protocol code or improve ownership. ### Payload hashes Replayable Web request bodies are SHA-256 hashed before signing. The client hashes strings, `ArrayBuffer`, `ArrayBufferView`, `Blob`, and `URLSearchParams` values. Requests without bodies use the standard SHA-256 of an empty payload. A low-level caller can supply `payloadHash`. This exists for S3 modes such as `UNSIGNED-PAYLOAD` where the selected provider accepts that contract. The client does not silently choose an unsigned payload when the exact request bytes can be determined without consuming or re-encoding caller state. A streamed low-level body cannot be consumed once merely to calculate a hash and then consumed again by Fetch. `FormData` has a related problem because Fetch owns its multipart boundary and exact wire encoding. Those two low-level body forms therefore use `UNSIGNED-PAYLOAD` unless the caller supplies an explicit `payloadHash`. Callers that need AWS streaming-signature chunk framing must implement that S3-specific streaming mode above `request()`. The normal high-level streamed `put()` avoids this ambiguity by using multipart parts, each of which is materialized before its individual signed request. ## Object and multipart limits are part of planning `S3_LIMITS` records the protocol limits that affect this implementation: | Limit | Value used by the client | Why it matters | | ----------------------- | ------------------------ | ------------------------------------------------------- | | Maximum object | 53,687,091,200,000 bytes | Exact 10,000 x 5 GiB multipart ceiling (48.8 TiB) | | Single `PutObject` | 5,000,000,000 bytes | Larger replacement must use multipart upload | | Single `CopyObject` | 5,000,000,000 bytes | Larger copy must use multipart copy | | Minimum multipart part | 5 MiB | Every non-final upload part must meet the S3 minimum | | Maximum multipart part | 5 GiB | Client part-size configuration cannot exceed it | | Maximum multipart parts | 10,000 | Known-size streams must choose a large enough part size | The distinction between GB and GiB is intentional. AWS documents the single-request PUT/copy threshold in decimal GB, while multipart part limits use binary-sized MiB/GiB values. AWS product documentation often calls the maximum object size 50 TB, while the current object guide and multipart arithmetic make the exact ceiling 10,000 x 5 GiB = 53,687,091,200,000 bytes (48.8 TiB, about 53.7 TB). The client uses the exact multipart-derived value so it does not reject objects that S3 can legally assemble. `partSize` defaults to 8 MiB. `copyPartSize` defaults to 1 GiB. Both are validated when the client is created. If `ObjectPutOptionsType.size` is supplied, the upload planner calculates the minimum part size required to stay at or below 10,000 parts and uses the larger of that value and the configured `partSize`. ```text known body size | v ceil(size / 10,000) | +--> <= configured partSize -> configured partSize | `--> larger -> required part size | `--> reject if > 5 GiB ``` When a stream size is unknown, the configured part size remains authoritative. The chunk iterator fails before part 10,001 instead of creating an invalid multipart request. A caller with a very large stream should supply `size` so the planner can choose a safe part size before network work begins. The final upload byte count is compared with the declared `size`. A mismatch is a caller/data-source error and the multipart upload is aborted. Failure and cancellation do not transfer cleanup authority to the caller. Once `CreateMultipartUpload` succeeds, the high-level streamed `put()` owns that upload until completion or abort. If a part fails or the caller cancels, the client stops consuming the source, waits for admitted part requests to settle, and then sends `AbortMultipartUpload` with a separate cleanup signal. `abortTimeoutMs` bounds that best-effort cleanup and defaults to 30 seconds. Using a separate signal matters because the caller's cancellation signal is already aborted at exactly the time cleanup becomes necessary. ## Multipart upload is a commit protocol A streamed replacement follows four protocol stages: ```text CreateMultipartUpload | v split stream into fixed-size owned byte parts | +--> UploadPart 1 +--> UploadPart 2 bounded by `concurrency` +--> ... `--> UploadPart N | v CompleteMultipartUpload | +--> success -> HEAD final object | `--> failure -> AbortMultipartUpload after active parts settle ``` `@std/async/pool` owns the concurrency admission. The client does not start an unbounded Promise for every part. Each successful `UploadPart` must return an ETag. The completion document contains one ordered `PartNumber`/`ETag` record per uploaded part. Before the client sends that XML, it verifies: - at least one part exists; - no more than 10,000 parts exist; - every part number is an integer in the legal range; - a part number is not duplicated; - every ETag is non-empty; - the final order is ascending by part number. The XML document is built with `@std/xml/stringify`; protocol escaping is not a hand-written string replacement. The completion request can carry destination `If-Match`, `If-None-Match`, and `x-amz-mp-object-size`. Preconditions belong to the commit stage rather than multipart initiation because commit is the point where the destination object becomes authoritative. S3 has an unusual completion failure mode: the service can send HTTP `200 OK` before final assembly finishes and then put an `` document in the response body. `completeUpload()` therefore parses the success body and treats an embedded `` as a failed commit. If any streamed part operation fails, the client waits for the pool's already started requests to settle before it sends `AbortMultipartUpload`. This order prevents a late `UploadPart` from racing after the abort request. An abort failure does not replace the original upload failure. The original operation remains the terminal error because it is what caused cleanup. Unfinished multipart state can still remain at the provider when both the operation and cleanup request fail, so production buckets should also use an S3 lifecycle rule for stale multipart uploads. ## Server-side copy has two distinct paths `copy()` first performs `HeadObject` on the source. This confirms existence, obtains size for planning, and supplies metadata needed by multipart initiation. For a source at or below the single-copy limit, the client sends `CopyObject`. For a larger source, it creates a multipart upload at the destination and sends one `UploadPartCopy` request per byte range. ```text HEAD source | +-- size <= 5 GB --------> CopyObject | `-- size > 5 GB ---------> CreateMultipartUpload | +--> UploadPartCopy range 1 +--> UploadPartCopy range 2 `--> ... | v CompleteMultipartUpload ``` Multipart copy chooses a range size large enough to keep the destination at or below 10,000 parts and rejects a plan that would require a part above 5 GiB. The range is inclusive because `x-amz-copy-source-range` uses inclusive byte positions. Source preconditions map to S3 copy-source headers: | Package option | S3 header | | ------------------------- | --------------------------------------- | | `sourceIfMatch` | `x-amz-copy-source-if-match` | | `sourceIfNoneMatch` | `x-amz-copy-source-if-none-match` | | `sourceIfModifiedSince` | `x-amz-copy-source-if-modified-since` | | `sourceIfUnmodifiedSince` | `x-amz-copy-source-if-unmodified-since` | Destination `ifMatch` and `ifNoneMatch` apply directly to `CopyObject` or to the multipart completion request. They are deliberately removed from individual `UploadPartCopy` requests because a destination object does not become the completed value until commit. `CopyObject` and `UploadPartCopy` can also encode a service error inside an HTTP 200 response. Both paths use the same success-XML inspection as multipart completion. ## Listing preserves provider pagination `list()` uses `ListObjectsV2` with these mappings: | Package field | S3 query field | | ------------- | -------------------- | | `prefix` | `prefix` | | `delimiter` | `delimiter` | | `limit` | `max-keys` | | `cursor` | `continuation-token` | `Contents` records become `ObjectEntryType`. `CommonPrefixes` become child prefixes. `NextContinuationToken` is returned as the next opaque cursor. The S3 object driver and object adapter are responsible for consuming pages and interpreting directory-marker metadata. The S3 client itself does not pretend that prefixes are native directories. ## Conditional writes are capability claims The client advertises `conditionalWrite: true` by default because Amazon S3 honors the preconditions used by this implementation. An S3-compatible service that ignores or only partially implements these conditions must set `conditionalWrite: false` in `createS3Client()`. That flag changes filesystem behavior. The S3 driver/object adapter will not claim that a read-modify-write append/update is protected from concurrent replacement when the backend cannot enforce the ETag precondition. `copy: false` similarly disables server-side copy for an endpoint whose S3 API does not implement the required copy operations correctly. These overrides are explicit because compatibility means "uses the S3 protocol" not "implements every Amazon S3 behavior". ## Failures retain provider evidence Non-success responses are parsed as S3 XML when possible. `S3Error` retains: ```text status S3 code requestId hostId original Response ``` The original `Response` remains available so a caller can inspect headers and provider-specific diagnostics that the stable error fields do not model. A response body that is not valid S3 XML still produces a failure based on HTTP status and available text. The client does not convert an unknown provider response into a fake known S3 error code. Cancellation uses `AbortSignal` on each Fetch request. Multipart cancellation is not a distributed transaction: cancellation can stop local admission and abort HTTP work, while an already accepted provider request may still have created remote multipart state. Cleanup is therefore explicit. Request retry is explicit and operation-aware. `request` in `S3ClientOptionsType` configures retries, exponential delay, jitter, and an optional per-attempt timeout. The implementation uses `@std/async/retry` for 408, 429, 5xx, and transport failures. Authorization is rebuilt for every attempt so refreshable credentials and SigV4 timestamps are current. Signed redirects are manual and are returned to the caller instead of being followed to another authority. Body replayability is only one admission condition. A one-shot `ReadableStream` receives one attempt. A mechanically replayable body can still belong to a non-idempotent protocol operation, so low-level `request()` also accepts `retry: false`. The high-level client disables automatic retry for `CreateMultipartUpload` and `CompleteMultipartUpload` because a lost response can make the server-side outcome ambiguous. Stable part-number PUTs, reads, deletes, lists, and ordinary replacements use the configured policy. `request: { retries: 0 }` disables automatic retry client-wide. A request admitted for only one attempt bypasses the retry engine entirely. A zero-delay policy with `minDelayMs: 0` and `maxDelayMs: 0` remains valid even though the underlying standard helper requires a positive maximum timeout. `getMetrics()` returns direct HTTP request counts, retry counts, terminal failures, response counts, and optional Fetch duration. Set `metrics: "none"` when measuring the raw protocol path, `basic` for counters, or `timing` for counters plus durations. ## Provider compatibility and known non-goals The direct client supports custom endpoint, region, headers, path/virtual addressing, copy capability, and conditional-write capability. This is enough to use Amazon S3 and many S3-compatible products while keeping compatibility choices visible. The current client does **not** claim complete coverage of: - SigV4 streaming chunk signatures; - presigned URL creation; - S3 Express directory-bucket session management; - access points, Object Lambda, or Outposts host construction; - Multi-Region Access Point SigV4A; - SSE-C/SSE-KMS convenience APIs; - checksum negotiation beyond the payload hash needed for signing; - object tagging, ACLs, retention, legal hold, replication, or lifecycle APIs; - version-ID aware filesystem paths; - bucket creation or bucket policy management; - adaptive throttling and provider-specific `Retry-After` scheduling beyond the shared exponential retry policy. A low-level signed request can still reach some provider features when the caller knows the exact S3 REST contract. A feature should receive a typed high-level API only after the library can document and test its semantics. ## Validation strategy S3 validation is intentionally split into protocol and provider tests. `tests/s3.test.ts` is deterministic. It uses a controlled Fetch implementation to inspect exact requests and covers: - Signature Version 4 canonicalization; - deterministic timestamps and credentials; - minimum/maximum multipart part configuration; - multipart part ordering and duplicate rejection; - `x-amz-mp-object-size` at completion; - HTTP 200 embedded service errors; - source and destination copy preconditions; - large-copy multipart planning; - part-count behavior. `tests/provider.test.ts` opens the pinned SeaweedFS S3-compatible server through Testcontainers. It proves a real HTTP implementation can accept our signed requests for PUT, HEAD, range GET, conditional create, multipart streaming upload, copy, listing, delete, the S3 driver, and the object filesystem adapter. The fixture uses a random mapped host port so concurrent local runs do not share one fixed endpoint. The provider container is SeaweedFS, not a statement that SeaweedFS defines the S3 specification. The container proves interoperability with one independent S3-compatible implementation. AWS-specific wire details remain covered by the deterministic protocol tests and the AWS documentation listed below. Before release, the maintainer test matrix should also run an opt-in real Amazon S3 suite with short-lived credentials when CI secret policy permits it. That suite must use a dedicated disposable bucket/prefix and explicit cleanup. ## Primary specification sources The implementation and this guide should be checked against these primary AWS sources when S3 behavior changes: - AWS Signature Version 4 canonical request: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html - Multipart upload limits: https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html - CompleteMultipartUpload: https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html - CopyObject: https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html - UploadPartCopy: https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPartCopy.html - ListObjectsV2: https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html Secondary S3-compatible provider documentation can explain provider-specific configuration, but it must not override the Amazon S3 wire contract when the client claims Amazon S3 behavior.