Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

S3 fixes aws (#1327)

Nahuel Nucera7136ac02818c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20a52691..582ddf14 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,15 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Fixed
+- **S3 — POST Object no longer misreads form fields as the object body** — a multipart part was classified as the object content when its name was `file` **or** it carried a `filename` attribute, but browsers and HTTP libraries (Python `requests`' `files=`) set `filename` on ordinary form fields, so every field looked like the body, no `key` field survived, and the upload was rejected with `InvalidArgument`. Only the field literally named `file` is the body now, matching S3. Reported by @gaul.
+- **S3 — `GetObject` with `partNumber` returns the requested part** — the `partNumber` parameter was dropped, so a client fetching an N-part object in parallel received N full copies. A completed multipart object now returns the requested part as `206 Partial Content` with a `Content-Range` and `x-amz-mp-parts-count`, matching S3. Reported by @gaul.
+- **S3 — `ListObjectVersions` returns continuation markers when truncated** — a truncated response set `IsTruncated=true` but emitted neither `NextKeyMarker` nor `NextVersionIdMarker`, and the incoming `version-id-marker` was ignored, so a paginating client looped on page one or (as boto3 does) rejected `KeyMarker=None`. The markers are now emitted and `version-id-marker` resumes within `key-marker`. Reported by @gaul.
+- **S3 — `CompleteMultipartUpload` returns `400 MalformedXML` for an unparseable body** — an empty or malformed body raised an unguarded `ParseError` that escaped as a `500` with a JSON document no S3 SDK can parse, so clients treated it as a transient fault and retried. It now returns `400 MalformedXML`, as XML. Reported by @gaul.
+- **S3 — `CompleteMultipartUpload` is idempotent** — the upload record was dropped on the first call, so a retry (how a client recovers from a lost response) returned `NoSuchUpload`. The completed response is now retained and replayed for a repeat call with the same upload id, without minting a second object version, matching S3. Reported by @gaul.
+- **S3 — object owner id is consistent between listings and ACLs** — `ListBuckets` / `ListObjects` / `ListObjectVersions` / `ListParts` hard-coded the owner id `owner-id` while `GetObjectAcl` / `GetBucketAcl` used the account id, so a client matching an object's owner against an ACL grantee always got a mismatch. All of them now use the account id. Reported by @gaul.
+- **S3 — presigned URLs are rejected once expired** — `X-Amz-Date` + `X-Amz-Expires` were never compared against the current time, so a URL minted with a one-second lifetime served the object indefinitely. An expired presigned URL now returns `403 AccessDenied` (`Request has expired`), matching S3. Reported by @gaul.
+- **S3 — conditional deletes honour `If-Match`** — `DeleteObject` ignored the `If-Match` header and `DeleteObjects` ignored a per-object `ETag`, so a delete carrying a stale ETag removed the object anyway (and the batch reported it under `Deleted`). `DeleteObject` now returns `412 PreconditionFailed` on an ETag mismatch, and `DeleteObjects` reports the key under `Error` (`PreconditionFailed`) instead of deleting it, matching S3's compare-and-swap delete. Reported by @gaul.
### Added
- **RDS — `ManageMasterUserPassword` wires Aurora clusters to Secrets Manager** — `CreateDBCluster(ManageMasterUserPassword=true)` previously ignored the flag: no secret was created, no `MasterUserSecret` was returned, and code paths that resolve database credentials from Secrets Manager (the common production pattern) could not be rehearsed locally. The flag now generates a random master password, stores it in MiniStack's own Secrets Manager as `{"username", "password"}` under the AWS naming convention (`rds!cluster-<uuid>`), and returns `MasterUserSecret` (`SecretArn`, `SecretStatus`, `KmsKeyId`) from create/describe/modify. `ModifyDBCluster(RotateMasterUserPassword=true, ApplyImmediately=true)` rotates the real database login through the same path as an explicit password change — including the pending-rotation behavior for stopped compute — and promotes the new credentials to `AWSCURRENT` (previous ones stay readable as `AWSPREVIOUS`); a rotation whose managed secret was deleted out from under RDS fails with `InvalidDBClusterStateFault` and flips `SecretStatus` to `impaired`, as on AWS. `DeleteDBCluster` deletes the managed secret with the cluster (and only when the delete actually succeeds). AWS-exact rejections: `ManageMasterUserPassword` + explicit `MasterUserPassword` at create, explicit password against a managed cluster, `RotateMasterUserPassword` without a managed secret or without `ApplyImmediately`, and explicit password + rotate flag in one request — validated before anything mutates. The RDS↔Secrets Manager seam is in-process and one-directional (rds → secretsmanager), reusing the emulator's existing stage-promotion and replica-sync internals. Contributed by @kiran01bm.
- **EventBridge — API destination targets are now invoked over HTTP on `PutEvents`** — API destinations and connections were control-plane stubs: a matching rule with an api-destination target logged "unsupported event target ARN" and dropped the event, so webhook-style pipelines (EventBridge → HTTPS endpoint) could not be tested locally. Matching events now POST (or the destination's configured method) to the `InvocationEndpoint` with the input-selected payload (`Input` / `InputPath` / `InputTransformer` apply as for other targets). Connection authorization is honored: `BASIC` populates `Authorization: Basic …`, `API_KEY` sends the configured header, and `OAUTH_CLIENT_CREDENTIALS` exchanges the client ID/secret at the authorization endpoint (`OAuthHttpParameters` merged in, `grant_type=client_credentials` defaulted), caches the token per connection and invalidates it when the connection is deleted, re-authorized, or deauthorized (a connection recreated under a reused name never inherits its predecessor's token), refreshes proactively when it expires within 60 seconds, and refreshes + retries once on a `401`/`407` response — matching documented AWS behavior. Connection `InvocationHttpParameters` and target `HttpParameters` are merged with connection values taking precedence (per the `HttpParameters` API reference), `PathParameterValues` populate `*` path wildcards, and body parameters fold into JSON-object bodies. Requests carry the AWS default headers (`User-Agent: Amazon/EventBridge/ApiDestinations` and `Range` non-overridable, `Content-Type` defaulting to `application/json; charset=utf-8`), strip the headers real EventBridge removes, and time out after 5 seconds (the documented maximum client execution timeout). Delivery runs on a background thread mirroring the SNS HTTP(S) path. Not modeled, mirroring the cross-region FailedInvocations policy: the 24h/185-attempt retry pipeline, `Retry-After`, DLQs, and `InvocationRateLimitPerSecond` — retryable statuses (`401`, `407`, `409`, `429`, `5xx`) are logged and dropped.
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index f3a3f1cd..2881f9cf 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -41,7 +41,7 @@ from urllib.parse import parse_qs as _parse_qs
from urllib.parse import quote as url_quote
from urllib.parse import unquote as url_unquote
from urllib.parse import urlparse as _urlparse
-from xml.etree.ElementTree import Element, SubElement, tostring
+from xml.etree.ElementTree import Element, ParseError, SubElement, tostring
from xml.sax.saxutils import escape as _esc
from defusedxml.ElementTree import fromstring
@@ -93,6 +93,11 @@ _object_retention = AccountScopedDict()
_object_legal_hold = AccountScopedDict()
_multipart_uploads = AccountScopedDict()
+# Completed uploads, keyed by upload id -> the (status, headers, body) response.
+# CompleteMultipartUpload is idempotent: a retry with the same upload id and
+# parts returns the original 200 result rather than NoSuchUpload (which real S3
+# only returns later, once the upload id is garbage-collected).
+_completed_multipart_uploads = AccountScopedDict()
# ── Persistence (metadata only — object bodies are NOT persisted here) ────
@@ -809,6 +814,22 @@ def _verify_presigned_sigv4(method, path, headers, query_params):
return _bad_signature()
_akid, date_stamp, region, service, _terminator = cred_parts
+ # Expiry: a presigned URL past X-Amz-Date + X-Amz-Expires is rejected by S3
+ # with 403 AccessDenied "Request has expired", independent of the signature.
+ expires = (_qp(query_params, "X-Amz-Expires", "")
+ or _qp(query_params, "x-amz-expires", ""))
+ if expires:
+ try:
+ signed_at = _dt.datetime.strptime(
+ amz_date, "%Y%m%dT%H%M%SZ"
+ ).replace(tzinfo=_dt.timezone.utc)
+ if _dt.datetime.now(_dt.timezone.utc) > signed_at + _dt.timedelta(
+ seconds=int(expires)
+ ):
+ return _error("AccessDenied", "Request has expired", 403, path)
+ except (ValueError, TypeError):
+ pass
+
# Canonical query string: every query param except X-Amz-Signature,
# RFC3986-encoded, sorted by encoded key then value.
pairs = []
@@ -1081,7 +1102,7 @@ def _dispatch(
def _list_buckets():
root = Element("ListAllMyBucketsResult", xmlns=S3_NS)
owner = SubElement(root, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = get_account_id()
SubElement(owner, "DisplayName").text = "ministack"
buckets_el = SubElement(root, "Buckets")
for name, data in sorted(_buckets.items()):
@@ -1801,17 +1822,57 @@ def _list_object_versions(bucket_name: str, query_params: dict):
SubElement(root, "VersionIdMarker").text = version_id_marker
SubElement(root, "MaxKeys").text = str(max_keys)
- # Collect all keys: from objects AND from version history (deleted objects)
- all_keys = set(k for k in bucket["objects"] if k.startswith(prefix) and k > key_marker)
+ owner_id = get_account_id()
+
+ # Collect all keys: from objects AND from version history (deleted objects).
+ # When a version-id-marker is supplied we must resume *within* key-marker,
+ # so that key is included; otherwise key-marker is exclusive.
+ def _in_page(k):
+ if not k.startswith(prefix):
+ return False
+ if version_id_marker:
+ return k >= key_marker
+ return k > key_marker
+
+ all_keys = set(k for k in bucket["objects"] if _in_page(k))
for (bn, k) in _object_versions:
- if bn == bucket_name and k.startswith(prefix) and k > key_marker:
+ if bn == bucket_name and _in_page(k):
all_keys.add(k)
keys = sorted(all_keys)
is_truncated = False
- SubElement(root, "IsTruncated").text = "false"
+ is_truncated_el = SubElement(root, "IsTruncated")
+ is_truncated_el.text = "false"
count = 0
+ next_key_marker = None
+ next_version_id_marker = None
+
+ def _emit_version(k, v):
+ if v.get("is_delete_marker"):
+ dm = SubElement(root, "DeleteMarker")
+ SubElement(dm, "Key").text = k
+ SubElement(dm, "VersionId").text = v["version_id"]
+ SubElement(dm, "IsLatest").text = "true" if v["is_latest"] else "false"
+ SubElement(dm, "LastModified").text = v["last_modified"]
+ owner = SubElement(dm, "Owner")
+ else:
+ ver = SubElement(root, "Version")
+ SubElement(ver, "Key").text = k
+ SubElement(ver, "VersionId").text = v["version_id"]
+ SubElement(ver, "IsLatest").text = "true" if v["is_latest"] else "false"
+ SubElement(ver, "LastModified").text = v["last_modified"]
+ SubElement(ver, "ETag").text = v["etag"]
+ SubElement(ver, "Size").text = str(v["size"])
+ SubElement(ver, "StorageClass").text = (
+ v.get("storage_class")
+ or bucket["objects"].get(k, {}).get("storage_class")
+ or "STANDARD"
+ )
+ owner = SubElement(ver, "Owner")
+ SubElement(owner, "ID").text = owner_id
+ SubElement(owner, "DisplayName").text = "ministack"
+
for k in keys:
if count >= max_keys:
is_truncated = True
@@ -1819,36 +1880,20 @@ def _list_object_versions(bucket_name: str, query_params: dict):
vkey = (bucket_name, k)
versions = _object_versions.get(vkey)
if versions:
- # Return all stored versions (newest first)
+ # Resume within key-marker: skip versions up to and including the
+ # supplied version-id-marker (versions are stored oldest-first, so
+ # newest-first iteration matches the S3 listing order).
+ skipping = bool(version_id_marker and k == key_marker)
for v in reversed(versions):
+ if skipping:
+ if v["version_id"] == version_id_marker:
+ skipping = False
+ continue
if count >= max_keys:
is_truncated = True
break
- if v.get("is_delete_marker"):
- dm = SubElement(root, "DeleteMarker")
- SubElement(dm, "Key").text = k
- SubElement(dm, "VersionId").text = v["version_id"]
- SubElement(dm, "IsLatest").text = "true" if v["is_latest"] else "false"
- SubElement(dm, "LastModified").text = v["last_modified"]
- owner = SubElement(dm, "Owner")
- SubElement(owner, "ID").text = "owner-id"
- SubElement(owner, "DisplayName").text = "ministack"
- else:
- ver = SubElement(root, "Version")
- SubElement(ver, "Key").text = k
- SubElement(ver, "VersionId").text = v["version_id"]
- SubElement(ver, "IsLatest").text = "true" if v["is_latest"] else "false"
- SubElement(ver, "LastModified").text = v["last_modified"]
- SubElement(ver, "ETag").text = v["etag"]
- SubElement(ver, "Size").text = str(v["size"])
- SubElement(ver, "StorageClass").text = (
- v.get("storage_class")
- or bucket["objects"].get(k, {}).get("storage_class")
- or "STANDARD"
- )
- owner = SubElement(ver, "Owner")
- SubElement(owner, "ID").text = "owner-id"
- SubElement(owner, "DisplayName").text = "ministack"
+ _emit_version(k, v)
+ next_key_marker, next_version_id_marker = k, v["version_id"]
count += 1
else:
# No version history — return current object with null version
@@ -1864,12 +1909,17 @@ def _list_object_versions(bucket_name: str, query_params: dict):
SubElement(ver, "Size").text = str(obj["size"])
SubElement(ver, "StorageClass").text = obj.get("storage_class") or "STANDARD"
owner = SubElement(ver, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = owner_id
SubElement(owner, "DisplayName").text = "ministack"
+ next_key_marker, next_version_id_marker = k, obj.get("version_id", "null")
count += 1
- # Update IsTruncated after actual count
- root.find("IsTruncated").text = "true" if is_truncated else "false"
+ is_truncated_el.text = "true" if is_truncated else "false"
+ # A truncated response must carry the continuation markers, or a paginating
+ # client loops on page one (or, as boto3 does, rejects KeyMarker=None).
+ if is_truncated and next_key_marker is not None:
+ SubElement(root, "NextKeyMarker").text = next_key_marker
+ SubElement(root, "NextVersionIdMarker").text = next_version_id_marker or "null"
return 200, {"Content-Type": "application/xml"}, _xml_body(root)
@@ -2571,7 +2621,11 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
file_filename: str | None = None
file_headers: dict = {}
for name, filename, ph, value in parts:
- if name == "file" or filename is not None:
+ # Only the field literally named "file" is the object body. A filename
+ # attribute on any other field does NOT make it the body — browsers and
+ # HTTP libraries (e.g. Python requests' files=) set filename on ordinary
+ # form fields, and S3 treats those as form fields, not content.
+ if name == "file":
file_value = value
file_filename = filename or ""
file_headers = ph
@@ -2794,6 +2848,29 @@ def _get_object(bucket_name: str, key: str, headers: dict, query_params: dict =
resp_headers.update(_object_tagging_count_header(bucket_name, key, obj.get("version_id")))
body = _read_body(bucket_name, key, obj)
+
+ # partNumber: return a single part of a completed multipart object as 206
+ # Partial Content with a Content-Range and x-amz-mp-parts-count, rather than
+ # the whole object. Parts are matched by their part number (which may be
+ # non-contiguous), and their byte offset is the sum of the preceding sizes.
+ part_number = _qp(query_params, "partNumber") if query_params else None
+ if part_number and obj.get("parts"):
+ try:
+ pn = int(part_number)
+ except (TypeError, ValueError):
+ pn = None
+ parts = obj["parts"]
+ idx = next((i for i, p in enumerate(parts) if p["PartNumber"] == pn), None)
+ if idx is not None:
+ offset = sum(p["Size"] for p in parts[:idx])
+ length = parts[idx]["Size"]
+ slice_body = body[offset : offset + length]
+ resp_headers["Content-Length"] = str(len(slice_body))
+ resp_headers["Content-Range"] = f"bytes {offset}-{offset + length - 1}/{obj['size']}"
+ resp_headers["x-amz-mp-parts-count"] = str(len(parts))
+ _apply_response_overrides(resp_headers, query_params)
+ return 206, resp_headers, slice_body
+
if range_header:
rng = _parse_range(range_header, obj["size"])
if rng is None:
@@ -3042,6 +3119,20 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None,
if bucket is None:
return _no_such_bucket(bucket_name)
+ # Conditional delete: If-Match against the current object's ETag. A
+ # non-matching (or absent) object fails the precondition with 412, so the
+ # object is not removed — S3's compare-and-swap delete.
+ if_match = (headers.get("if-match") or "").strip()
+ if if_match:
+ _cur = bucket["objects"].get(key)
+ if _cur is None or if_match.strip('"') != _cur["etag"].strip('"'):
+ return _error(
+ "PreconditionFailed",
+ "At least one of the preconditions you specified did not hold.",
+ 412,
+ f"/{bucket_name}/{key}",
+ )
+
if key in bucket["objects"]:
lock_err = _check_object_lock(bucket_name, key, headers)
if lock_err:
@@ -3993,7 +4084,7 @@ def _list_objects_v1(bucket_name: str, query_params: dict):
SubElement(c, "Size").text = str(obj["size"])
SubElement(c, "StorageClass").text = obj.get("storage_class") or "STANDARD"
owner = SubElement(c, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = get_account_id()
SubElement(owner, "DisplayName").text = "ministack"
for cp in sorted(common_prefixes):
@@ -4069,7 +4160,7 @@ def _list_objects_v2(bucket_name: str, query_params: dict):
SubElement(c, "StorageClass").text = obj.get("storage_class") or "STANDARD"
if fetch_owner:
owner = SubElement(c, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = get_account_id()
SubElement(owner, "DisplayName").text = "ministack"
for cp in sorted(common_prefixes):
@@ -4123,6 +4214,22 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):
})
continue
+ # Conditional delete: an ObjectIdentifier with an ETag deletes only if it
+ # matches the current object. On mismatch the key is reported under Error
+ # (PreconditionFailed), not Deleted, so the object survives.
+ etag_el = _find_xml_tag(obj_el, "ETag")
+ cond_etag = etag_el.text if (etag_el is not None and etag_el.text) else ""
+ if cond_etag:
+ _cur = bucket["objects"].get(k)
+ if _cur is None or cond_etag.strip('"') != _cur["etag"].strip('"'):
+ errors.append({
+ "key": k,
+ "version_id": version_id,
+ "code": "PreconditionFailed",
+ "msg": "At least one of the preconditions you specified did not hold.",
+ })
+ continue
+
if version_id:
# Explicit VersionId → permanently purge that exact version/marker.
# S3 reports the delete as successful even if the version was absent.
@@ -4337,6 +4444,11 @@ def _complete_multipart_upload(
return _no_such_bucket(bucket_name)
upload_id = _qp(query_params, "uploadId")
+ # Idempotent retry: if the upload already completed, replay its response
+ # instead of returning NoSuchUpload (real S3 stays 200 until the id is GC'd).
+ cached = _completed_multipart_uploads.get(upload_id)
+ if cached is not None and cached.get("key") == key:
+ return cached["response"]
if upload_id not in _multipart_uploads:
return _error(
"NoSuchUpload",
@@ -4354,7 +4466,16 @@ def _complete_multipart_upload(
f"/{bucket_name}/{key}",
)
- xml_root = fromstring(body)
+ try:
+ xml_root = fromstring(body)
+ except ParseError:
+ return _error(
+ "MalformedXML",
+ "The XML you provided was not well-formed or did not validate "
+ "against our published schema.",
+ 400,
+ f"/{bucket_name}/{key}",
+ )
ordered_parts: list[tuple[int, str | None]] = []
for part_el in xml_root.iter():
local = part_el.tag.split("}")[-1] if "}" in part_el.tag else part_el.tag
@@ -4454,7 +4575,12 @@ def _complete_multipart_upload(
SubElement(root, "Bucket").text = bucket_name
SubElement(root, "Key").text = key
SubElement(root, "ETag").text = final_etag
- return 200, resp_headers, _xml_body(root)
+ response = (200, resp_headers, _xml_body(root))
+ # Retain the response so an idempotent retry (same upload id) replays it
+ # rather than 404ing; the versioning block above is NOT re-run on replay,
+ # so a retry never mints a second object version.
+ _completed_multipart_uploads[upload_id] = {"key": key, "response": response}
+ return response
def _abort_multipart_upload(bucket_name: str, key: str, query_params: dict):
@@ -4532,10 +4658,10 @@ def _list_multipart_uploads(bucket_name: str, query_params: dict):
SubElement(u, "Key").text = upload["key"]
SubElement(u, "UploadId").text = uid
initiator = SubElement(u, "Initiator")
- SubElement(initiator, "ID").text = "owner-id"
+ SubElement(initiator, "ID").text = get_account_id()
SubElement(initiator, "DisplayName").text = "ministack"
owner = SubElement(u, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = get_account_id()
SubElement(owner, "DisplayName").text = "ministack"
SubElement(u, "StorageClass").text = upload.get("storage_class") or "STANDARD"
SubElement(u, "Initiated").text = upload["created"]
@@ -4580,10 +4706,10 @@ def _list_parts(bucket_name: str, key: str, query_params: dict):
SubElement(root, "UploadId").text = upload_id
initiator = SubElement(root, "Initiator")
- SubElement(initiator, "ID").text = "owner-id"
+ SubElement(initiator, "ID").text = get_account_id()
SubElement(initiator, "DisplayName").text = "ministack"
owner = SubElement(root, "Owner")
- SubElement(owner, "ID").text = "owner-id"
+ SubElement(owner, "ID").text = get_account_id()
SubElement(owner, "DisplayName").text = "ministack"
SubElement(root, "StorageClass").text = upload.get("storage_class") or "STANDARD"
SubElement(root, "PartNumberMarker").text = str(part_marker)
@@ -4882,6 +5008,7 @@ def reset():
_object_tags,
_object_acl,
_multipart_uploads,
+ _completed_multipart_uploads,
_bucket_object_lock,
_bucket_replication,
_object_retention,
diff --git a/ministack/services/transfer.py b/ministack/services/transfer.py
index 7e5a4e33..8c19a8c6 100644
--- a/ministack/services/transfer.py
+++ b/ministack/services/transfer.py
@@ -59,16 +59,18 @@ logger = logging.getLogger("transfer")
# guarded so that a base install with the transfer service still works for
# the control plane (CreateServer / DescribeServer / etc.) even when the
# SFTP listener isn't available.
-try:
- import asyncssh
- from asyncssh.sftp import SFTPAttrs, SFTPName
-
- _ASYNCSSH_AVAILABLE = True
-except Exception: # noqa: BLE001 — any import failure means no SFTP
- asyncssh = None # type: ignore[assignment]
- SFTPAttrs = None # type: ignore[assignment]
- SFTPName = None # type: ignore[assignment]
- _ASYNCSSH_AVAILABLE = False
+import importlib.util as _importlib_util
+
+# asyncssh (+ its cryptography/OpenSSL bindings) is imported lazily by
+# _ensure_sftp_runtime() the first time the SFTP listener actually starts, so
+# importing this module for the control plane / persistence does not pull it
+# into the boot path. `find_spec` checks availability without importing.
+asyncssh = None # type: ignore[assignment]
+SFTPAttrs = None # type: ignore[assignment]
+SFTPName = None # type: ignore[assignment]
+_ASYNCSSH_AVAILABLE = _importlib_util.find_spec("asyncssh") is not None
+_MiniStackSSHServer = None # type: ignore[assignment] built by _ensure_sftp_runtime()
+_MiniStackSFTPServer = None # type: ignore[assignment]
REGION = os.environ.get("MINISTACK_REGION", "us-east-1")
@@ -784,419 +786,433 @@ def _sftp_build_server_factory(restrict_to_server_id: Optional[str] = None):
return _factory
-class _MiniStackSSHServer(asyncssh.SSHServer if _ASYNCSSH_AVAILABLE else object):
- """SSH-side auth callback. Resolves the (account, region, server, user)
- tuple from the presented public key and stashes it on the connection so
- the SFTP layer can read it back.
+def _ensure_sftp_runtime() -> None:
+ """Import asyncssh and build the SSH/SFTP server classes on first use.
- Subclassing :class:`asyncssh.SSHServer` (rather than just duck-typing
- the relevant methods) is required because asyncssh probes a wide set
- of optional auth methods (host-based, kbdint, GSSAPI) on the server
- instance during userauth negotiation; the default base-class
- implementations return ``False`` for everything we don't support.
+ Deferred so importing this module (control plane, persistence, get_state)
+ does not pull asyncssh + cryptography/OpenSSL at boot; only starting the
+ SFTP listener pays that cost.
"""
+ global asyncssh, SFTPAttrs, SFTPName, _MiniStackSSHServer, _MiniStackSFTPServer
+ if _MiniStackSFTPServer is not None:
+ return
+ import asyncssh as _mod
+ from asyncssh.sftp import SFTPAttrs as _A, SFTPName as _N
+ asyncssh, SFTPAttrs, SFTPName = _mod, _A, _N
+
+ class _MiniStackSSHServer(asyncssh.SSHServer if _ASYNCSSH_AVAILABLE else object):
+ """SSH-side auth callback. Resolves the (account, region, server, user)
+ tuple from the presented public key and stashes it on the connection so
+ the SFTP layer can read it back.
+
+ Subclassing :class:`asyncssh.SSHServer` (rather than just duck-typing
+ the relevant methods) is required because asyncssh probes a wide set
+ of optional auth methods (host-based, kbdint, GSSAPI) on the server
+ instance during userauth negotiation; the default base-class
+ implementations return ``False`` for everything we don't support.
+ """
- def __init__(self, restrict_to_server_id: Optional[str] = None):
- super().__init__() if _ASYNCSSH_AVAILABLE else None
- self._restrict_to_server_id = restrict_to_server_id
- self._resolved = None
- self._username = None
- self._conn = None
-
- def connection_made(self, conn):
- self._conn = conn
-
- def connection_lost(self, exc):
- pass
-
- def begin_auth(self, username):
- # True → continue to public-key validation. False would mean "no
- # auth needed", which we never want.
- self._username = username
- return True
-
- def password_auth_supported(self):
- return False
-
- def public_key_auth_supported(self):
- return True
+ def __init__(self, restrict_to_server_id: Optional[str] = None):
+ super().__init__() if _ASYNCSSH_AVAILABLE else None
+ self._restrict_to_server_id = restrict_to_server_id
+ self._resolved = None
+ self._username = None
+ self._conn = None
- def validate_public_key(self, username, key):
- """Called by asyncssh for each presented public key. Returns True
- if the key is registered for this username on some Transfer server.
+ def connection_made(self, conn):
+ self._conn = conn
- We export the key in OpenSSH format and string-compare against the
- body stored via `ImportSshPublicKey`. This is deliberately stricter
- than fingerprint comparison — same key body, exact match.
- """
- try:
- presented_body = key.export_public_key("openssh").decode("utf-8")
- except Exception as e:
- logger.debug("SFTP: failed to export presented key: %s", e)
- return False
+ def connection_lost(self, exc):
+ pass
- match = _sftp_resolve_user_by_key(username, presented_body)
- if not match:
- return False
+ def begin_auth(self, username):
+ # True → continue to public-key validation. False would mean "no
+ # auth needed", which we never want.
+ self._username = username
+ return True
- account_id, region, server_id, user = match
- if self._restrict_to_server_id and server_id != self._restrict_to_server_id:
- return False
- if _sftp_server_state(account_id, region, server_id) != "ONLINE":
+ def password_auth_supported(self):
return False
- self._resolved = (account_id, region, server_id, user)
- if self._conn is not None:
- self._conn.set_extra_info(ministack_user=user)
- self._conn.set_extra_info(ministack_server_id=server_id)
- self._conn.set_extra_info(ministack_account_id=account_id)
- self._conn.set_extra_info(ministack_region=region)
- return True
+ def public_key_auth_supported(self):
+ return True
+ def validate_public_key(self, username, key):
+ """Called by asyncssh for each presented public key. Returns True
+ if the key is registered for this username on some Transfer server.
-class _MiniStackSFTPServer(asyncssh.SFTPServer if _ASYNCSSH_AVAILABLE else object):
- """SFTP filesystem backed by MiniStack's in-memory S3 state.
+ We export the key in OpenSSH format and string-compare against the
+ body stored via `ImportSshPublicKey`. This is deliberately stricter
+ than fingerprint comparison — same key body, exact match.
+ """
+ try:
+ presented_body = key.export_public_key("openssh").decode("utf-8")
+ except Exception as e:
+ logger.debug("SFTP: failed to export presented key: %s", e)
+ return False
+
+ match = _sftp_resolve_user_by_key(username, presented_body)
+ if not match:
+ return False
+
+ account_id, region, server_id, user = match
+ if self._restrict_to_server_id and server_id != self._restrict_to_server_id:
+ return False
+ if _sftp_server_state(account_id, region, server_id) != "ONLINE":
+ return False
+
+ self._resolved = (account_id, region, server_id, user)
+ if self._conn is not None:
+ self._conn.set_extra_info(ministack_user=user)
+ self._conn.set_extra_info(ministack_server_id=server_id)
+ self._conn.set_extra_info(ministack_account_id=account_id)
+ self._conn.set_extra_info(ministack_region=region)
+ return True
+
+
+ class _MiniStackSFTPServer(asyncssh.SFTPServer if _ASYNCSSH_AVAILABLE else object):
+ """SFTP filesystem backed by MiniStack's in-memory S3 state.
+
+ asyncssh instantiates this per session, passing the SSH channel so we
+ can recover the auth metadata stashed by `_MiniStackSSHServer`.
+
+ Subclassing :class:`asyncssh.SFTPServer` (rather than duck-typing) is
+ required so unsupported file ops (statvfs, link, etc.) inherit the
+ base implementations that politely return SSH_FX_OP_UNSUPPORTED to
+ the client instead of crashing the session.
+ """
- asyncssh instantiates this per session, passing the SSH channel so we
- can recover the auth metadata stashed by `_MiniStackSSHServer`.
+ def __init__(self, chan, restrict_to_server_id: Optional[str] = None):
+ if _ASYNCSSH_AVAILABLE:
+ super().__init__(chan)
+ self._chan = chan
+ self._restrict_to_server_id = restrict_to_server_id
+ # asyncssh's SSHServerChannel exposes the parent connection via
+ # ``get_connection``; older versions expose it as ``_conn``.
+ conn = None
+ if hasattr(chan, "get_connection"):
+ conn = chan.get_connection()
+ elif hasattr(chan, "_conn"):
+ conn = chan._conn
+ self._user = conn.get_extra_info("ministack_user") if conn else None
+ self._account_id = conn.get_extra_info("ministack_account_id") if conn else None
+ self._region = conn.get_extra_info("ministack_region") if conn else None
+ self._server_id = conn.get_extra_info("ministack_server_id") if conn else None
+ # Open-file map. Reads use BytesIO over the existing object body;
+ # writes accumulate into a BytesIO that we PUT on close.
+ self._open_files: dict = {}
+ self._next_handle = 1
+
+ def _resolve(self, path):
+ """bytes path → (bucket, key) for the currently authenticated user,
+ within their account context."""
+ from ministack.core.responses import set_request_account_id, set_request_region
+
+ if self._account_id:
+ set_request_account_id(self._account_id)
+ if self._region:
+ set_request_region(self._region)
+ virtual = path.decode("utf-8", errors="replace") if isinstance(path, bytes) else path
+ return _sftp_resolve_s3_target(self._user or {}, virtual)
+
+ @staticmethod
+ def _attrs_for_file(size, mtime):
+ a = SFTPAttrs()
+ a.type = 1 # SSH_FILEXFER_TYPE_REGULAR
+ a.size = size
+ a.uid = 0
+ a.gid = 0
+ a.permissions = 0o100644
+ a.atime = mtime
+ a.mtime = mtime
+ return a
+
+ @staticmethod
+ def _attrs_for_dir(mtime):
+ a = SFTPAttrs()
+ a.type = 2 # SSH_FILEXFER_TYPE_DIRECTORY
+ a.size = 0
+ a.uid = 0
+ a.gid = 0
+ a.permissions = 0o040755
+ a.atime = mtime
+ a.mtime = mtime
+ return a
+
+ # ---- path / metadata ops --------------------------------------------
+
+ def realpath(self, path):
+ virtual = path.decode("utf-8", errors="replace")
+ return _sftp_normalize_virtual_path(virtual).encode("utf-8")
+
+ def stat(self, path):
+ bucket, key = self._resolve(path)
+ if not bucket:
+ return self._attrs_for_dir(int(time.time()))
+ obj = _sftp_s3_get_object(self._account_id, bucket, key)
+ if obj:
+ return self._attrs_for_file(obj.get("size", 0), int(time.time()))
+ prefix = key.rstrip("/") + "/" if key else ""
+ for _ in _sftp_s3_list_keys(self._account_id, bucket, prefix):
+ return self._attrs_for_dir(int(time.time()))
+ if _sftp_s3_bucket(self._account_id, bucket) is None:
+ raise asyncssh.SFTPNoSuchFile(f"No such bucket: {bucket}")
+ raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
- Subclassing :class:`asyncssh.SFTPServer` (rather than duck-typing) is
- required so unsupported file ops (statvfs, link, etc.) inherit the
- base implementations that politely return SSH_FX_OP_UNSUPPORTED to
- the client instead of crashing the session.
- """
+ def lstat(self, path):
+ return self.stat(path)
- def __init__(self, chan, restrict_to_server_id: Optional[str] = None):
- if _ASYNCSSH_AVAILABLE:
- super().__init__(chan)
- self._chan = chan
- self._restrict_to_server_id = restrict_to_server_id
- # asyncssh's SSHServerChannel exposes the parent connection via
- # ``get_connection``; older versions expose it as ``_conn``.
- conn = None
- if hasattr(chan, "get_connection"):
- conn = chan.get_connection()
- elif hasattr(chan, "_conn"):
- conn = chan._conn
- self._user = conn.get_extra_info("ministack_user") if conn else None
- self._account_id = conn.get_extra_info("ministack_account_id") if conn else None
- self._region = conn.get_extra_info("ministack_region") if conn else None
- self._server_id = conn.get_extra_info("ministack_server_id") if conn else None
- # Open-file map. Reads use BytesIO over the existing object body;
- # writes accumulate into a BytesIO that we PUT on close.
- self._open_files: dict = {}
- self._next_handle = 1
-
- def _resolve(self, path):
- """bytes path → (bucket, key) for the currently authenticated user,
- within their account context."""
- from ministack.core.responses import set_request_account_id, set_request_region
-
- if self._account_id:
- set_request_account_id(self._account_id)
- if self._region:
- set_request_region(self._region)
- virtual = path.decode("utf-8", errors="replace") if isinstance(path, bytes) else path
- return _sftp_resolve_s3_target(self._user or {}, virtual)
-
- @staticmethod
- def _attrs_for_file(size, mtime):
- a = SFTPAttrs()
- a.type = 1 # SSH_FILEXFER_TYPE_REGULAR
- a.size = size
- a.uid = 0
- a.gid = 0
- a.permissions = 0o100644
- a.atime = mtime
- a.mtime = mtime
- return a
-
- @staticmethod
- def _attrs_for_dir(mtime):
- a = SFTPAttrs()
- a.type = 2 # SSH_FILEXFER_TYPE_DIRECTORY
- a.size = 0
- a.uid = 0
- a.gid = 0
- a.permissions = 0o040755
- a.atime = mtime
- a.mtime = mtime
- return a
-
- # ---- path / metadata ops --------------------------------------------
-
- def realpath(self, path):
- virtual = path.decode("utf-8", errors="replace")
- return _sftp_normalize_virtual_path(virtual).encode("utf-8")
-
- def stat(self, path):
- bucket, key = self._resolve(path)
- if not bucket:
- return self._attrs_for_dir(int(time.time()))
- obj = _sftp_s3_get_object(self._account_id, bucket, key)
- if obj:
- return self._attrs_for_file(obj.get("size", 0), int(time.time()))
- prefix = key.rstrip("/") + "/" if key else ""
- for _ in _sftp_s3_list_keys(self._account_id, bucket, prefix):
- return self._attrs_for_dir(int(time.time()))
- if _sftp_s3_bucket(self._account_id, bucket) is None:
- raise asyncssh.SFTPNoSuchFile(f"No such bucket: {bucket}")
- raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
-
- def lstat(self, path):
- return self.stat(path)
-
- def fstat(self, file_obj):
- h = self._open_files.get(file_obj)
- if not h:
- raise asyncssh.SFTPFailure("Bad file handle")
- size = h["size"] if h["mode"] == "read" else len(h["buf"].getvalue())
- return self._attrs_for_file(size, h.get("mtime", int(time.time())))
-
- def setstat(self, path, attrs):
- # No-op so `sftp -p` and rsync don't fail on the mode/time copy.
- return None
+ def fstat(self, file_obj):
+ h = self._open_files.get(file_obj)
+ if not h:
+ raise asyncssh.SFTPFailure("Bad file handle")
+ size = h["size"] if h["mode"] == "read" else len(h["buf"].getvalue())
+ return self._attrs_for_file(size, h.get("mtime", int(time.time())))
- def fsetstat(self, file_obj, attrs):
- return None
+ def setstat(self, path, attrs):
+ # No-op so `sftp -p` and rsync don't fail on the mode/time copy.
+ return None
- def lsetstat(self, path, attrs):
- return None
+ def fsetstat(self, file_obj, attrs):
+ return None
- # ---- directory ops ---------------------------------------------------
+ def lsetstat(self, path, attrs):
+ return None
- async def scandir(self, path):
- bucket, key = self._resolve(path)
- seen_names: set = set()
+ # ---- directory ops ---------------------------------------------------
- for special in (".", ".."):
- attrs = self._attrs_for_dir(int(time.time()))
- yield SFTPName(
- filename=special.encode("utf-8"),
- longname=self._format_longname(special, attrs).encode("utf-8"),
- attrs=attrs,
- )
+ async def scandir(self, path):
+ bucket, key = self._resolve(path)
+ seen_names: set = set()
- if not bucket:
- virtual = path.decode("utf-8", errors="replace") if isinstance(path, bytes) else path
- virtual = _sftp_normalize_virtual_path(virtual)
- sub_entries: set = set()
- for mapping in (self._user or {}).get("HomeDirectoryMappings", []) or []:
- entry = _sftp_normalize_virtual_path(mapping.get("Entry", "/"))
- if entry == virtual:
- continue
- if entry.startswith(virtual.rstrip("/") + "/") or virtual == "/":
- suffix = entry[len(virtual.rstrip("/")) + 1:].split("/")[0]
- if suffix:
- sub_entries.add(suffix)
- for name in sorted(sub_entries):
- if name in seen_names:
- continue
- seen_names.add(name)
+ for special in (".", ".."):
attrs = self._attrs_for_dir(int(time.time()))
yield SFTPName(
- filename=name.encode("utf-8"),
- longname=self._format_longname(name, attrs).encode("utf-8"),
+ filename=special.encode("utf-8"),
+ longname=self._format_longname(special, attrs).encode("utf-8"),
attrs=attrs,
)
- return
- prefix = key.rstrip("/") + "/" if key else ""
- b = _sftp_s3_bucket(self._account_id, bucket)
- if b is None:
- return
-
- for full_key in sorted(b.get("objects", {}).keys()):
- if not full_key.startswith(prefix):
- continue
- remainder = full_key[len(prefix):]
- if not remainder:
- continue
- head, sep, _ = remainder.partition("/")
- if sep:
- if head in seen_names:
+ if not bucket:
+ virtual = path.decode("utf-8", errors="replace") if isinstance(path, bytes) else path
+ virtual = _sftp_normalize_virtual_path(virtual)
+ sub_entries: set = set()
+ for mapping in (self._user or {}).get("HomeDirectoryMappings", []) or []:
+ entry = _sftp_normalize_virtual_path(mapping.get("Entry", "/"))
+ if entry == virtual:
+ continue
+ if entry.startswith(virtual.rstrip("/") + "/") or virtual == "/":
+ suffix = entry[len(virtual.rstrip("/")) + 1:].split("/")[0]
+ if suffix:
+ sub_entries.add(suffix)
+ for name in sorted(sub_entries):
+ if name in seen_names:
+ continue
+ seen_names.add(name)
+ attrs = self._attrs_for_dir(int(time.time()))
+ yield SFTPName(
+ filename=name.encode("utf-8"),
+ longname=self._format_longname(name, attrs).encode("utf-8"),
+ attrs=attrs,
+ )
+ return
+
+ prefix = key.rstrip("/") + "/" if key else ""
+ b = _sftp_s3_bucket(self._account_id, bucket)
+ if b is None:
+ return
+
+ for full_key in sorted(b.get("objects", {}).keys()):
+ if not full_key.startswith(prefix):
continue
- seen_names.add(head)
- attrs = self._attrs_for_dir(int(time.time()))
- yield SFTPName(
- filename=head.encode("utf-8"),
- longname=self._format_longname(head, attrs).encode("utf-8"),
- attrs=attrs,
- )
- else:
- if head in seen_names:
+ remainder = full_key[len(prefix):]
+ if not remainder:
continue
- seen_names.add(head)
- obj = b["objects"][full_key]
- attrs = self._attrs_for_file(obj.get("size", 0), int(time.time()))
- yield SFTPName(
- filename=head.encode("utf-8"),
- longname=self._format_longname(head, attrs).encode("utf-8"),
- attrs=attrs,
- )
-
- def _format_longname(self, name, attrs) -> str:
- """ls-l-style line for asyncssh's longname field."""
- is_dir = attrs.type == 2
- mode_str = "drwxr-xr-x" if is_dir else "-rw-r--r--"
- size = attrs.size or 0
- mtime = attrs.mtime or int(time.time())
- ts = time.strftime("%b %d %H:%M", time.localtime(mtime))
- return f"{mode_str} 1 ministack ministack {size:>10d} {ts} {name}"
-
- def mkdir(self, path, attrs):
- bucket, key = self._resolve(path)
- if not bucket:
- raise asyncssh.SFTPFailure("Cannot create directory above bucket level")
- if not key:
+ head, sep, _ = remainder.partition("/")
+ if sep:
+ if head in seen_names:
+ continue
+ seen_names.add(head)
+ attrs = self._attrs_for_dir(int(time.time()))
+ yield SFTPName(
+ filename=head.encode("utf-8"),
+ longname=self._format_longname(head, attrs).encode("utf-8"),
+ attrs=attrs,
+ )
+ else:
+ if head in seen_names:
+ continue
+ seen_names.add(head)
+ obj = b["objects"][full_key]
+ attrs = self._attrs_for_file(obj.get("size", 0), int(time.time()))
+ yield SFTPName(
+ filename=head.encode("utf-8"),
+ longname=self._format_longname(head, attrs).encode("utf-8"),
+ attrs=attrs,
+ )
+
+ def _format_longname(self, name, attrs) -> str:
+ """ls-l-style line for asyncssh's longname field."""
+ is_dir = attrs.type == 2
+ mode_str = "drwxr-xr-x" if is_dir else "-rw-r--r--"
+ size = attrs.size or 0
+ mtime = attrs.mtime or int(time.time())
+ ts = time.strftime("%b %d %H:%M", time.localtime(mtime))
+ return f"{mode_str} 1 ministack ministack {size:>10d} {ts} {name}"
+
+ def mkdir(self, path, attrs):
+ bucket, key = self._resolve(path)
+ if not bucket:
+ raise asyncssh.SFTPFailure("Cannot create directory above bucket level")
+ if not key:
+ return None
+ placeholder_key = key.rstrip("/") + "/"
+ _sftp_s3_put_object(self._account_id, bucket, placeholder_key, b"")
return None
- placeholder_key = key.rstrip("/") + "/"
- _sftp_s3_put_object(self._account_id, bucket, placeholder_key, b"")
- return None
- def rmdir(self, path):
- bucket, key = self._resolve(path)
- if not bucket or not key:
- raise asyncssh.SFTPFailure("Cannot remove bucket root via SFTP")
- prefix = key.rstrip("/") + "/"
- children = [k for k in _sftp_s3_list_keys(self._account_id, bucket, prefix) if k != prefix]
- if children:
- raise asyncssh.SFTPFailure(f"Directory not empty: {path!r}")
- _sftp_s3_delete_object(self._account_id, bucket, prefix)
- return None
-
- def remove(self, path):
- bucket, key = self._resolve(path)
- if not bucket or not key:
- raise asyncssh.SFTPNoSuchFile(f"Cannot remove {path!r}")
- if not _sftp_s3_delete_object(self._account_id, bucket, key):
- raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
- return None
-
- def rename(self, oldpath, newpath):
- return self._do_rename(oldpath, newpath, allow_overwrite=False)
-
- def posix_rename(self, oldpath, newpath):
- return self._do_rename(oldpath, newpath, allow_overwrite=True)
-
- def _do_rename(self, oldpath, newpath, *, allow_overwrite: bool):
- src_bucket, src_key = self._resolve(oldpath)
- dst_bucket, dst_key = self._resolve(newpath)
- if not src_bucket or not src_key:
- raise asyncssh.SFTPNoSuchFile(f"No such file: {oldpath!r}")
- src_obj = _sftp_s3_get_object(self._account_id, src_bucket, src_key)
- if src_obj is None:
- raise asyncssh.SFTPNoSuchFile(f"No such file: {oldpath!r}")
- if not dst_bucket:
- raise asyncssh.SFTPFailure("Cannot rename above bucket level")
- if not allow_overwrite and _sftp_s3_get_object(self._account_id, dst_bucket, dst_key):
- raise asyncssh.SFTPFailure(f"Destination exists: {newpath!r}")
- # S3 has no atomic rename — copy + delete.
- _sftp_s3_put_object(self._account_id, dst_bucket, dst_key, src_obj.get("body", b""))
- _sftp_s3_delete_object(self._account_id, src_bucket, src_key)
- return None
-
- # ---- file ops --------------------------------------------------------
-
- def open(self, path, pflags, attrs):
- # asyncssh masks: SSH_FXF_READ=0x01, SSH_FXF_WRITE=0x02,
- # SSH_FXF_APPEND=0x04, SSH_FXF_CREAT=0x08, SSH_FXF_TRUNC=0x10,
- # SSH_FXF_EXCL=0x20.
- bucket, key = self._resolve(path)
- if not bucket or not key:
- raise asyncssh.SFTPFailure("Open requires bucket+key")
+ def rmdir(self, path):
+ bucket, key = self._resolve(path)
+ if not bucket or not key:
+ raise asyncssh.SFTPFailure("Cannot remove bucket root via SFTP")
+ prefix = key.rstrip("/") + "/"
+ children = [k for k in _sftp_s3_list_keys(self._account_id, bucket, prefix) if k != prefix]
+ if children:
+ raise asyncssh.SFTPFailure(f"Directory not empty: {path!r}")
+ _sftp_s3_delete_object(self._account_id, bucket, prefix)
+ return None
- wants_write = bool(pflags & 0x02)
- wants_create = bool(pflags & 0x08)
- wants_truncate = bool(pflags & 0x10)
- wants_excl = bool(pflags & 0x20)
+ def remove(self, path):
+ bucket, key = self._resolve(path)
+ if not bucket or not key:
+ raise asyncssh.SFTPNoSuchFile(f"Cannot remove {path!r}")
+ if not _sftp_s3_delete_object(self._account_id, bucket, key):
+ raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
+ return None
- existing = _sftp_s3_get_object(self._account_id, bucket, key)
+ def rename(self, oldpath, newpath):
+ return self._do_rename(oldpath, newpath, allow_overwrite=False)
+
+ def posix_rename(self, oldpath, newpath):
+ return self._do_rename(oldpath, newpath, allow_overwrite=True)
+
+ def _do_rename(self, oldpath, newpath, *, allow_overwrite: bool):
+ src_bucket, src_key = self._resolve(oldpath)
+ dst_bucket, dst_key = self._resolve(newpath)
+ if not src_bucket or not src_key:
+ raise asyncssh.SFTPNoSuchFile(f"No such file: {oldpath!r}")
+ src_obj = _sftp_s3_get_object(self._account_id, src_bucket, src_key)
+ if src_obj is None:
+ raise asyncssh.SFTPNoSuchFile(f"No such file: {oldpath!r}")
+ if not dst_bucket:
+ raise asyncssh.SFTPFailure("Cannot rename above bucket level")
+ if not allow_overwrite and _sftp_s3_get_object(self._account_id, dst_bucket, dst_key):
+ raise asyncssh.SFTPFailure(f"Destination exists: {newpath!r}")
+ # S3 has no atomic rename — copy + delete.
+ _sftp_s3_put_object(self._account_id, dst_bucket, dst_key, src_obj.get("body", b""))
+ _sftp_s3_delete_object(self._account_id, src_bucket, src_key)
+ return None
- if wants_write:
- if existing and wants_excl:
- raise asyncssh.SFTPFailure(f"File exists: {path!r}")
- if not existing and not wants_create:
+ # ---- file ops --------------------------------------------------------
+
+ def open(self, path, pflags, attrs):
+ # asyncssh masks: SSH_FXF_READ=0x01, SSH_FXF_WRITE=0x02,
+ # SSH_FXF_APPEND=0x04, SSH_FXF_CREAT=0x08, SSH_FXF_TRUNC=0x10,
+ # SSH_FXF_EXCL=0x20.
+ bucket, key = self._resolve(path)
+ if not bucket or not key:
+ raise asyncssh.SFTPFailure("Open requires bucket+key")
+
+ wants_write = bool(pflags & 0x02)
+ wants_create = bool(pflags & 0x08)
+ wants_truncate = bool(pflags & 0x10)
+ wants_excl = bool(pflags & 0x20)
+
+ existing = _sftp_s3_get_object(self._account_id, bucket, key)
+
+ if wants_write:
+ if existing and wants_excl:
+ raise asyncssh.SFTPFailure(f"File exists: {path!r}")
+ if not existing and not wants_create:
+ raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
+ initial = b"" if (wants_truncate or not existing) else existing.get("body", b"")
+ handle = self._next_handle
+ self._next_handle += 1
+ self._open_files[handle] = {
+ "mode": "write",
+ "bucket": bucket,
+ "key": key,
+ "buf": io.BytesIO(initial),
+ "size": len(initial),
+ "mtime": int(time.time()),
+ }
+ return handle
+
+ # Read mode
+ if not existing:
raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
- initial = b"" if (wants_truncate or not existing) else existing.get("body", b"")
handle = self._next_handle
self._next_handle += 1
+ body = existing.get("body", b"")
self._open_files[handle] = {
- "mode": "write",
+ "mode": "read",
"bucket": bucket,
"key": key,
- "buf": io.BytesIO(initial),
- "size": len(initial),
+ "buf": io.BytesIO(body),
+ "size": len(body),
"mtime": int(time.time()),
}
return handle
- # Read mode
- if not existing:
- raise asyncssh.SFTPNoSuchFile(f"No such file: {path!r}")
- handle = self._next_handle
- self._next_handle += 1
- body = existing.get("body", b"")
- self._open_files[handle] = {
- "mode": "read",
- "bucket": bucket,
- "key": key,
- "buf": io.BytesIO(body),
- "size": len(body),
- "mtime": int(time.time()),
- }
- return handle
-
- def read(self, file_obj, offset, size):
- h = self._open_files.get(file_obj)
- if not h:
- raise asyncssh.SFTPFailure("Bad file handle")
- h["buf"].seek(offset)
- data = h["buf"].read(size)
- return data if data else b""
-
- def write(self, file_obj, offset, data):
- h = self._open_files.get(file_obj)
- if not h:
- raise asyncssh.SFTPFailure("Bad file handle")
- if h["mode"] != "write":
- raise asyncssh.SFTPFailure("File not open for writing")
- h["buf"].seek(offset)
- h["buf"].write(data)
- return len(data)
-
- def close(self, file_obj):
- h = self._open_files.pop(file_obj, None)
- if not h:
+ def read(self, file_obj, offset, size):
+ h = self._open_files.get(file_obj)
+ if not h:
+ raise asyncssh.SFTPFailure("Bad file handle")
+ h["buf"].seek(offset)
+ data = h["buf"].read(size)
+ return data if data else b""
+
+ def write(self, file_obj, offset, data):
+ h = self._open_files.get(file_obj)
+ if not h:
+ raise asyncssh.SFTPFailure("Bad file handle")
+ if h["mode"] != "write":
+ raise asyncssh.SFTPFailure("File not open for writing")
+ h["buf"].seek(offset)
+ h["buf"].write(data)
+ return len(data)
+
+ def close(self, file_obj):
+ h = self._open_files.pop(file_obj, None)
+ if not h:
+ return None
+ if h["mode"] == "write":
+ _sftp_s3_put_object(self._account_id, h["bucket"], h["key"], h["buf"].getvalue())
return None
- if h["mode"] == "write":
- _sftp_s3_put_object(self._account_id, h["bucket"], h["key"], h["buf"].getvalue())
- return None
- def fsync(self, file_obj):
- return None
+ def fsync(self, file_obj):
+ return None
- # ---- explicitly unsupported -----------------------------------------
+ # ---- explicitly unsupported -----------------------------------------
- def link(self, oldpath, newpath):
- raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support hardlinks")
+ def link(self, oldpath, newpath):
+ raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support hardlinks")
- def symlink(self, oldpath, newpath):
- raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support symlinks")
+ def symlink(self, oldpath, newpath):
+ raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support symlinks")
- def readlink(self, path):
- raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support symlinks")
+ def readlink(self, path):
+ raise asyncssh.SFTPOpUnsupported("S3-backed SFTP does not support symlinks")
- def lock(self, file_obj, offset, length, flags):
- return None
+ def lock(self, file_obj, offset, length, flags):
+ return None
- def unlock(self, file_obj, offset, length):
- return None
+ def unlock(self, file_obj, offset, length):
+ return None
- def exit(self):
- # Flush handles the client forgot to close.
- for handle in list(self._open_files):
- self.close(handle)
+ def exit(self):
+ # Flush handles the client forgot to close.
+ for handle in list(self._open_files):
+ self.close(handle)
# ── SFTP lifecycle — called from app.py lifespan + Create/Delete handlers ──
@@ -1207,6 +1223,7 @@ async def sftp_start() -> None:
if not _sftp_enabled():
logger.info("SFTP: disabled (asyncssh missing or SFTP_ENABLED=0)")
return
+ _ensure_sftp_runtime()
global _sftp_shared_acceptor, _sftp_next_per_server_port
_sftp_next_per_server_port = _per_server_base_port()
@@ -1261,6 +1278,7 @@ async def sftp_start_server_listener(server_id: str) -> Optional[int]:
"""
if not (_sftp_enabled() and _port_per_server()):
return None
+ _ensure_sftp_runtime()
global _sftp_next_per_server_port
if _sftp_next_per_server_port is None:
_sftp_next_per_server_port = _per_server_base_port()