mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
cd0f60a2f0858c07ea202b00ebf8df19e65a10a2
238
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2f300c2969 |
s3api: keep the in-flight upload counters 64-bit aligned on 32-bit (#13321)
The recursiveListDeclined sync.Map placed ahead of inFlightDataSize and inFlightUploads moved them off 8-byte alignment on 386, so the first throttled upload panicked with "unaligned 64-bit atomic operation". atomic.Int64 is aligned wherever it sits in the struct. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f599f870a8 |
s3: list without a delimiter from one range of the filer store (#13263)
* s3: -s3.listRecursiveFromStore, on by default Lets an operator keep recursive listings on the directory walk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * s3: list without a delimiter from one range of the filer store A bucket that never had versioning is listed with ListEntriesRecursive: one read of the bucket's path range per page instead of one directory listing per directory. A folder object's "<dir>/" key waits for its place in key order, and the folder objects whose rows sort before the range (the one the prefix names, those the marker ends inside of) are looked up. .uploads is skipped; a .versions folder hands the page to the walk, as does a filer that answers Unimplemented, which is then not asked again for a minute. The test pages through both ways over the same tree, for prefixes, markers and page sizes, and expects the same keys, sizes, ETags and markers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * test/postgres_flat: a range-read gateway lists what the walking one does A second S3 gateway with -listRecursiveFromStore=false runs on the same filer. ListObjectsV2 and V1 pages agree for prefixes, markers and page sizes over folder objects, a prefix object, an unfinished upload and +/-/0 neighbours. Listing 60 keys five directories deep scans the bucket table 2 times from the range read and 302 times from the walk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * s3: range-read listings without the -s3.listRecursiveFromStore flag A filer whose store cannot list a range answers Unimplemented and the gateway already walks that bucket's directories instead, so the flag only switched off a path that falls back by itself. The unit test forces the walk through the decline cache, and the postgres_flat test checks pages against the keys in byte order rather than against a second gateway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: step a range-read listing over the bucket's upload parts The walk skips the bucket's .uploads folder as one entry, but a range read from the bucket root streamed every part of every unfinished upload and dropped them, one 1024-row window after another, on each first page. Every path under .uploads/ sorts before ".uploads0", so the read resumes there and looks up the one key with that name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: list a waiting folder object once a row passes its key A range-read page queued every childless folder object until a file row arrived, so max-keys=1 over a bucket of empty folders read the whole bucket before answering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: forget a deleted bucket's recursive-listing decline Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b1f86ddfa2 |
s3: support PutBucketDefaultStorageClass and GetBucketDefaultStorageClass (#13282)
* s3: add PutBucketDefaultStorageClass and GetBucketDefaultStorageClass The setting is kept in the bucket entry's extended attributes next to the other bucket configuration, so every gateway sees it through the bucket config cache. Only STANDARD and INTELLIGENT_TIERING are accepted, matching the AWS model; STANDARD clears the stored value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: give new objects the bucket default storage class PutObject, POST uploads, CreateMultipartUpload and CopyObject store the bucket default when the request names no storage class. The request headers are left alone, so bucket-policy storage-class conditions and the self-copy change check still see only what the client sent. Upload parts are not tagged; a completed upload takes the class recorded when it was initiated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: test the bucket default storage class APIs and write default Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: fail a write whose bucket default storage class cannot be read A failed bucket config lookup used to fall back to STANDARD, so a write could store a different class than the bucket default asks for. The write now returns the lookup error instead. A request that names its own class still needs no lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: give extracted ZIP directory members the bucket default storage class Directory members are created through mkdir rather than putToFiler, so they stored no class while the files next to them did. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: reject a default storage class body with trailing data The decoder stopped after the first element, so a valid configuration followed by another element or stray bytes was accepted. The body is now read with a size bound and only whitespace, comments or processing instructions may follow the configuration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * go.mod: bump aws-sdk-go-v2/service/s3 to v1.117.1 The release adds the PutBucketDefaultStorageClass and GetBucketDefaultStorageClass client operations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: test the bucket default storage class through the AWS SDK Covers get/set, an unsupported class, the setting stored in the bucket entry and read back by a fresh bucket config, PUT, explicit classes, multipart initiation, copy, existing objects, and per-API grants. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: let each default storage class subtest set up its own state Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: assert the explicit STANDARD class exactly in the default class test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: note that the bucket default storage class is a label only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
284d491587 |
s3: forward notification topics to webhook targets (#13245)
* util: move the guarded dialer out of the volume server The deny list and the dialer that re-checks every resolved address at connect time move into weed/util/netguard, with the allow-private knob as a policy, so other outbound clients can dial through the same guard. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: fence consumer group position saves by generation A position saved with a generation is written only while the stored one carries no newer generation, or the same generation from another writer: the save reads the stored position and writes on the condition that it is unchanged, routed to the entry's owner filer, and re-reads when another writer got there first. A single consumer that elects itself can then store its offsets without a deposed predecessor overwriting them. Saves without a generation keep overwriting as before. Loading a missing position now reports ErrNotFound instead of trying every filer and marking each one failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: post bucket event batches to a webhook target A webhook destination renders a batch of records as one {"Records":[...]} body, posts it with the target's bearer token, and takes any 2xx as delivered. The renderer is a function the destination holds, a stand-in that refuses until the record renderer lands. It dials through the guarded dialer under a new Local policy, which refuses metadata-service, link-local and unspecified addresses at connect time but lets an operator point a target at a private host or a sidecar on loopback. Redirects are followed only to the endpoint's own host and never down from https. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: forward each target's topic to its destination A Forwarder runs beside the Publisher on every gateway. Each enabled target with a destination gets a lock, s3.notify.<target>, held through LockClient.StartLongLivedLock, so one gateway forwards a target and targets spread across gateways; a topic target has none. The holder runs one loop per partition of the target's topic: fetch from the stored offset at the partition's leader, decode the records, deliver them as one batch, store the next offset. A fetch that stops short at a segment boundary just continues from its next offset. A failed send, a rejected one included, blocks the partition and is retried with capped backoff, and the offset is stored only after the destination took the batch. An offset that retention removed skips to the earliest one and counts the gap. Offsets go to the consumer group offset storage under group forwarder, fenced by the lock generation. On taking the lock a forwarder stores each partition's offset back under its generation, so an older holder's saves are refused and it stops. A stored generation at or above its own means the lock was lost, unless the forwarder has since held the lock through a full renewal, which happens only when the lock server's counter restarted; it then fences above the stored generation. Metrics per target: records delivered, send retries, retention gaps, and lag from the forwarding gateway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: run notification forwarders beside the publisher Every gateway with filers starts a Forwarder with the publisher. It elects itself per target through the gateway's object-write lock client, stores offsets in the filer, reads through the same brokers the publisher uses, follows the target registry as the publisher does, and releases its locks on shutdown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: post a test event to a webhook on its own The renderer refuses an s3:TestEvent that shares a body with other records, so a webhook splits a batch around each one and posts them in order, the test event as its own body. The test is a stand-in until the renderer's lands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: skip a bucket event record that can never be delivered A record that does not decode, or that the renderer refuses, used to be retried like a failed send and would block its partition for good. The webhook now renders a whole batch before posting any of it and names the records that cannot render; the forwarder drops those, counts them per target and reason in notification_skipped_records_total, logs each offset once, and sends the rest. Only transport and HTTP failures are retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: read a fenced position save at the filer that applies it The fenced save read the stored position from whichever filer answered and then sent its conditional write to the key's owner, so with filers that keep their own stores the condition could be checked against an entry other than the one read, failing until replication caught up or judging a stale copy. The storage now takes the ring's owner lookup, the one route-by-key writes already use, and sends both the read and the write to that filer. The gateway hands its object-write lock client's PrimaryForKey to the forwarder offsets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: follow a repartitioned notification topic A forwarder listed its topic's partitions once, when it took the lock, so a repartition left the new partitions unforwarded until the lock moved. It now lists them again every 30 seconds, starts a loop for each new partition, and marks the loops of partitions no longer listed as replaced; such a loop keeps delivering what its partition holds and ends once it has caught up. A failed fetch now looks up the leader of that exact partition, not of any partition with the same range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: let the first forwarder take the lock before the second asks The election test synced both gateways at once, and each forwarder asks for its lock from its own goroutine, so the second could ask first and store the offsets the test expected from the first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: warn when a partition returns nothing below its high-water mark A fetch that returned no records and kept its next offset below the high-water mark looked like an idle partition, so the forwarder waited without a word while its lag stayed up. It still waits, since skipping would lose the records, but now warns at most once a minute with the topic, partition, offset and high-water mark, so the lag has an explanation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: render webhook bodies with the bucket event renderer The webhook now renders through Render and posts each s3:TestEvent alone by IsTestEvent, replacing the stand-ins it held until the renderer landed. The tests send real records and read the object keys and test request ids back out of the bodies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * netguard: refuse the IPv6 and Alibaba metadata service addresses AWS's IPv6 metadata address fd00:ec2::254 is unique-local and Alibaba's 100.100.100.200 sits in the CGNAT range, so the Private and Local policies let a webhook or remote endpoint reach them. Refuse both under every policy, like 169.254.169.254. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * grafana: chart the notification forwarder metrics Add an S3 Notifications row with delivered records, lag, send retries, and records skipped or lost to retention per target. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: follow only webhook redirects that keep the POST On a 301, 302 or 303 Go resends the request as a GET without a body, so an endpoint that redirected and then answered 2xx counted as delivered while it received no records. Only 307 and 308, which keep the method and resend the body, are followed now; any other redirect fails the send and is retried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep webhook endpoint secrets out of errors and logs The guarded dialer names its endpoint in every refusal, and the forwarder logs that error, so a webhook endpoint carrying credentials in its userinfo or a token in its query had them written to the log. The dialer now gets the endpoint as scheme, host and path only, and the parse and request errors no longer echo the URL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: load a consumer group position from its owner filer A forwarder taking over read its start offset from whichever filer answered, while its fenced saves read and write at the key's owner. With filers that keep their own stores, a replica still holding an older offset handed the new holder that offset, which it then stored under its higher generation at the owner, replaying everything delivered since. Loads now go to the owner too when the storage knows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound consumer group position loads and saves by the caller LoadConsumerGroupPosition and SaveConsumerGroupPosition ran their filer calls under context.Background(), so a filer whose store stalled held a forwarder's save forever: ending the lead waited on it, the lock was never released, and Close hung while the lock kept renewing. Both now take the caller's context; the forwarder gives each call its RPC deadline under the lead's context, so stopping returns and the lock is released. The offset wrappers the broker uses keep their signatures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: list a consumer group's positions across partition generations ListConsumerGroupPositions walks every generation and range directory of a topic and returns the group's stored position in each, keyed by partition directory, so a consumer can tell which ranges it holds offsets for that the topic no longer lists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: stop forwarding ranges a repartition removed A repartition drops the old assignments, and the broker serves only assigned ranges, so the loop draining a removed range retried a refused fetch forever, and after a restart nothing looked at it at all. Reading a removed range's flushed data would need a read-only path in the broker. Until then a removed range's loop delivers the batch it holds and ends, and the forwarder logs an error naming each range it stops and, when it takes the lock, each partition directory holding a stored offset the topic no longer lists. The fake broker now refuses unassigned ranges as the real one does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: deliver what a repartition left in the retired ranges The lookup now offers the sealed ranges a repartition retired, and any broker serves them from their files, so the forwarder no longer drops them. On taking the lock and on each re-list it asks for the retired ranges too and runs a loop for each, from its stored offset up to its high-water mark, after which the loop ends; a range it was forwarding as current and that is now retired gets the same end. A read below a retired range's log start counts as a retention gap, as for a live one. A key's records in a retired range precede its records in the ranges that replaced it, and loops running side by side would not keep that order. So the retired ranges go first, one generation at a time, oldest first, and the current ranges start only once none is left. A range listed neither as assigned nor as retired, as while a drained range is not sealed yet, pauses until it is offered again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: match a retired range to its forwarding loop by directory The broker lists a retired range at the second its generation directory is named for, while the assignment the forwarder started its loop from carried nanoseconds. After a repartition the retired entry missed the running loop, so a second loop started on the same stored offset and delivered the batch the first was still retrying. Key the loops by partition directory; the fake broker now lists retired ranges and the fake positions store offsets at that resolution, like the real ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: replace a paused forwarding loop only once it ended A range drained but not sealed yet is listed neither as assigned nor as retired, so its loop is paused and dropped from the lead's loops while it may still be retrying a batch. Once the range was offered as retired a new loop started at the stored offset and sent that batch again. Keep a paused loop until it ends, and start the range again only then. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: hold the new ranges while a drained one is not sealed yet A repartition saves the new ranges before it drains and seals the old ones, so for a while an old range is offered neither as assigned nor as retired, and the forwarder started the new ranges at once: a key's new records could go out before its records still waiting in the old range. On each look at the topic the forwarder now lists the directories holding a stored offset that the topic does not offer, and probes each at its offset; one that may still hold records past it, refused because it is not sealed, holds the new ranges until it is offered as retired and drained. One that answers with nothing past the stored offset is settled, sealed and empty or already delivered, and stays so for the lead. While holding, the forwarder logs at most once a minute and keeps looking even with no loop running. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: have the fake broker serve only the generation a fetch names The broker now refuses a fetch naming a generation other than the one it assigns for the range, unless that generation is sealed and read as retired. The forwarder tests' fake broker matched an assigned range by its range alone, so it served the live generation to a fetch for an older, unsealed one; it now matches the generation too, as the broker does. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold the current ranges until the stored offsets can be listed A lead whose first look at the stored offsets failed took that as no old range left unsettled and started the current ranges, delivering a key's newer records ahead of the ones still in a drained range that is not sealed yet. A failed look now holds the current ranges as an unsettled range does, and is retried with backoff and on each partition refresh; the current ranges start only after a look succeeds. Retired ranges and loops already running carry on meanwhile. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3api: leave forwarding off on an unusable broker TLS config The forwarder loaded the grpc.msg_broker client TLS config with LoadClientTLS, which exits the process on a bad one, and every gateway with filers builds a forwarder whether or not it has webhook targets. It now loads it as the publisher does: an unusable config is logged and leaves forwarding off while the gateway keeps serving. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold the new ranges for an unsealed old range with no stored offset The check for old ranges still unsealed looked only at ranges holding a forwarder offset. A forwarder starting for the first time while a drained range was not sealed yet had stored none in it, so it started the new ranges and delivered a key's newer records ahead of its older ones. The consumer group listing now names every partition directory of the topic, with no position where the group stored none, and such a range is probed from offset 0. A range with nothing left past that offset, including one whose records retention already removed, is settled. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: check the load in the fenced save race test The test read the stored position back ignoring the load's error, so a failed load panicked on a nil position instead of reporting the error. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: take a partition over at the offset its last holder committed A new forwarder generation claimed a partition by writing the offset it had loaded. When the old generation committed again in between, the claim rewound the stored offset and the new lead replayed what had been delivered since. A fenced save that takes over from an older generation now keeps the offset that generation committed last, rereading it on a conditional write miss, and hands it back in the position, and the forwarder starts from it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: wait for a position's owner filer instead of asking another A position store routed by owner fell back to any filer while the owner of a key was not known yet, as before the lock ring is learned. That filer's not-found ended the load there, though it may only not have caught up, and a claim on it would start the partition over. Loads and fenced saves now fail until the owner is known, and the forwarder retries them; a store without an owner routing still uses any filer. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: wait for the last checkpoint before a forwarder handoff in tests The resume, repartition and election tests stopped the first forwarder once its records were delivered but possibly before their offsets were stored, so they could pass on a replay rather than on a committed handoff. They now wait for the final offsets first. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: have Close wait for removed targets to release their locks A target removed from the registry had its forwarder cancelled and dropped from the targets, so a Close soon after did not wait for it and returned with that target's lock possibly still held. Removed forwarders are now kept until they are done, and Close waits for them as well. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold newer retired generations behind an unsealed older one A range of an old generation still unsealed held back only the current ranges. A generation retired after it was offered and delivered right away, ahead of the older generation's records of the same keys. The unsealed range's generation now counts as the oldest one left, so only that generation's own sealed ranges are forwarded until it is sealed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: check the forwarder lock right before each send A lead checked its lock at the top of each fetch and after a failed send's backoff, so a lead that lost the lock while it fetched a batch still sent it, and the next holder sent it again. The lock is now checked right before each send. Delivery stays at-least-once: a lock lost during a send cancels that send once the lead notices, which may be after the endpoint took the batch. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: read a retired range past a broker that answers with an error Any broker serves a retired range from its files, but a fetch took the first broker's answer even when it was a storage error, and each retry asked that broker first again, so one broker that could not read the files held the range up for good. A retired fetch answered with an error other than an offset out of range now goes on to the next broker, and returns the error only when none could read it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: count ranges held back behind an older generation in the lag The lag gauge summed what each running loop reported, so the current ranges held back while an older generation was still unsealed, and the retired generations waiting their turn, showed no lag however much piled up in them. On each partition refresh the lead now reports their lag from the stored offset to the high-water mark, read from the range's leader or the retired listing, and drops the lag of ranges it no longer has. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: hold retired generations too while stored offsets cannot be listed A lead whose look at the stored offsets failed held only the current ranges and went on forwarding retired generations, though an older generation it could not see might still be unsealed and hold earlier records of the same keys. A failed look now holds every range not yet running until a look succeeds; loops already running carry on. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: read stored offsets only of the ranges a lead does not know yet The check for unsettled ranges listed every partition directory and read every stored offset in it one by one under one deadline, before dropping the ranges the topic offers and those already found settled. A topic with many past generations could take longer than the deadline on every refresh and hold a new lead for good. The listing now takes the directories to skip and reads only the remaining offsets, a few at a time, and the lead skips the offered ranges and those it found settled. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: test the failed-listing hold with no unsealed range The failed-listing test also had an older generation unsealed, which holds the newer ranges on its own once a listing succeeds, so it did not show the listing guard by itself. A second case has no unsealed range: nothing goes out while the listing fails, and both the retired and the current range do once it succeeds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: stop the lead before marking a failed loop ended A forwarding loop that failed, as on being deposed, was marked ended before it cancelled its lead. A partition refresh in between saw a retired range's loop ended, took the range as delivered, and started the next generation's ranges on the lead that was about to stop. The lead is now cancelled first, so no refresh acts on the failed loop. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: count no retention gap below an offset only claimed A lead claiming a partition with no stored offset wrote offset 0 to fence it before reading anything. A lead that stopped there left 0 behind, and the next one, finding the log start past it, counted those offsets as lost though no forwarder had ever been at them. A claim made before any read is now marked as such, a takeover keeps the marker of the entry it replaces, and only an offset a lead read from counts a gap. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: retry a takeover save at the offset it kept A claim's save that took a partition over from an older generation kept that generation's last offset, but when its reply was lost the retry went out with the offset the claim had loaded. The stored entry was by then the claim's own, so the retry kept nothing and rewound the partition, replaying what had been delivered since. A failed save now retries with the offset and marker the attempt settled on. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: store an offset as read from once the first fetch succeeds A claimed offset lost its claimed marker only when a later save moved it, so a lead that read an empty partition and stopped left it marked as never read. Records published and then removed by retention while no gateway forwarded the target were skipped without a gap counted or logged. The first successful fetch now stores the offset as read from, once per claim, even when it has not moved. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: wait for the stalled topic's publisher before reading it in a test The worker sets the topic publisher up on its own goroutine, which on a loaded host can start after Publish has stopped waiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep what a timed-out offset check settled for the next one A check for unsettled ranges that could not read every stored offset within its deadline returned nothing, so each retry read the same ranges again and a long enough history kept the new ranges held for good. The listing now returns the positions it read along with the error and goes on past one that fails, and the check probes those and keeps the ranges it finds settled before reporting the failure, so the next check reads only the rest. The ranges stay held until a check covers them all. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: say which records the notification lag counts The lag gauge's help, and the dashboard panel with none, read as every undelivered record, but the records of an old range still being sealed after a repartition cannot be read and are not counted. Both now say the gauge covers the current ranges, the ranges held back behind an older generation, and the sealed retired ranges. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3f2f625822 |
s3: publish bucket events to each notification target's MQ topic (#13244)
* mq: report when a published message is acknowledged Publish now returns a channel the publisher closes once the broker acks that message, including an ack that arrives on a later stream after a resend. A caller that has to know its message is stored, such as the S3 gateway answering a request only after its event is durable, can wait on it with its own bound; callers that do not care ignore it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: build bucket event records in the AWS shape An Event is what one operation did to one object; Record turns it into an eventVersion 2.7 record for one rule, and Message wraps that record in the Records envelope a consumer receives. The key is form-encoded per path segment as AWS does it, size and eTag are left off removals, and the sequencer is the filer's commit stamp as 16 hex digits, so one key's sequencers compare as strings in commit order. The s3:TestEvent message is built here too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: publish bucket event records to each target's MQ topic The Publisher runs one worker per enabled target. The worker creates the target's topic, s3.notify-<target> with 4 partitions and 7 days of retention, then hands records to the MQ publisher keyed by bucket/key so one object's events stay in one partition in order. Setup retries with backoff, so a broker that is down or still taking the balancer lock after a cold start delays records instead of losing them. A removed or disabled target's worker stops; its topic is left for retention to age out, since a forwarder may still be draining it. Publish queues every record and waits up to 2 seconds, or until the request ends, for all of them to be acked, and reports whether they were. A record not acked by then stays queued and is still sent; the MQ publisher resends it across leader changes. Each target's queue holds 10000 records; past that, and for records whose target has no worker, a record is dropped. Acked, late and dropped records, the queue depth and the wait are exported as metrics. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: start a bucket event publisher with the gateway The gateway creates one event publisher and syncs it with the target registry whenever the registry loads or changes, so each enabled target gets its topic and worker. The publisher bootstraps from the broker the command started beside the gateway, passed in as MqBroker once it bound, and from every broker the masters list, so a gateway running without its own broker still finds the cluster's. Broker connections use the grpc.msg_broker TLS section. Shutdown stops the workers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: send the test event before storing a notification configuration Unless x-amz-skip-destination-validation is true, PUT notification publishes an s3:TestEvent to the topic of every target the configuration names, in parallel, and fails with InvalidArgument listing the destinations whose topic did not ack it within the publisher's 2 second wait. Nothing is stored in that case. The registry checks still run with the header, and an empty configuration sends nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: publish ObjectCreated events for PUT and POST A PUT, including a "dir/" marker, publishes ObjectCreated:Put and a POST upload ObjectCreated:Post, after the filer commit and before the response, once per matching rule of the bucket's configuration, waiting for the acks within the publisher's bound. A failed write publishes nothing and a slow or absent broker never fails the request. The sequencer is the filer's stamp of the commit. putToFiler records it, from the routed ObjectTransaction or the lock path's CreateEntry, with the committed size, into the request so the handler finds it; the marker write and a create recovered after an ambiguous route return none, and take the gateway's clock instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: publish ObjectCreated events for copy and multipart completion CopyObject, including a metadata-only copy onto itself, publishes ObjectCreated:Copy, and CompleteMultipartUpload publishes ObjectCreated:CompleteMultipartUpload, both after the commit and before the response; a copy that keeps the connection alive publishes before its final answer. The write wrappers these use dropped the transaction response, so they now return the filer's commit stamp: routedMkFile, writeMultipartObject, routedVersionedFinalize, routedMultipartFinalize, routedSelfCopy and finalizeCopyDestination. Writes that go off the owner, through mkFile, still return none and the event takes the gateway's clock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: publish ObjectRemoved events for deletes DeleteObject and DeleteObjects publish ObjectRemoved:DeleteMarkerCreated when a delete without a version id leaves a marker in place of the key, in a versioning-enabled or suspended bucket, and ObjectRemoved:Delete for any other delete, including the delete of a marker by its version id. The record carries the marker's or the deleted version's id. DeleteObjects publishes one event per key it deleted and waits for all of them at once. The routed delete wrappers now return the filer's commit stamp: routedDeleteSpecificVersion, routedDeleteNullVersion, routedDemoteNullVersion and createDeleteMarker; deleteMutationResult carries it to the handler. A suspended delete uses the stamp of the null version's delete, since the marker write after it returns none. Deletes on the lock path go through DeleteEntry, which has no stamp, and take the gateway's clock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: report the ack of a published record too PublishRecord now returns the same ack channel as Publish, so a caller publishing to a topic with a record type can wait for its record to be stored. Both go through doPublish, which registers the waiter for every message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: carry bucket events as schematized records A notification topic now has a record type, EventRecordType, the single source for its flat snake_case columns: the event, requester, bucket and object fields, the commit stamp as sequencer, and multipart columns for later. event_time, event_name and bucket_name are required, the rest optional, and changes to it are additive only. The topic is configured with it, with bucket_name and object_key as key columns and the schema format left empty as for the other schematized topics, and records go out through PublishRecord. The record holds raw values: the object key unencoded, the sequencer as an int64, and nulls where a value is absent, such as size and eTag on removals. Render turns records into the AWS JSON a destination receives, the Records envelope with eventVersion 2.7, a form-encoded key and a hex sequencer, or the test event message for an s3:TestEvent, so forwarders produce exactly the body the gateway used to publish. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: shut a stopped target's publisher down even while it is blocked With the broker away long enough to fill a partition's unacked buffer, the worker blocks inside PublishRecord. Removing, disabling or closing the target only cancelled the worker's context, which the blocked worker never looked at, so the publisher and its queued records lived on and resumed sending once the broker came back. Stopping a target now shuts its MQ publisher down directly, which releases the blocked publish, and does it in the background so Sync and Close do not wait for the flush. A publisher that finishes setting up after the stop is shut down at once, and a worker that dequeues a record after the stop drops it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: publish nothing for a retried multipart completion A CompleteMultipartUpload retried after the object committed is answered from that commit and writes nothing, yet the handler still published an ObjectCreated:CompleteMultipartUpload, with size 0 since no commit was noted. AWS sends the event once, for the completion that created the object, so the handler now publishes only when the request itself committed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: take an event's principal from the authenticated identity only With auth off, the gateway keeps the s3-account-id header the client sent, and an event's principal_id fell back to it, so any client could name itself as the requester in the record a destination trusts. The principal is now the identity name authentication put in the request context, or anonymous. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: turn notifications off instead of exiting on a bad broker TLS config The event publisher loaded the grpc.msg_broker client TLS with LoadClientTLS, which exits the process on a config it cannot use, such as a cert without its key, so a broker-only TLS mistake took the S3 gateway down even with no notification targets. It now loads it with TryLoadClientTLS and, on an error, logs it and runs without a publisher: object writes publish nothing and a notification configuration's test event fails. It never falls back to an insecure connection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: count a record dropped while its request waits only as dropped A record dropped while a request waited for it, by a PublishRecord error or its target being stopped, was counted dropped where it was dropped, and then late when the request's wait ran out, which it also sat through in full. Each queued record now carries a done signal that both its ack and its drop close, so the wait ends as soon as the record's fate is known and the drop is not counted again as late. Late still counts a record that was neither acked nor dropped when the request answered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: let a caller cancel starting a topic publisher NewTopicPublisher returned only once a partition lookup succeeded, and retried the lookup for as long as the broker refused it, with nothing a caller could stop it with. It now takes a context that bounds the start: the topic configuration runs under it, and cancelling it stops the lookup loop and returns an error. A publisher already returned is not affected. Existing callers pass context.Background(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: stop a removed target's publisher that is still starting A target's MQ publisher was started without the worker's context, so a target removed while its partitions had no leader kept its publisher looking them up, and its worker waiting, until a lookup succeeded. The worker's context now bounds the start, so removing or disabling the target ends both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: bound each broker's ConfigureTopic during a target's setup Setup asked each broker in turn to configure the target's topic with the worker's context alone, so a broker that accepted the call and never answered held the worker there for good. Each broker now gets 10 seconds before setup moves on to the next, and a stopped worker does not ask the rest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: stamp a suspended delete's event with its marker write A suspended-bucket delete removes the null version, then writes the null delete marker and points latest at it. Its DeleteMarkerCreated event took the stamp of the first step, so a write landing between the steps got a later sequencer although the marker it lost to is what remained. The event now takes the stamp of the pointer write, the delete's last commit. To get it, MkFile, the gateway's mkFile and updateLatestVersionInDirectory return the CreateEntry stamp, and createNullDeleteMarker returns it. createDeleteMarker's unrouted path and writeMultipartObject off the owner now return their write's stamp too instead of none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound each broker's ConfigureTopic when a publisher starts NewTopicPublisher configures the topic again before its lookups, with no deadline per broker, so a broker that accepted the call and hung held the start until the caller gave up, even with a healthy broker next in the list. Each broker now gets 10s before the next is tried. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: sequence a key's events only with stamps from its owner filer The previous change stamped a suspended delete's DeleteMarkerCreated with the null marker's pointer write, but that write goes to the gateway's default filer, not the key's owner. Filer clocks differ, so a delete could get a smaller sequencer than the PUT before it, and a consumer deduplicating on the sequencer would drop it as stale. Routing the marker write to the owner would move the suspended delete onto the transaction path, a change to the write itself. Until then the event goes back to the stamp of the null version's routed delete on the owner, and gateway clock when the delete is not routed. The same reasoning applies to the other stamps that change began returning from off-owner writes, a delete marker or a multipart object written through mkFile, so those return none again, and MkFile, mkFile and updateLatestVersionInDirectory go back to returning only an error. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3: count each queued record once as acked or dropped, and late apart A drop counted the record as dropped and then closed its done channel, so a request whose wait ran out between the two still saw it pending and counted it late in the same counter. Each queued record now has a terminal outcome, acked or dropped, set once by compare-and-swap, and notification_records_total counts that outcome alone, so every lost record shows as dropped exactly once. Late moves to its own counter, notification_records_late_total, counted once per record when its request stops waiting on it before it is acked or dropped; that record is still counted acked or dropped when it settles. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * s3api: publish the event of a completion recovered after its commit When a finalize committed but returned an error, completeMultipartUpload answered from committedCompletion without noting the commit, so the handler published no ObjectCreated:CompleteMultipartUpload. A retry is answered as a replay and publishes nothing either, so the event was lost although the object exists. The recovery now notes the commit when the stored object holds this attempt's parts, stamped by the gateway clock as the filer's stamp is not known. One answered from another attempt's commit stays silent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: sequence a recovered completion's event with its entry's commit stamp A completion whose finalize committed but returned an error is answered from the stored object, and its event took the gateway clock. The stored entry carries CommitTsNs, the meta log stamp the committing filer gave the write, from the same sequence as the stamps the routed write paths return, and peers that replicate the entry keep it. The event now takes that stamp, and falls back to the gateway clock only for an entry written by a filer that predates it. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
45458336e1 |
s3: run a message queue broker beside every S3 gateway (#13235)
* mq broker: let an embedding command own the broker's start failure and shutdown startQueueServer now returns an error when the broker cannot start instead of exiting, binds its port before creating the broker so one that cannot serve never registers with the master, and stops when an optional shutdownCtx is cancelled. Profiling setup moves to weed mq.broker, since an embedded broker read the standalone command's profile flags. weed mq.broker and weed server -mq.broker still exit on a start failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: run a message queue broker beside the gateway by default weed s3 now starts a broker on -mq.broker.port (17777) once it has reached its filer, using the masters and filer group the filer reports. The broker is its own gRPC server: it binds the gateway's -ip.bind, advertises the address the gateway registers with the master, and joins the cluster like any other broker. It stops with the gateway. A broker that cannot start, say because the port is taken, is logged and the gateway keeps serving. -mq.broker=false turns it off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * server: start the message queue broker with the S3 gateway weed server -s3 now runs a broker beside its gateway, started by the gateway once it reaches the filer. -mq.broker=false leaves it out. An explicit -mq.broker or -mq.agent still starts the broker on its own, and then the gateway does not start a second one. Only that explicit broker exits the server when it cannot start; the one that comes with -s3 is logged, so a host already running a broker on the port keeps its gateway. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mini: run the message queue broker beside the S3 gateway weed mini now starts a broker with its S3 gateway on -mq.broker.port (17777, below the Linux ephemeral range), binding and advertising mini's -ip.bind and -ip like the other services. The port joins mini's port layout, so a taken port moves to the next free one unless it was given explicitly. The broker stops with the gateway, before the filer it flushes to. -mq.broker=false or -s3=false leaves it out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: start the message queue broker with the S3 gateway weed filer -s3 now runs a broker beside its gateway on -s3.mq.broker.port (17777), the same way weed server -s3 does: it binds and advertises where the gateway does, takes the filer's -dataCenter and -rack, stops with the gateway, and a broker that cannot start is logged while the gateway keeps serving. -s3.mq.broker=false leaves it out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mini: list the message queue broker when it is running The S3 gateway now binds its broker's port before it starts serving, as it does for the Iceberg and Lance listeners, and records whether the bind worked. Once mini sees the S3 port answer, the result is final: the progress board shows the broker ready or failed, and the welcome banner lists its address only when it bound. With -mq.broker=false or -s3=false neither shows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep the default broker off the gateway's own ports The broker binds before the gateway binds its ports, so a gateway started with -port=17777, -port.grpc=17777 or -port=7777 (gRPC port 17777) lost its port to the default broker and exited. weed s3, weed server -s3 and weed filer -s3 now compare the broker port with the gateway's HTTP, HTTPS, gRPC, Iceberg, Lance and metrics ports first. A default broker port that clashes skips the broker with a warning; a broker port given on the command line that clashes is an error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mini: reserve explicitly set gRPC ports before placing other ports Mini only kept derived gRPC ports free while it placed the other services, so the broker's default port could take an explicit -s3.port.grpc=17777 and push the S3 gRPC server to another port. An explicit gRPC port is now reserved too: the default broker moves off it, and an explicit broker port on it is rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * server: keep the default broker off the ports of the servers it starts With -volume.port=7777 the volume gRPC port is 17777, the default broker port. The volume server binds its gRPC port only after a master answers, so the broker could take it first and the whole process exited. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mini: keep an explicit gRPC reservation when a derived one moves When the filer's HTTP port was taken and moved, dropping its old derived gRPC port also dropped an explicit -s3.port.grpc on the same port, so an explicit -mq.broker.port could share it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * server: bind the broker beside S3 where the gateway binds With -ip.bind=0.0.0.0 -s3.ip.bind=127.0.0.1 the broker that comes with the gateway listened on every interface. It now takes the gateway's bind and advertised address, as under weed s3 and weed filer -s3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * server: keep the default broker off the volume public port Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: report a bad TLS config instead of exiting The embedded broker loaded grpc.msg_broker TLS through LoadClientTLS and LoadServerTLS, which exit on a bad config, so a cert without a key or without grpc.ca took the whole S3 gateway down. The broker now loads TLS before binding through the error-returning loaders, exported from the security package as TryLoadClientTLS and TryLoadServerTLS, and returns the error like any other start failure: the gateway logs it and keeps serving, while weed mq.broker and weed server -mq.broker still exit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: start the gateway's broker by default only with broker TLS Without grpc.msg_broker TLS the broker accepts any peer, so the broker beside weed s3, weed server -s3 and weed filer -s3 now starts on its own only when grpc.msg_broker has a cert and key in security.toml. Otherwise it stays off and the gateway logs one line saying so and that -mq.broker=true (-s3.mq.broker=true for the filer) runs it without TLS. An explicit true starts it either way and an explicit false keeps it off. weed mini, a single-process dev setup, keeps its broker on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: keep the default broker off the ports of the servers it starts weed filer -s3 checked the broker port only against the gateway's ports, so with -webdav -webdav.port=17777 the broker could bind 17777 first and WebDAV then took the whole filer down. The check now also covers the filer's own HTTP, gRPC and read-only ports, its metrics port, and the WebDAV, IAM and SFTP ports when those run, as weed server does. A default broker port that clashes skips the broker with a warning; a clashing -s3.mq.broker.port is an error before the servers start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * server: keep the default broker off the filer read-only and debug ports The port check beside -s3 left out -filer.port.public and, with -debug, -debug.port, so a broker on 17777 could still take a port the filer or the debug server binds. Both are now in the list. WebDAV, SFTP and IAM were already covered when enabled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6b2e22950a |
s3: bucket notification configuration API and target registry (#13236)
* s3: add the bucket notification target registry Notification destinations are defined by the operator in /etc/s3/notification/targets.json and referred to by name from bucket configurations, so a bucket owner cannot make the server connect anywhere new. The registry parses and validates that file: unique names that fit in an ARN segment and an MQ topic name, known types (topic and webhook now, kafka, aws_sqs, google_pub_sub and pubsub accepted for later), the fields each type needs, and no unknown keys. A target serves only the buckets its allowed_buckets globs match, and none when the list is empty. Parse errors never carry credential values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: hot-reload the notification target registry Every gateway reads /etc/s3/notification/targets.json at startup and reloads it from the /etc metadata subscription it already runs for the IAM and circuit breaker files. A write reloads it, a delete or rename away empties it, and a file that does not parse leaves the previous registry in place so a bad edit does not cut every bucket off its destinations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: parse and validate bucket notification configurations The full PutBucketNotificationConfiguration document is parsed: topic, queue and cloud function configurations with their Id, destination ARN, events and key filter. Event names are checked against the AWS list, wildcards and names for things that never happen here included, plus the multipart and retention events this server emits. A filter takes at most one prefix and one suffix rule, a document at most 100 configurations, and overlapping rules are allowed. EventBridge stays NotImplemented. A destination resolves by the last segment of its ARN to a target, which must exist, be enabled and allow the bucket; the error does not say which of those failed. A rule without an Id gets one derived from its content, so every gateway reports the same configurationId for it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: match an event against a bucket's notification rules Configuration.Match takes an event name such as s3:ObjectCreated:Put and an object key and returns each rule that covers them, with its configurationId and target, in configuration order. Category wildcards cover every event in the category, prefix and suffix are case-sensitive and checked independently, and an event that several rules cover matches each of them, as AWS delivers one record per rule. Publishing calls this; it is a pure function of the stored configuration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: store bucket notification configurations PutBucketNotificationConfiguration used to accept only an empty document and answer NotImplemented for any destination. It now parses the full document, checks every destination against the target registry for this bucket, and stores the XML exactly as sent in one Extended key on the bucket entry through updateBucketConfig, which patches that key alone on the bucket's owner filer. An empty document removes the key. GET returns the stored bytes unchanged, so tools comparing ARNs see no diff, and the bucket config cache carries the parsed rules for publishing to match. x-amz-skip-destination-validation is parsed and must be true or false. It only skips the test event, which publishing will send; the registry check always runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3notification: reject content after the configuration's root element The stored document is served back unchanged by GET, so anything after the root other than whitespace, comments or processing instructions is refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3notification: reject unknown elements inside rules and filters A misspelled Filter, S3Key, FilterRule or Value was dropped by decoding and left an unfiltered rule; it is now MalformedXML like an unknown root child. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3notification: URL-decode prefix and suffix filter values AWS has special characters in filter values percent-encoded and a space written as +, so reports+2026/ selects reports 2026/a. A value that is not valid encoding is still matched as written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: refuse a notification targets file stored in chunks Only inline content is read, so a targets.json kept in chunks (written by a mount, for one) read as an empty registry and dropped every target. It is now refused with a warning and the loaded registry stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3notification: refuse overlapping rules as AWS does AWS answers InvalidArgument ("Configuration is ambiguously defined") when two rules share an event type and both their prefixes and suffixes overlap, so an event for a key matches at most one rule. Such configurations were accepted and matched every rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
480a1baa20 |
s3api: GetPart, reading parts of in-progress and completed multipart uploads (#13174)
* s3api: GetPart reads one part of a multipart upload GET /key?part&partNumber=N&uploadId=X serves the latest attempt of an open upload's part, or the bytes that part became in the object a completed upload assembled, including a version that is no longer latest. x-amz-multipart-upload-status says which. A Range counts within the part, and a whole part answers 200 even though a completed part is served as a range of the object. The route sits ahead of ListParts and claims any ?part request, so a missing partNumber is InvalidArgument rather than a listing, and the request resolves to s3:GetObject, not the ListParts grant. * s3api: reading an open upload's part needs s3:GetIncompleteUpload AWS gates GetPart on an upload that has not completed behind s3:GetIncompleteUpload on top of s3:GetObject, so a plain read grant does not start exposing data its writer has not committed yet. The action is its own legacy grant too; Read alone does not carry it, Admin does. A completed upload's part needs only the read grant, plus s3:GetObjectVersion when it lives in a version. * s3api: a GetPart request carrying ?uploads is not a multipart listing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: GetPart answers a completed empty part with an empty 200 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
05d9242f3c |
s3api: answer NoSuchBucket to a denied authenticated request on a missing bucket (#13139)
* s3api: optionally answer NoSuchBucket to a denied signed request on a missing bucket ## Problem AWS S3 answers 404 NoSuchBucket to an authenticated caller that is denied on a bucket that does not exist. SeaweedFS answers 403 AccessDenied. S3-compatibility test suites run by data platforms (which create, probe and clean up buckets with a scoped key) flag the difference, and a client that maps 404 to "create it" or "skip it" takes the 403 for a permissions problem instead. Answering 404 tells every authenticated identity whether a bucket name exists, which a multi-tenant deployment may not want, so the default stays 403. ## Fix A new option, off by default: `-s3.noSuchBucketWhenDenied` on `weed server`, `weed filer` and `weed mini`, `-noSuchBucketWhenDenied` on `weed s3` (`S3ApiServerOption.NoSuchBucketWhenDenied`). With it set, `refineDenial` extends `refineDenialForBucketName` (400 InvalidBucketName) with the NoSuchBucket answer, in `Auth`, `AuthPostPolicy` and the POST policy handler: - only after authentication succeeded with a signature or a token (signed, presigned, V2, streaming signed, streaming-unsigned with a signed header, JWT). The anonymous identity keeps 403 under any auth type, so an anonymous caller still learns nothing about which buckets exist; - a bucket-level PUT (CreateBucket, configuring a bucket) keeps 403, as AWS answers a refused create; - the lookup goes through the bucket config cache, which the authorization path has usually just filled, so a denied request rarely costs a filer lookup; a failed lookup is "unknown" and keeps 403; - an allowed request never looks a bucket up. `Auth` now keeps the auth type it used to discard; the POST policy handler, which verifies the form signature itself, passes `authTypeSigned`. With the option off nothing changes. ## Tests `weed/s3api/auth_no_such_bucket_test.go`: - `TestRefineDenialThroughAuth`: through `iam.Auth`, a signed caller denied on another identity's existing bucket gets 403 and on a missing bucket 404 (GET, PUT, a signed streaming-unsigned PUT); a bucket-level PUT stays 403; the caller's own bucket is allowed with no lookup. - `TestRefineDenialAnonymousLearnsNothing`: anonymous requests answer 403 for a missing and an existing bucket alike and never drive a lookup. - `TestRefineDenialRules`: presigned and JWT callers, failed authentication, allowed requests, a missing bucket name, a failed lookup, and the option off (no lookup wired) all keep their answer. - `TestPostPolicyDeniedNoSuchBucket`: a verified browser POST form denied on a missing bucket answers NoSuchBucket; a bad signature stays SignatureDoesNotMatch; an existing bucket stays AccessDenied. `TestRefineDenialThroughAuth`, `TestRefineDenialRules` and `TestPostPolicyDeniedNoSuchBucket` fail without the NoSuchBucket answer. `go vet` reports nothing in the touched files; `go test ./weed/s3api/ ./weed/command/`: ok. `go build ./weed`: ok. * s3api: count streaming-unsigned as signed only with a SigV4 or JWT credential A client-certificate identity that streamed its body unsigned answered NoSuchBucket on a denied missing bucket, while the same request without the body-encoding header answered 403. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: tell the anonymous identity by name, without the unlocked pointer read isAnonymousIdentity compared against iam.identityAnonymous without iam.m, racing a configuration reload. The configured anonymous identity always has the anonymous name and account, which the check already covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * command: keep allowBackslashInKeyUsage's doc comment on its const Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: answer NoSuchBucket to a denied request on a missing bucket by default AWS S3 answers it this way, so drop the -s3.noSuchBucketWhenDenied flag and always wire the bucket lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: answer NoSuchBucket to a client-certificate identity too The AWS answer now goes to every authenticated identity, so it no longer depends on how the caller authenticated. The anonymous identity keeps 403, as anonymous object reads mask a missing bucket. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: fold the NoSuchBucket answer into refineDenialForBucketName One refinement for the bucket a denied request names: 400 for a malformed name, 404 for a missing one. The anonymous read paths keep their answer, since the anonymous identity never gets the 404. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
442e0a24c6 |
iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s (#13138)
* iceberg: let a client ask for a shorter vended session, with an opt-in floor below 900 s ## Problem The Iceberg REST catalog vends table-scoped S3 sessions on load and create with one process-wide lifetime, `-iceberg.credentialDurationSeconds` (default 3600). A client has no way to ask for less, and nothing can go below STS's 900 s floor. Some deployments want short sessions for some callers (a one-off read, a session handed to a less trusted process) without shortening them for every client: a process-wide 900 already breaks clients that keep a loaded table object for longer than its session (PyIceberg does not refresh vended credentials; DuckDB, Spark and Trino re-load and are fine). The Iceberg REST spec has no parameter for a credential lifetime. The precedent is `DurationSeconds` on AWS STS and on Lake Formation's `GetTemporaryGlueTableCredentials`. ## Fix - **Request header** `X-SeaweedFS-Credential-Duration-Seconds` on a load or create that asks for vended credentials (`X-Iceberg-Access-Delegation: vended-credentials`). A positive whole number of at most 9 digits is passed to the vendor; a missing, malformed, zero, signed or overlong value is ignored without an error, so clients that never send it see no change. - **It can only shorten a session.** The vended lifetime is `min(asked, configured)`; with no configured duration the ceiling is STS's `TokenDuration`, capped at `MaxSessionLength` as STS caps it. A request at or above the ceiling changes nothing (the configured duration is sent, as before). - **Floor:** new `-iceberg.credentialMinDurationSeconds` (`-s3.iceberg.credentialMinDurationSeconds` on `weed server` and `weed mini`), **default 900, which keeps today's behaviour exactly.** A request below the floor is raised to it. Values outside 1-900 mean 900, with a warning at startup; the setting can only lower the floor. - **STS:** `AssumeRoleForPrincipalRequest` gains `MinDurationSeconds`, a per-request floor honoured only within (0, 900]. Only the catalog's vend sets it, and only when the client actually shortened the session: a vend at the configured duration keeps the 900 s floor (so a configured `credentialDurationSeconds` under 900 is still refused), and AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials and every other action keep 900 through the unchanged `validateSessionDurationSeconds`. `MinSessionDurationSeconds` names the 900. - **Caching:** load answers now send `Vary: X-Iceberg-Access-Delegation, X-SeaweedFS-Credential-Duration-Seconds`, so a cache never hands a session vended for one lifetime to a request that asked for another. - The client learns the lifetime it got from `s3.session-token-expires-at-ms`, as today. The Lance namespace vend passes 0 (unchanged). ## Tests - `weed/s3api`: `TestVendDurationRequestOnlyShortensTheSession` (real STS and trust policy; the lifetime read from the session JWT's `exp - iat` and `max_dur`): nothing asked keeps 3600; 120 honoured; 60 at a floor of 60; 7200 capped to 3600; 30 raised to a floor of 60; floor unset, 900 or 1200 keeps 900. `TestVendFloorDoesNotLowerAssumeRole`: with the floor at 60 the vend mints 60 s (positive control) while AssumeRole and AssumeRoleWithCredentials on the same server refuse 60 s. `TestVendDurationRequestRespectsMaxSessionLength`, `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`. - `weed/iam/sts`: `TestSessionFloorIsLoweredOnlyForTheRequestThatAsks`. - `weed/s3api/iceberg`: `TestCredentialDurationHeaderReachesTheVendor` (the accepted and ignored header forms), and the Vary test updated. - Each rule undone turns its test red (request ignored: `TestVendDurationRequestOnlyShortensTheSession`, `…RespectsMaxSessionLength`; floor applied to every vend: `TestVendFloorDoesNotAdmitAConfiguredDurationBelow900`). - `go vet` and `go test` of `weed/s3api`, `weed/s3api/iceberg`, `weed/iam/sts`, `weed/iam/integration`, `weed/command` pass, `-race` on `weed/s3api/iceberg`, and `weed` builds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: let a shortened vend fit a caller credential with less than 900 s left A vend the caller shortened below 900 s (with a lower catalog floor) needs only that floor of the caller's credential to remain, not 900 s. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> |
||
|
|
a9fda6b50f |
filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers * Authenticate gateway filer calls with per-call admin tokens * Authenticate shell admin and synchronization filer calls * Authenticate workers MQ and remaining filer client paths * Cache filer client signing keys and sign subscriptions with the shared key Re-reading security.toml on every filer RPC cost about 125us against 8us for signing. Keep the keys for up to a second, re-reading at once when a WEED_ override or the configuration directory changes. When the file exists but cannot be read, keep the last keys read, else the startup keys, as FilerAdminKeys does, so a process without a key stays tokenless. Metadata subscriptions prefer the shared key, as filer peers do, because older filers verify subscription admin tokens only with it. * Authenticate admin-script, maintenance and filer.conf shell paths Plugin worker admin scripts and master maintenance scripts build their own shell options and carried no filer token source; fs.configure and s3.bucket.quota.check read filer.conf without it. * filer.cat: report a failed read; isolate key overrides in the admin-script test filer.cat ignored the error from its filer call and exited successfully, leaving a truncated -output file. Report the error and exit with failure. The admin-script token test now clears the WEED_ signing-key overrides, which take precedence over security.toml. * security: refuse gRPC keys too short to sign; query engine uses client TLS Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key, and filer client token sources check the keys they read, so a reloaded or per-endpoint security file with a short key is refused instead of panicking when the next RPC signs. The query engine's broker client dialed every master, filer and broker in plaintext, so the admin token it now sends could cross the network in the clear. It dials with the grpc.client TLS settings instead, and weed-sql loads security.toml as weed-db does. * security: per-endpoint admin tokens ignore WEED_ key overrides FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with -a.security and -b.security signed both clusters' admin tokens with the one key, handing each cluster a token valid on the other. A per-endpoint file now supplies its own keys only. * weed-sql, weed-db: refuse to start on an unreadable security.toml Both only warned when security.toml was present but could not be read or parsed. They then dialed without the grpc.client TLS settings while the filer token source could still sign admin tokens from WEED_ environment keys, so the tokens could travel in plaintext. They now exit with an error that does not quote the file; a missing file is still fine. * pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the existing helpers instead of keeping two names for each. Callers without a token source pass nil. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * util: return the read error from ReadConfiguration Fold ReadConfigurationWithError into ReadConfiguration. The error is returned and not logged, since parser errors can quote values; the existing reload callers already warn when no file was read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: keep the test-only filerAdminToken helper in the test It had no production caller. The test helper now resolves keys through filerClientKeysFrom, as the token sources do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * util: read security.toml once in LoadSecurityConfigurationOrError It validated the file, then merged it with a second read whose failure was ignored and whose parser error was logged. It now merges with one read and logs nothing from the parser. Viper's search also treats a directory the process cannot search as holding no file; a candidate that cannot be checked for lack of permission is now refused too. * security: verify admin subscription tokens with the gRPC clock leeway CheckGrpcMetadataSubscription checked admin tokens strictly, while unary filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second client admin tokens, a subscriber whose clock trailed the filer's by more than ten seconds was refused with a matching key. It now takes the leeway, and the filer passes its configured one. The leeway check moves from the server package to security.IsFilerAdminTokenWithLeeway so both use it. * util: start without security.toml only when every candidate is confirmed absent A candidate whose check fails for any reason other than not existing, such as a symlink loop, is refused like one the process cannot search. --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8053e77813 |
s3api: decide existing-object-tag denies on the object's tags (#13038)
* s3api: report a bucket policy Deny on existing object tags HasExistingObjectTagDeny tells whether a bucket policy has a Deny statement conditioned on s3:ExistingObjectTag/<key>, so the auth layer knows when a deny may turn on tags it has not read yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: decide existing-object-tag denies on the object's tags The auth layer evaluates the bucket policy before the handler reads the object, so s3:ExistingObjectTag/<key> resolves to a missing tag. A Deny with a negated condition (StringNotEquals, StringNotLike, StringNotEqualsIgnoreCase, Null true) then matched every object and was final, even one whose tag satisfies it, as in the deny-until-scanned-clean pattern. When that early evaluation denies and the policy has such a Deny, look up the object's entry and evaluate again with its tags. A missing object or a failed lookup keeps the deny. Copy sources and per-key checks that go through authorizeObjectKeyAction get the same treatment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: give identity checks the object tags a Deny was decided on With IAM integration, VerifyActionPermission evaluates the mirrored bucket policy again alongside the identity's policies, from a condition context built from the request alone. The negated existing-tag Deny matched there once more and denied an object tagged to pass it. evaluateBucketPolicy now returns the request carrying the tags it read, and RequestConditionValues reports them as s3:ExistingObjectTag/<key>. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: recheck in-flight tag conditions on the version served An in-flight request is authorized again when access changes. The entry lookup read the version current by then, so a newer version tagged to pass the Deny could keep a download of an older, denied version running. The handler's entry recheck now records the entry it authorized on the tracked request, and the re-check decides on that entry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: load the bucket before deciding an object request on its policy On a bucket whose policy was not loaded yet, the early bucket policy check found no policy and skipped the object-tag lookup, so the identity checks saw the request without the object's tags. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: keep an owned copy of the entry a tracked request served Handlers change the entry's metadata after the check, for example when storing new tags, so revalidation read a map the handler was writing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
9fc8a6aec2 |
mount: read SSE-S3 objects through the S3 gateway (#12909)
* mount: read SSE-S3 objects through an authenticated S3 gateway * mount: check each comma-joined mount option against -sseS3ReadEndpoint Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read a mounted version file by its object key and version id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: read a current null-version object without s3:GetObjectVersion Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: declare -sseS3ReadEndpoint with the other mount options so weed fuse accepts it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: require the canonical bucket path as the root of an SSE-S3 read mount Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: fall back to the null version when the current object is another version Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * master: list the S3 endpoint each S3 gateway advertises Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: advertise the gateway's S3 endpoint to the master Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: find the S3 gateway through the masters instead of -sseS3ReadEndpoint -sseS3Read turns gateway reads on. The reader lists the S3 endpoints the filer's masters have registered, prefers HTTPS, and picks another gateway when the current one cannot be reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: retry an unreachable S3 gateway read on a different gateway Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: warn when -sseS3Read falls back to a plain-HTTP gateway Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: do not retry an unreachable HTTPS gateway over plain HTTP Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mount: tell HTTPS gateways apart by the parsed URL scheme An S3 gateway advertised as HTTPS://host lost the HTTPS preference and the plain-HTTP fallback guard, since the check matched the raw string. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
548d8f1b42 |
weed-worker: take the cluster from admin, need only --admin (#12905)
* master, s3: an S3 gateway advertises its Lance Namespace port The gateway registers with the master already; it now says which port its Lance Namespace listens on, and ListClusterNodes returns it, so admin can tell workers where the catalog is instead of each deployment configuring it. * admin: tell workers where the Lance Namespace is Each S3 gateway that serves a Lance Namespace is now in the cluster context admin sends with every request, and a preview request carries the context too, so a worker can be pointed at admin alone. * seaweed-worker: take the filers and the Lance Namespace from admin Admin names both with every request, as it does for the Go worker, so weed-worker needs only --admin. --namespace is used when admin names no namespace, as an admin or gateways from before they could do so name none. --masters and --filer-group are accepted and ignored; the filer group is the one the filers report. * helm: weed-worker needs only the admin address The Lance container no longer derives a namespace URL or passes the masters and filer group; worker.namespaceUrl, when set, is the worker's fallback. * s3: advertise the Lance port only once its listener has bound A gateway whose Lance port was taken kept advertising it, so workers that picked that gateway sent every Lance request to a port nobody served. The listener now binds before the master registration, and the port reaches the master only when the bind succeeded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: stop waiting for the cluster context at the caller's deadline The admin provider builds the context with context.Background(), so a master outage held a preview, which now loads the context before it is sent, past its own deadline. Loading the context now returns when the caller's context ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * helm: keep giving the Lance worker its masters, group and namespace A worker image pinned to 4.55 or older needs the masters and the namespace and exits without them, and a 4.56 worker under an older admin needs the namespace. The chart now passes all three through the environment, which a 4.56 worker reads only when admin names nothing, and the namespace again defaults to the S3 service's Lance port. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * helm: give admin the filer group Admin lists filers and S3 gateways from its own group, and the Lance worker now takes its filers from admin, so with filer.filerGroup set the worker had no filers. Admin now gets the group; an -filerGroup in admin.extraArgs still wins. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * seaweed-worker: drop --namespace, --masters and --filer-group Admin names the namespace and the filers with every request, so the worker takes them from there alone. Handlers and the preview hold the admin-fed cluster, which also carries the signing key. The live tests get the filer through WEED_FILER and feed it to the worker as admin would. * helm: drop worker.namespaceUrl A worker from 4.56 takes the namespace from admin and has no option for it, so the value could only reach a pinned older image; the environment still gives one the S3 service's namespace, masters and filer group. * seaweed-worker: keep the last known namespaces while admin lists none When a master call fails, admin still sends its cached filers but no S3 gateways. With no --namespace fallback left, that emptied the worker's namespaces and failed every Lance job until the master answered again, though the gateways serve the namespace without it. The namespaces are now kept like the filers are. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * helm: run the Lance container for the filer's S3 gateway and an external admin The container was left out whenever the chart's own S3 gateway served no Lance namespace. A filer's embedded gateway serves one too, and an external admin names its cluster's, so both now get it; the namespace variable for a pinned older worker is set only when the chart's gateway serves one. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5afeb20ad6 |
s3: enforce BlockPublicPolicy and RestrictPublicBuckets for bucket policies (#12882)
* s3: refuse a public bucket policy when the bucket blocks public policies PutBucketPolicy stored and enforced a policy granting access to every principal even with BlockPublicPolicy set. Check the stored public access block on the bucket entry that the policy write reads, and answer AccessDenied for a public policy. A policy counts as public when an Allow names a wildcard principal (or uses NotPrincipal) and no fixed-value restricting condition such as aws:SourceIp or aws:SourceVpce narrows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep a public bucket policy from granting anonymous access under RestrictPublicBuckets With RestrictPublicBuckets set, an anonymous request was still allowed by a public bucket policy. The bucket policy engine now treats such an Allow as granting nothing when the bucket restricts public buckets and its policy is public, so the request falls through to the remaining checks instead of reading as an explicit deny. A bucket whose configuration cannot be read is treated as restricted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: write a bucket policy only over the extended attributes it checked setBucketPolicy rewrote the whole bucket entry it had read, so a public access block set between the BlockPublicPolicy check and the write was erased and the public policy stored anyway. Send the read extended attributes, including an absent public access block, as the update's expected values, and redo the read and check when they changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: count more policy forms as public An empty principal list and a principal holding a policy variable can both match anyone, so they are public. An aws:SourceIp range wider than /8 (IPv4) or /32 (IPv6) no longer restricts a grant. An ARN condition value with a fixed account, such as an access point ARN with a wildcard name, does restrict it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: deny anonymous callers outright on a restricted bucket with a public policy RestrictPublicBuckets limits a bucket with a public policy to callers of the owning account, so dropping only the policy's own grant left public ACLs able to serve anonymous reads. While the policy is public, the policy engine now answers an anonymous request with a deny. It checks before and after evaluating, so a policy replaced in between cannot let an anonymous grant through. A bucket without a policy, or with a non-public one, is unaffected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: count an empty principal string as public A principal of "" compiles to no principal check, so it matches anyone, the same as an empty list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: write a bucket policy only over the bucket entry it checked The policy write replaced the whole bucket entry and asserted only the public access block key, so a bucket setting first written between the lookup and the write (versioning, for one) was dropped. Pin the write to the entry it read; any concurrent change fails it and the lookup retries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: judge an IPv4-mapped aws:SourceIp range by its IPv4 prefix ::ffff:0.0.0.0/96 parses as a 128-bit network but matches every IPv4 caller, so it passed the /32 IPv6 bound and a public policy slipped past BlockPublicPolicy and RestrictPublicBuckets. Apply the IPv4 /8 bound to mapped ranges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
22df63ad22 |
security: accept a previous JWT signing key during rotation (#12844)
* security: verify JWTs against an optional previous signing key DecodeJwt, the admin token checks and the volume expiry classifier take previous keys to try after the current one, and Guard keeps a previous write and read key next to the current ones. Signing still uses only the current key. Callers pass no previous key yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume, filer, s3, admin: accept tokens signed with jwt.*.previous_key jwt.signing.previous_key, jwt.signing.read.previous_key, jwt.filer_signing.previous_key and jwt.filer_signing.read.previous_key (WEED_JWT_*_PREVIOUS_KEY from the environment) name a key the verifiers still accept next to the current one, and SIGHUP reloads them. Keys can then rotate without an error window: add the new key as previous everywhere, swap current and previous, then remove previous. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * scaffold: document jwt previous_key for key rotation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): accept tokens signed with jwt.signing previous_key Mirrors the Go volume server: [jwt.signing] and [jwt.signing.read] take previous_key (WEED_JWT_SIGNING_PREVIOUS_KEY, WEED_JWT_SIGNING_READ_PREVIOUS_KEY), the guard verifies against it after the current key, and SIGHUP reloads it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume, filer, s3: drop a removed previous_key on SIGHUP LoadConfiguration merges, so a previous_key line deleted from security.toml kept verifying until a restart. Read the previous keys without the merge on reload, as the Rust volume server already does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume, filer, s3: keep previous keys when a reload cannot read the file A SIGHUP that found security.toml unreadable or malformed cleared the previous keys while the merged current keys stayed. Fall back to the merged configuration then, so the keys in effect stay in effect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: IAM and metadata subscription admin checks follow the filer guard The IAM gRPC service checked the jwt.filer_signing keys read at startup, and the metadata subscription read them from the merged configuration, so adding or removing previous_key with SIGHUP did not reach them. Both now read the filer guard that Reload updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: reload jwt keys in one place, keeping the guard's previous keys When security.toml could not be read, the reloads fell back to the merged configuration, which still holds a previous_key an earlier reload removed. Guard.ReloadSigningKeys keeps the previous keys the guard already has instead, and the volume, filer and S3 reloads share it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: take reloaded current keys from the same read as previous keys The current keys came from the merged configuration and the previous keys from a second read of the file, so a file swapped between the two reads could publish the same key as both. Take every key the fresh read sets from it; a current key the file no longer sets keeps its merged value. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: worker streams read the filer admin keys as security.toml sets them Both worker stream handlers read jwt.filer_signing keys from the merged configuration. Under weed mini a reload merges the file, which keeps a previous_key the operator removed, so new streams still accepted it; a standalone admin never picked up a rotation at all. Read the keys the file sets now, falling back to the merged values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * scaffold: wait for old-key tokens to expire before clearing previous_key Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): keep the keys in effect when SIGHUP cannot read security.toml parse_security_config falls back to defaults when the file is missing or unreadable, so a SIGHUP then cleared every key and turned JWT checks off. Skip the key and whitelist update in that case, as the Go reload keeps its merged configuration and the guard's previous keys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: keep every key in effect when a reload cannot read security.toml A failed read took the current keys from the merged configuration while keeping the active previous keys, so after a swapped pair the guard could publish the old key twice and reject tokens signed with the new one. The reload now leaves the keys untouched, as the Rust volume server does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: filer admin keys fall back to the last pair read, not merged values When security.toml stopped being readable, FilerAdminKeys returned the merged configuration, which still holds a previous_key the file had already dropped, so tokens signed with the retired key verified again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: STS store gates check the admin token against one key snapshot The OIDC provider and role RPCs read the reloadable admin key twice, in checkAdminAuth and in the store gate. A reload that set the key between the two reads let a call without a token pass both. The gate now takes one snapshot for the empty-key refusal and the token check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: read and cache filer admin keys under one lock Concurrent callers could store their reads out of order, so an older pair that still had previous_key could overwrite a newer one and come back when a later read of security.toml failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: unlock the filer admin key mutex on every exit of its test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3aadc0fc46 |
s3api: bound route-by-key lookups at an unreachable owner filer (#12827)
* s3api: bound route-by-key lookups at an unreachable owner filer A route-by-key read (getObjectEntryRoutedByKey and the scoped .versions listing) asks the key's owner filer first, on context.Background(). When that owner sits behind a network partition that drops packets instead of refusing them, the lookup waits out gRPC's 20 s connect timeout before the failover walk asks the next filer. The owner is then skipped for only 2 s, so the next read of any key it owns dials it again and waits another 20 s. With the ring spread over two data centers, about half the keys stall every ~22 s for as long as the partition lasts (#12826). - The owner's attempt in the walk now gets a deadline, -s3.routedLookupTimeout (default 1s), when the owner is not the gateway's current filer. Past it the walk moves on to the next filer, as for any transport error, and flags the owner unreachable. The current filer and every later attempt stay unbounded, so a slow but reachable local filer still answers; 0 restores the unbounded lookup. The prior- owner probe during a ring rebalance gets the same bound. - The skip time of a failed owner is now -s3.unreachableOwnerTTL (default 2s, unchanged). Deployments that can see dropped-packet partitions can raise it so each owner is retried less often. - The S3 gateway's volume location lookups take -s3.volumeLookupTimeout per filer (default 5s, the FilerClient default, unchanged), so a vidMap miss need not wait 5 s per unreachable filer. The flags exist on weed s3 (without the s3. prefix), weed filer, weed server and weed mini. Tests (s3api_object_routed_read_deadline_test.go): an owner that never answers costs a read the deadline and is skipped by the next read (hangs without the change); with the deadline 0 a slow owner is still waited for; an owner that is the current filer is not timed out; a slow filer later in the walk is waited for; the scoped listing fails over at the deadline; the skip TTL honours the option and the default. * s3api: bound a routed listing only until the owner's first message The routed-lookup deadline covered the whole .versions stream at a remote owner. A reachable owner whose listing keeps streaming past it (a store scan trailing its first rows) was cut off mid-stream, and the failover walk refuses to replay a stream that already delivered entries, while listRetry does not retry DeadlineExceeded, so the listing failed outright where it used to succeed. Lift the deadline once the stream delivers its first message; an owner that never answers still fails over at it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
f5e091cf91 |
wdclient, s3: return an embedded S3 gateway to its local filer after failover (#12772)
* wdclient: sort newly discovered filers and log every current-filer switch Discovery appended new filers in map iteration order, so after the current filer left, the fallback at index 0 was a random filer. Append them sorted. Route every change of the current filer through one helper that logs it at V(0) with its reason (failover, return_home, discovery), so an operator can see which filer a gateway uses without new metrics. * wdclient: prefer a home filer and return to it after failover with backoff A FilerClient with FilerClientOption.HomeFiler set goes back to that filer once its circuit breaker allows a re-check, instead of staying on whichever peer it failed over to. Leaving home again soon after a return doubles the wait before the next return, up to 5 minutes; a return that holds for 10 minutes resets it. Volume lookups and discovery follow the same preference. * s3: embedded gateway uses its local filer as home filer weed filer -s3, weed server -s3 and weed mini now build the gateway's filer address in the form the filer registers in the master (ip:port.grpcPort), with the gRPC port default applied, and pass it to the gateway as its home filer, so the gateway returns to its local filer after any failover. Standalone weed s3 has no home filer and behaves as before. Refs #12768, follow-up to #12771 * wdclient: switch the current filer only from the filer a request started on A volume lookup that started on a peer and finished after the client had returned home moved it back to the peer and counted that as leaving home, doubling the return backoff although home never failed. Concurrent failovers could also each count as a separate departure. Failovers now name the filer they started on and take effect only while it is still current, via compare-and-swap, so only the winning switch logs and feeds the backoff. S3's failover walk uses the same rule. * wdclient: switch the current filer and record the return backoff in one step The index moved by compare-and-swap before the switch was recorded, and both ran under the shared read lock. A request reading the current filer in that gap saw the peer with the old eligibility time and, with home's breaker still closed after one failure, switched straight back home. The eligibility check, the move and the bookkeeping now all run under homeMu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * wdclient: discovery falls back past a home that is still backing off When discovery removed the current filer and home was not yet eligible, the client took index 0, which is home whenever it is listed first. With home's breaker still closed after a single failure, requests went back to the filer they had just left. Take the next filer instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * wdclient: start return timing on every switch back to the home filer Only a return_home switch stamped lastReturnHome. Discovery or a peer's failover could also put the client back on home, and a failure soon after such a return kept the backoff at its base value instead of doubling it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Konstantin Lebedev <whitefox@mayflower.work> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
53bc62c773 |
s3api: accept the accelerate and notification configurations the bucket already reports (#12747)
* test/s3: run tigrisdata-community s3-api-compat-tests in CI Runs the suite, pinned to a commit, against weed mini through a small provider patch, and fails on any test that is not in expected_failures.txt or on a listed test that starts passing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * test/s3/tigris_compat: prepare the suite again when the patch changes The checkout was reused whenever it sat at the pinned commit, so an edited seaweedfs-provider.patch, or a checkout whose patch failed to apply, kept being built as it was. Record the commit and the patch's hash once the patch applies, and prepare the checkout again when either differs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: keep the pid file of a server already running start-server removed weed-server.pid before it found the port taken, so a second start lost the pid of the server holding it and stop-server could no longer stop that one. Remove the file only once the port is free, and have test-with-server stop only a server it started. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: bound the S3 port probes A listener that accepts but never answers held curl, and with it the readiness loop and the cleanup after it, for good. Give each probe two seconds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: accept PutBucketAccelerateConfiguration with Status=Suspended GetBucketAccelerateConfiguration always reports Suspended, but the PUT answered 501 for every request. Suspended is now accepted, Enabled stays NotImplemented, and the accelerate subresource resolves to s3:GetAccelerateConfiguration / s3:PutAccelerateConfiguration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * s3api: accept an empty PutBucketNotificationConfiguration GetBucketNotificationConfiguration always reports an empty configuration, but the PUT answered 501, including for the empty configuration clients send to clear notifications. An empty one is now accepted; a topic, queue, Lambda or EventBridge destination stays NotImplemented. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * s3api: reject accelerate and notification bodies with the wrong root Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * test/s3/tigris_compat: expect a listed test to end with its listed status A listed test passed the check with any non-pass status, so a setup error that skipped the call under test (RestoreObject's PutObject, say) went unnoticed. Entries now expect fail unless they name another status; only GetBucketAccelerateConfiguration, whose setup PUT is unsupported, expects error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: refuse to start while the recorded server still runs A second start-server before the first server answered on the S3 port passed the port probe and dropped the pid file of the live server, so stop-server could no longer stop it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: recognize the test server by its command line start-server and stop-server took any process named weed at the recorded pid for the test server, so a weed process that reused the pid would be reported as running and killed by stop-server. Match the command line start-server launches instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: recognize the test server by its start time A weed mini started from another checkout has the same command line, so a pid it reused still matched. Record the process start time next to the pid at launch and require both before treating the process as the test server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: PutObjectTagging_VersionId passes now Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: keep the server records until the server exits stop-server waited a fixed two seconds after SIGTERM and then removed weed-server.pid and weed-server.started even if weed was still shutting down, so a later stop-server could not find it and clean could delete data it still used. Wait up to 30 seconds for the recorded server to exit and keep the records, failing, while it still runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test/s3/tigris_compat: start the server on an empty data directory A data directory left by an earlier run on other ports made the master freeze volume growth (topology id mismatch), and every PutObject failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0d3f5a220c |
s3: keep serving for -preStopSeconds after SIGTERM (#12703)
* s3: keep serving for -preStopSeconds after SIGTERM On SIGTERM the gateway closed its listeners at once, so requests a load balancer or Kubernetes Service still routed to it failed until the endpoint was removed. With -preStopSeconds set, the gateway makes /status, /healthz and /readyz return 503, keeps serving for that many seconds, then runs the existing graceful shutdown. 0 (the default) keeps the old behavior. The flag is registered for weed s3 and as -s3.preStopSeconds for weed filer, weed server and weed mini. A cancelled weed mini cluster context ends the wait early. The Helm chart passes s3.preStopSeconds and filer.s3.preStopSeconds through. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: assert the preStopSeconds chart render under set -e, drop timing from the probe test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: wait before weed mini cancels its clients; size grace periods in the chart weed mini's interrupt hook runs before the S3 one and cancels the S3 gateway's shutdownCtx, so the pre-stop wait never happened there. The wait is now also registered with beforeMiniClientsShutdown, which runs before that cancel, and a sync.OnceFunc keeps the interrupt hook from waiting a second time. Outside weed mini the registration is a no-op. Helm: the s3 deployment fails to render when terminationGracePeriodSeconds is below preStopSeconds + 15. The filer statefulset and the all-in-one deployment, whose grace period is fixed at 60s, add preStopSeconds to it. allInOne.s3.preStopSeconds is passed through, inheriting s3.preStopSeconds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep 64-bit counters aligned on 386; let allInOne.s3.preStopSeconds=0 disable the wait draining sat ahead of inFlightDataSize and inFlightUploads in S3ApiServer and shifted them off 8-byte alignment on 32-bit builds, so the atomic upload-limit counters panicked there. It now follows them. Helm: allInOne.s3.preStopSeconds inherits s3.preStopSeconds only when null; default treated an explicit 0 as unset. The s3 values and the grace period error now say a lifecycle preStop hook's time comes on top. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * grace: add OnInterruptFirst for hooks that must run before any shutdown Interrupt hooks run in reverse registration order, so a hook cannot run ahead of a service that registers later, such as a volume server that is still loading its volumes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: run the -preStopSeconds wait before every other interrupt hook Under weed server the volume server registers its hook once its volumes are loaded, often after the S3 gateway. Its hook then ran first and shut the volume server down, so the gateway spent the whole wait serving requests that could not read or write objects. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> |
||
|
|
c4e1802e3e |
s3: route ';' queries as authorized, and report an empty s3:prefix to policies (#12702)
* s3: escape raw semicolons before the router matches a route registerRouter applied EscapeSemicolonsInQuery with router.Use, but mux runs router middleware only after it has picked the route. Queries() matchers split pairs on ';', so GET /bucket?uploads;x=1 reached the multipart listing handler while the handler and the IAM resolver read uploads%3Bx=1 and saw no uploads subresource. Wrap the S3 router with the escape so routing and authorization read the same query. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: report a listing without prefix as s3:prefix "" in policy conditions The advanced IAM path already sets s3:prefix to "" when a bucket listing names no prefix, as AWS does, but bucket policies and attached policies read conditions from ExtractConditionValuesFromRequest, which leaves the key out. The AWS home-directory policy that grants s3:prefix ["", "home/"] then denied the root listing, and a Deny keyed on the empty prefix never applied. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: test the served handler composition for the semicolon escape Move the escape and the Vectors split into s3Handler so a command test can send ';' queries through the handler the server actually serves. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: keep the isVectorsRequest doc comment on its function Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
813ac74d79 |
s3tables: keep legacy-subject owners and policy principals for federated STS sessions (#12615)
* s3tables: re-anchor legacy owners for federated STS sessions A web-identity role session was keyed on its bare OIDC subject until owners became issuer-scoped. Its sessions now carry the scoped aws:userid but no asserted issuers, so the legacy subject check never applied and the session lost the table buckets and namespaces it had created. Read the configured issuer set for such sessions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: keep token claims from asserting trusted issuers on STS sessions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: give the catalog's table handler the local accounts and issuer set Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3tables: test a federated session on a bucket its legacy subject owns Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sts: drop a token-supplied aws:userid when a session has no parent user Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: take a session's aws:userid from its signed parent user Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test that session claims keep only the server-asserted aws:userid Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3tables: match legacy subject patterns in table bucket policy principals A policy written before issuer scoping can name role sessions by a pattern over their bare OIDC subjects. Match such a pattern against the caller's subject claim once that subject resolves to the session's scoped principal under the single configured issuer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3tables: test a federated session against a legacy subject pattern principal Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d685709832 |
s3api: refuse writes to a stored version's physical path (#12622)
* s3api: refuse a PUT to a stored version's physical path In a Suspended bucket a PUT to <key>.versions/v_<id> replaced the stored version's body in place. Look the entry up when the key has the version file shape and deny the write when it is a version file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: refuse copy, multipart, POST and rename writes to a version file Apply the same version file check to the CopyObject, CreateMultipartUpload, CompleteMultipartUpload, POST Object and RenameObject destinations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: read a version file write target on its logical owner The guard resolved the key as an object, which on a ring reads the physical path's owner and, in a versioned bucket, may return a nested version under <key>.versions/v_<id>.versions instead of the stored version. Look up the physical entry directly, routed by the logical key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: confirm a version file miss on a skipped owner When the owner was recently unreachable the routed lookup answers from a replica, whose miss does not show the version is absent. Ask the owner directly in that case and refuse the write when it cannot answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: confirm every routed version file miss on the owner Whether the routed lookup skipped the owner can change between the lookup and a second unreachable check, letting a replica's miss through. Ask the owner after any miss instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a6a3bdef8d |
s3api: deny signed reads of a version file through its physical path (#12574)
* s3api: deny signed reads that name a version file by its physical path A stored version lives at <key>.versions/v_<id>, and that path is also a valid object key. Anonymous reads already refuse it; signed GET, HEAD, copy sources and object subresources did not, so a caller without s3:GetObjectVersion, or under a Deny on the logical key, could read any version through it. Apply the same check in the shared entry recheck. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: recheck a version file key before answering a conditional read A conditional GET or HEAD answered 304 or 412 with the ETag before the handler's entry recheck, so the physical version path still confirmed a version's ETag to signed callers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: look up version file keys in the lookup-based policy recheck Retention, legal hold, tagging writes and deletes only fetched the entry for the recheck when the bucket had a policy, so without one they still acted on a version file named by its physical path. Fetch it whenever the key has the version file shape. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: refuse a directory-marker delete that names a version file A trailing slash kept "<key>.versions/v_<id>/" out of the version file shape check, and the lookup recheck misses the entry for that form, so a DELETE reached deleteDirectoryMarker and removed a chunkless version or delete marker without s3:DeleteObjectVersion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
6c1eec8703 |
s3: store the POST Object acl on the uploaded object (#12567)
* s3api: split upload ACL assembly out of preparePutObjectACL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: store POST Object acl and grant fields on the object The form acl and x-amz-grant-* fields were authorized but never assembled, so the object kept no ACL: acl=private on a public-read bucket stayed anonymously readable and invalid values were accepted. Build them with the same rules as PutObject, which also covers the Block Public Access check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test POST Object stores its upload ACL Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: take the POST Object ACL from the signed form only ACL request headers are not covered by the POST policy, so a holder of a signed form could add one and have it stored with the upload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: reject a POST acl field the policy does not cover The acl form field now sets the stored object ACL, so like the x-amz-* fields it needs a policy condition, as AWS requires. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test unsigned ACL headers and uncovered acl fields on POST Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: evaluate POST upload policies on the canonical ACL Policy conditions on the grant headers saw the raw form value, so an equivalent spelling of a denied grantee passed. Use the PutObject request shape that the PUT path evaluates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: check bucket policy for POST ACLs with auth disabled PutObject applies the bucket policy to an explicit upload ACL when IAM is off; POST now does the same before storing it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: reject differing acl and x-amz-acl POST fields Both promote to the canned ACL header, so map order picked the stored ACL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test POST grant canonicalization, auth-off ACL policy, acl conflicts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: check the auth-off POST ACL policy after loading the bucket Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: reject an empty acl or x-amz-acl POST field beside a differing one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test the auth-off POST ACL policy on a cold bucket cache and empty acl aliases Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: load the bucket before per-key object authorization Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test the POST ACL policy on a cold bucket cache with auth on Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: stop per-key object authorization when the bucket fails to load Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test the cold-bucket POST ACL allow path and a failed bucket load Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
fcfca3fee3 |
s3, filer: bound the wait for an upload slot (#12559)
* util: add WaitUntil, a cond wait bounded by a context and a timeout The caller holds the cond lock. Cancellation and the timeout wake the waiter through a broadcast taken under the same lock, so no wakeup is lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: bound the wait for an upload slot A PUT that arrived while the concurrent upload limits were exhausted waited on the condition variable with no bound. The handler reads nothing from the body while it waits, so a client that gave up and reset its connection went unnoticed: the socket and goroutine stayed pinned until a slot freed, and a stalled volume server grew the gateway's fd count by one per aborted PUT. The wait now ends on InflightUploadDataTimeout with 503 SlowDown, which S3 SDKs retry, and on request cancellation. An admitted upload takes its slot under the lock, and a finished upload broadcasts, so freed bytes admit every waiter that fits instead of one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: bound the wait for an upload slot The filer's PUT/POST upload limits queued requests the same unbounded way. Reuse the bounded wait: reject with 429 after InflightUploadDataTimeout, as the volume server does, and stop on request cancellation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * command: add -inflightUploadDataTimeout for the S3 gateway and the filer weed s3 -inflightUploadDataTimeout, weed filer -inflightUploadDataTimeout and -s3.inflightUploadDataTimeout, weed server and weed mini -filer.inflightUploadDataTimeout and -s3.inflightUploadDataTimeout. The default of 60s matches the volume server's flag of the same name; 0 keeps the old unbounded wait. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: reject a queued upload without reading its body WriteErrorResponse drains the request body before answering. Behind the stats recorder the drain has no read deadline, and reading the body sends an Expect: 100-continue client the go-ahead to upload what is about to be discarded. Answer the rejection with an empty-body copy of the request so the drain is skipped; net/http closes the connection when a large unread body remains. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3, filer: release an upload slot under the cond lock A waiter checks the counters under the cond lock and then waits. A release that decremented and broadcast without the lock could land between the two, so the waiter slept with a slot free until the next release or its timeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3, filer: close the HTTP/1 connection when rejecting a queued upload net/http reads up to 256 KiB of an unread request body before sending a keep-alive reply, so a client that stalls its body held back the 503 or 429 until the connection idle timeout. Connection: close skips that read. HTTP/2 is left alone: there it would shut down the whole connection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3e64326f2b |
s3: require their own actions to change a bucket's CORS or versioning (#12433)
* s3: require their own actions to change a bucket's CORS or versioning PUT/DELETE ?cors and PUT ?versioning were authorized as Write, so an identity granted only object writes on a bucket could replace its CORS rules or suspend versioning. They now need PutBucketCors, DeleteBucketCors and PutBucketVersioning (or Admin), and inline policies granting s3:PutBucketCors, s3:DeleteBucketCors or s3:PutBucketVersioning map to those actions instead of Write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: test that object Write cannot change bucket CORS or versioning Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * admin: offer the bucket CORS and versioning permissions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3: test each bucket config action with its own identity Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
ce292a4e5e |
s3: require Admin to put or delete a bucket's lifecycle configuration (#12327)
PUT and DELETE ?lifecycle were authorized as Write, so an identity granted only object writes on a bucket could add expiration rules or remove the ones the bucket administrator set. They now need Admin on the bucket, like the encryption, public access block and ownership controls writes. Identities authorized by IAM policies are unaffected: they are still checked against s3:PutLifecycleConfiguration. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
d72f761d83 |
seaweed-vector: work on its defaults, and without identities or credentials (#12323)
* seaweed-vector: default --namespace to the gateway's Lance port The old default, http://localhost:8888/lance, is a path nothing serves: the Lance Namespace listens on its own port, 9101 by default on weed s3, weed server, weed filer and weed mini. With it, the filer answered the engine's catalog calls with a 500 and every CreateIndex failed with InternalFailure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * seaweed-vector: default --listen to a port no SeaweedFS server takes 127.0.0.1:8080 is the volume server's default port, so weed-vector next to weed server exited with "Address already in use (os error 98)". 8090 is not among the defaults of master, volume, filer, S3 and its Iceberg and Lance catalogs, IAM, WebDAV, SFTP, the message queue broker and agent, the admin server or weed mini, nor any of their gRPC ports (HTTP + 10000). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * lance: take any key while the S3 server runs without identities Without identities the S3 port accepts any signature and treats the caller as the admin. The Lance catalog still checked an x-api-key or Bearer token against identities that did not exist, so weed-vector started with --storage-option credentials on such a server got 401 on every catalog call. The catalog now skips both checks when S3 auth is off and leaves the caller to the S3 authenticator, which admits it as the admin, as it already did for a request with no key. With identities configured nothing changes: an unknown key is still 401. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * lance: tell clients to skip signing while S3 auth is off A client with no credentials of its own could not reach a table's data on a server without identities, though the S3 port takes unsigned requests there: lance fell back to the AWS default credential chain and failed with CredentialsNotLoaded. weed-vector without --storage-option failed every CreateIndex that way. The catalog now adds aws_skip_signature to the storage options it hands out while S3 auth is off, and leaves it out once identities exist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * seaweed-vector: bind the listener before registering with the master The engine spawned its master registration and then bound --listen, so an engine whose port was taken could reach the master before it exited: on weed server with 18080 taken the master logged "vector node 127.0.0.1:18080 added" and removed it in the same millisecond, and the gateway noticed it. Bind first, and name the address in the error instead of "transport error". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * seaweed-worker: keep an unsigned store off the AWS default chain A store the catalog says takes unsigned requests needs no credentials, but lance builds the AWS default credential chain for any store without them, and the chain probes instance metadata on every dataset open. With no credentials of its own, weed-vector spent a second on each query (1030-1066 ms against 32-46 ms with --storage-option ones). The merge of the operator's fallback and the vended options, which the engine and the Lance worker each did in their own copy, moves into table_options, and gives such a store empty credentials. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK * test(s3vectors): serve an index with no identities and no engine credentials A second cluster runs weed s3 without -config and weed-vector without --storage-option, with no AWS credentials in either environment: weed s3 would turn them into an admin identity, and the engine would find them. On master its CreateIndex fails with InternalFailure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b9bc42c217 |
s3vectors: vend write credentials to index data only to the vector engine and Lance worker (#12316)
* security: share the filer admin token check CheckGrpcAdminPeer verifies an admin Bearer token inline. Move the check into IsFilerAdminToken so an HTTP endpoint can accept the same token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: recognize the cluster's own components by a signed token A request whose X-Seaweedfs-Cluster-Token header carries an admin token signed with jwt.filer_signing.key comes from a component that holds the cluster key: the vector engine or the Lance maintenance worker. Mark such a request as trusted. It still authenticates as an identity, which stays the principal for vended credentials. A dedicated header leaves the Authorization header to Lance OAuth clients. A gateway with no key trusts no one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: vend write credentials to a vector bucket's indexes only to trusted callers An index in a vector bucket's vector namespace is also a Lance table, so a caller granted s3tables:UpdateTable could describe it, or declare it again, and get credentials that write the index data without passing the vector bucket policy. In that namespace both now vend read-only credentials unless the caller is trusted, and a declare from anyone else no longer writes the dataset markers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance worker: prove the cluster key to the Lance namespace The gateway now vends write credentials to a vector bucket's indexes only to callers that send a token signed with jwt.filer_signing.key. The worker already takes that key for the admin stream; its namespace client now mints a token from it for every catalog request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * weed-vector: describe the index the gateway created and prove the cluster key CreateIndex declared a table the gateway had just created, which only worked because declare is idempotent. Describe it instead. The Lance namespace vends write credentials to a vector bucket's indexes only to callers that send a token signed with jwt.filer_signing.key, so take the key with --filer-signing-key, the same flag the Lance worker has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance worker: keep the cluster key out of Debug output Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: answer a declare of an existing table with its own location CreateTable succeeds for a name that already exists without looking at the location requested, and declare kept using that location for the dataset markers and the vended credentials. Declaring an existing table with another table's location, such as a vector index, got credentials to that table's data. Use the location the catalog holds, which CreateTable now also reports for a new table. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: sign cluster tokens with a key derived for the catalog A cluster token was a filer admin token signed with jwt.filer_signing.key and, by default, never expired. Sent to the Lance namespace on every request, often over plain HTTP, a captured one would also authorize the filer's IAM service. Sign it with a key derived from the cluster key for this one use, which the admin services do not accept, and mint it with a five minute lifetime. weed-vector drops its token lifetime flag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: follow a reloaded jwt.filer_signing.key The Lance namespace copied the cluster key at startup. A SIGHUP reload refreshes the gateway's filer guard but not that copy, so after a key rotation the restarted vector engine and worker were no longer trusted. Read the key from the guard on every check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: keep a vector bucket's indexes read-only An index in a vector bucket is also a catalog table the Iceberg REST catalog loads, and LoadTable vended credentials that could write it to any caller granted s3tables:UpdateTable. A commit staged its metadata file in the index directory on the same grant. Apply the vector namespace rule to both, after the caller's own UpdateTable check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * iceberg: confine a created table's location to its namespace before writing Stage-create skips the registration that confines a location to the table's namespace, yet vends write credentials for that location. A caller allowed to create a table in any namespace of a bucket could name another namespace's prefix, a vector index included, and get write credentials to it. The non-staged create also wrote its first metadata file there before the registration refused the location. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * lance: a declare that finds an existing table answers like describe Creating a name that already exists is idempotent, so a caller allowed only to create tables could declare someone else's table and get write credentials to it, and clear its deregistered marker. Describe would have vended that caller read-only credentials. A declare now looks the name up first; when it only finds the table, writing needs UpdateTable, as it does for describe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
3a8d756bdd |
s3: drop retired volume servers from the gateway location cache (#12281)
* wdclient: publish applied volume-location deletes to registered listeners The master already tells each connected client which volumes a server stopped hosting; only the MasterClient's own vidMap applied it. Expose the same filtered deletions (moves between a server's disks excluded) through OnVolumeLocationDelete so clients keeping a second location cache can drop the retired server too. * wdclient: drop retired volume servers from the FilerClient location cache The S3 gateway's FilerClient keeps its own vidMap, filled by filer lookups, and only forgot a retired volume server after a read against it failed (a ~15s header-timeout stall when the host still resolves). When built with a MasterClient, subscribe to its applied deletions so the cache forgets the server as soon as the master reports it gone. * wdclient: drop retired EC servers from the regular location map too Filer lookups cache EC locations alongside regular ones in vid2Locations, so an EC removal has to clear the retired server there as well as in the EC map for the delete to reach what reads actually use. * wdclient: tombstone pushed deletions against in-flight provider fills A filer lookup already running when a delete lands can return the retired location afterwards and re-cache it. Keep a short tombstone on each deleted (vid, url) pair so fills neither cache nor return it while the lookup source is still settling. * wdclient: clear the FilerClient location cache on master reconnect Removals the master pushed while the gateway link was down never arrive as deletes, so on reconnect the lookup-fed cache is dropped outright rather than kept generation-wise like the stream-fed one, and relearned through filer lookups as before. * wdclient: invoke push hooks outside their registration locks A callback that registers or replaces a hook would wait on the read lock the invocation already holds and stall the master stream. Copy the hook under the lock and call it after the lock is released. * wdclient: report pushed adds so confirmed re-adds clear the suppression A server coming back at the same URL inside the tombstone window stayed hidden from provider fills. updateVidMap now carries the additions it applied through the same hook (renamed OnVolumeLocationChange), and the registered cache untombstones them without eagerly caching them. * wdclient: amortize tombstone expiry over a delete batch A server leaving takes every volume it hosted with it, and scanning all recentDeletes per removed vid squared the batch. Prune lazily on reads and at most once per half TTL on writes. * wdclient: let every location cache subscribe to pushed volume changes The setters were single-slot, so a second FilerClient built on the same MasterClient would have silently replaced the first one's subscription. Registration now returns an unhook func, delivered to all listeners, and FilerClient.Close releases its own. * wdclient: hold the deletion fence until the master re-confirms a location * wdclient: check the deletion fence and the cache add under one lock * wdclient: drop provider answers that crossed a cache reset * wdclient: bound the deletion fence by evicting its oldest mark * wdclient: refresh a repeated removal instead of evicting another mark * wdclient: evict the oldest deletion-fence mark in constant time * wdclient: fence a server only once it serves the volume in no form ec.encode registers the shards before the regular copy is deleted from the same server, and ec.decode mounts the regular copy before the shards come off it. Both arrive add-first in separate heartbeats, so the later removal tombstoned a (vid, url) pair the server still serves and dropped it from the FilerClient map; the filer's answer naming that server was then fenced out and the volume read as not found until the gateway reconnected. Tombstone and report a removal only when neither map still names the url for that volume. * wdclient: serve a provider answer that crossed a cache reset The answer is as fresh as the provider's view; only the cache it would land in has been re-told. Dropping it failed every read whose lookup was in flight during a master reconnect with 'volume not found'. Return it and leave the new view to be filled by the next lookup. * wdclient: test the moved volume whose old server keeps proxying * wdclient: stop caching inside the master lookup provider The provider wrote every answered location through addLocation, which clears the deletion fence: a lookup still naming a server a pushed delete had just retired untombstoned and re-cached it. Fallback lookups already gate caching through fillLocation, and authoritative lookups bypass the cache by contract, so the provider no longer writes the map at all. * wdclient: count only master-pushed locations when suppressing a removal hasLocation could not tell a confirmed regular copy from a lookup fill: the master answers an EC volume with its shard servers, so the regular map holds shard locations that arrived by lookup, and entries an earlier generation learned linger past a reconnect. An EC removal whose url still showed either was suppressed, leaving the retired server served. The vid map now records the generation each regular location was pushed at, drops an unconfirmed regular entry alongside the shard that fed it, and answers hasServingLocation from pushed marks and current-generation entries only. * wdclient: test removals against lookup-cached and stale locations * wdclient: fence removals only in the gateway cache The fence and the pushed-location marks ran inside every MasterClient, including the filer's, whose map is also filled by lookups and cleared by InvalidateCache. A removal reported while the server still served the volume (e.g. a decoded copy whose mark a failed read had wiped) left the pair fenced until the master pushed it again, with reads failing as volume not found meanwhile. Only the S3 gateway's FilerClient now tombstones, from the removals its push-only MasterClient reports. That client decides a removal from the current generation of both its maps after the whole message is applied, so pushedLocations goes away, and the master lookup provider caches as before. The hooks follow the existing single-slot SetOn...Fn pattern and are wired next to SetOnPeerUpdateFn. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * wdclient: let a removal fence expire after a minute The master drops a broadcast when a client's channel is full, so the re-add that would lift a fence can be lost while the gateway stays connected. A mark held until that re-add then hid a live server, and a volume whose only copy it held read as not found until the next master reconnect. Bounding marks by a minute still outlasts a lookup in flight when the removal landed; expiring early only falls back to learning by a failed read, as before this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
74f196ceab |
s3: route regular copy source reads to the write owner (#12173)
* s3: read regular copy sources from their write owner * filer: report mutation sentinel codes in ObjectTransaction responses A failed mutation only surfaced resp.Error text, so routed writers could not distinguish an existing-directory conflict from a generic failure and could not apply the prefix-object retry the plain CreateEntry path has. * s3api: retry a routed mkfile as a prefix object over a directory mkFile retries ErrExistingIsDirectory by marking the entry a prefix object; the routed path returned the conflict instead, so a routed write to a key that is also a prefix failed where the lock path succeeds. The filer now reports the code on the transaction response, making the retry recognizable. * s3api: commit copy destinations on the key's write owner An owner-routed source read still left the destination on the gateway's default filer, so a second copy resolved the first copy's destination on the owner, found nothing, and returned NoSuchKey. Write unversioned and suspended destinations through routedMkFile, and write the version file on the owner the finalize recomputes on. * s3api: cache remote objects on the filer that served the entry An owner-routed lookup can return a remote-only entry that has not replicated to the gateway's default filer; the cache RPC then cannot find it and the copy or read degrades to a 503. Ask the entry's write owner to cache it first, falling back to the default filer. * s3: read versioned object state from the key's write owner CopyObject destinations now commit version files and the .versions pointer on the owner's object-scope ring key, so versioned reads through the default filer could miss them until replication. Generalize the routed read to dir/name lookups and paginated lists scoped to the object's owner, and point the versioned read paths at it: getSpecificObjectVersion, doGetLatestObjectVersion, the .versions quick-checks in Get/Head/attributes, the self-heal rescans, tagging, delete conditionals, directory-marker history checks, rename destination, multipart completion checks, and the version-id format probe. Reads fall back to the default filer when no ring owner is resolvable, preserving single-filer deployments. * test(s3api): fake RECOMPUTE_LATEST/DELETE and cover versioned copy reads The ambiguous-PUT fake filer now creates parent directories on PUT (mirroring InsertEntry), applies DELETE mutations, and re-derives the .versions pointer for RECOMPUTE_LATEST the way applyRecomputeLatest does, so owner-vs-replica tests can exercise versioned writes. TestVersionedCopyDestinationReadsOnOwner copies into a versioned bucket whose writes commit on the owner while the gateway's default filer is a replica with no replication, then asserts reads by versionId, latest-version resolution, and a copy chained off the new version all resolve on the owner. * test(s3api): gofmt the versioned-copy coverage * s3: only swap in a cache fill of the resolved remote generation A cache response can come back from a filer holding an older generation of the key. Replacing the authorized source or swapping its chunks under a size and range computed for the resolved entry serves the wrong object or truncates the response. Match RemoteEntry identity and size before using a cached entry, in both the copy and streaming paths. * filer: keep directory attributes when an object lands as prefix object The object-onto-directory retry replaced the existing directory's mode, owner, and extended attributes with the object's. Preserve the directory identity; merge directory-held extended keys only when the old entry never held an object, so a prior generation's object metadata is not carried forward. * s3: keep marker lock checks on the filer that replaces the marker The object-lock precondition read the key's write owner while mkdir still replaces the marker on the default filer, so a locked marker not yet replicated to the owner could be overwritten. Read the entry where the replacement lands, in both PutObjectHandler and zip extraction. Also hash a trailing-slash marker key to the same route key as the object it names, so marker and object share one owner and one write lock. * s3: route tag writes to the owner tag reads resolve GetObjectTagging reads the key's write owner, but PutObjectTagging and DeleteObjectTagging still wrote through the default filer, so a successful change returned the owner's stale tags until replication. setTags, rmTags, and the versioned tag updates now write on the owner first, falling back to the default filer when no owner resolves. * s3: keep rename lookups on the filer that performs the move AtomicRenameEntry and the retry token it carries both execute on the default filer, but the source and destination reads went to the write owner — a completed rename's token was invisible to its own retry, and a source that only exists on the default filer looked absent. Read both ends on the default filer. * s3: send the .versions pointer repair with the object's route key The heal reads the .versions entry on the object's owner, but the conditional UpdateEntry is routed by the .versions path's own ring key, which can hash to a different filer — leaving the pointer the routed reads consult unchanged. Ship the CAS repair as a PATCH_EXTENDED ObjectTransaction on the object's route key instead. * filer: preserve only directory identity on a prefix-object write Merging the old directory's extended attributes could carry a marker's encryption, version, or etag fields onto the new plaintext object, since a directory's own keys cannot be told apart from the object it held. Keep only mode, uid, gid, user name and group names. * s3: also require matching size when a cache fill replaces the source The remote-generation check covers identity; size equality is the cheap guard that keeps the streamed or copied range consistent with what was resolved. * s3: lock the object path for a routed .versions pointer repair conditionalUpdateEntryRouted held the lock on the .versions path while version writes and deletes serialize on the object path, so a repair could pass IF_ENTRY_EQUAL and then apply over a pointer a writer had advanced in between. Lock the object path like the writers and keep the condition on the .versions entry via condition_key. * s3: do not replay an owner-side tag mutation on another filer withWriteOwnerFilerClient re-ran fn on the default filer after any owner error, so an authoritative not-found could update a stale replica entry and still report success, and a post-apply transport error could apply the mutation twice. The failover walk now ends on any error fn returns; only a channel that never came up moves to another filer. * filer: keep a directory's xattrs when a prefix object replaces it The prefix-object branch preserves the directory's identity but dropped its Extended map wholesale; FUSE xattrs live there under the xattr- prefix and belong to the directory, not to the object the marker held. * s3: delete null and specific versions on the filer that serves them On the default filer an absent entry deletes as success, so a version that only reached the write owner survived a reported success while owner-routed reads kept serving it. The suspended-versioning and lifecycle deletes now go through routedDeleteNullVersion and routedDeleteSpecificVersion when an owner resolves; an unsettled attempt keeps the lock path. * s3: route a lifecycle null-version delete to the object entry The "null" version is the regular object entry, not a .versions file, so it goes through routedDeleteNullVersion; only a real version id takes the .versions-file delete. * s3: repoint .versions only while it still names the deleted version routedDeleteSpecificVersion recomputed the latest pointer on every version delete, so removing a noncurrent version re-derived the pointer to the newest remaining file — resurrecting an older version over a cleared pointer (a suspended bucket's null write keeps it clear while the null object stays current) or over a pointer that moved on. The pointer is now read on the owner and repointed under an IF_ENTRY_EQUAL guard only while it still names the deleted version; a contested pointer is left for the self-heal path rather than overwritten by a stale scan. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: let lifecycle expiry keep its metadata-only deletes on routed paths The routed lifecycle deletes hardcoded IsDeleteData, so expiring an entry with a volume TTL queued per-chunk deletions instead of leaving the data for the volume to reclaim — extra work on the owner for deletes recordMetadataOnlyIf still counts as metadata-only. Pass the caller's cleanup choice through routedDeleteNullVersion and routedDeleteSpecificVersion; the interactive DELETE path keeps deleting data. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: let RECOMPUTE_LATEST skip a pointer that moved on A version delete repoints .versions only while the pointer still names the deleted version, but the gateway cannot carry the pointer's current state into the transaction's condition — the condition slot is already spent on the version's WORM guards. only_if_current_name moves the check under the transaction lock: the filer compares the pointer's name_to_key value before scanning and skips the recompute when it moved (or was cleared by a suspended bucket's null write), so a noncurrent delete cannot resurrect an older version. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: repoint inside the version's locked delete repointLatestBeforeVersionDelete ran in its own transaction ahead of the delete, so a version delete denied by retention or legal hold still moved the latest pointer — GET and HEAD went on serving the older version it rolled to. The repoint and the delete now ride one transaction behind the version's WORM guards, atomically gated by the new only_if_current_name recompute guard instead of a stale-read IF_ENTRY_EQUAL. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
5700aa5e91 |
s3: evaluate bucket CORS for path-style OPTIONS on the bucket root (#12028)
* s3: evaluate bucket CORS for path-style OPTIONS on the bucket root
A path-style preflight for /bucket (no trailing slash) missed the bucket
OPTIONS route, whose template is /{bucket}/, and was answered by the global
OPTIONS handler from the global AllowedOrigins instead of the bucket CORS
configuration. Register the bucket OPTIONS route without a path matcher, and
keep OPTIONS for the health probe paths on the service-level handler ahead of
each path-style router.
Fixes #12025
* test: drop the issue reference from the bucket-root preflight test comment
---------
Co-authored-by: Wleeaf <179125857+wleeaf@users.noreply.github.com>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
||
|
|
cd97c93deb |
command: keep filer, s3, and sftp up when the local unix socket cannot bind (#11999)
* pb: share the stale-socket tolerant unix listener ServeGrpcOnLocalSocket already treats the local socket as optional; pull the remove-and-listen block out so the filer, s3, and sftp http sockets can use it too. * command: keep filer, s3, and sftp up when the local socket cannot bind A stale socket file owned by another uid (e.g. left in /tmp by a containerized job) made os.Remove fail with EPERM and the Fatalf took the whole server down. The gRPC local socket already treats the unix listener as optional; do the same for the http/sftp sockets. * filer: clear shared localSocket flag when the unix socket cannot bind s3.localFilerSocket and (in weed server) the sftp local socket share the filer's -localSocket flag pointer. If the filer cannot bind the socket it now keeps running without it, so consumers still holding the configured path would dial a dead or foreign-owned socket. * command: keep sftp on its own localSocket flag under weed server sftpOptions.localSocket was overwritten with the filer's -localSocket flag, so -sftp.localSocket was ignored and an explicit filer socket path made the sftp server try to bind the same socket the filer already held. * s3: fall back to TCP when the filer local socket cannot be dialed The embedded S3 server copies the filer's -localSocket flag before the filer tries to bind it, so a socket that never comes up left every filer HTTP request dialing a dead path. Try the unix socket first and fall back to the request's TCP address on dial failure. * filer: keep the shared localSocket flag read-only after startup Clearing *fo.localSocket raced with the embedded s3 goroutine reading the same flag pointer and could not help a reader that had already copied it. The s3 filer client's TCP fallback covers the unbound-socket case without mutating shared flag state. |
||
|
|
f2d5c27f65 |
operation: renew the write JWT when a fan-out rollback delete is rejected (#11970)
* operation: renew the cleanup JWT when a fan-out rollback delete is rejected A stalled holder can out-wait the assignment JWT's 10s expiry, so the type=replicate delete that rolls back landed copies comes back 401 and the needle leaks. Retry the delete once with a fresh token minted through the new LookupJwtFunc hook when a holder answers unauthorized. * s3api: wire a cleanup-JWT renewer into chunked uploads Keep the master client on the server and use it to mint fresh volume JWTs for rollback deletes that run past the assignment token's expiry. * admin: wire a cleanup-JWT renewer into file-browser uploads * operation: bound the cleanup-JWT renewal with a per-attempt deadline A rollback delete that hits 401 renewed the token through a background context, so a master outage could park the wait for a connection and the lookup RPC inside the failed upload's cleanup path. Thread a context through LookupJwtFunc and LookupJwt, and bound each renewal with a 10s deadline covering both the master wait and the lookup call. * operation: let every holder's 401 retry with a renewed cleanup JWT A single renewed flag meant only the first rejecting holder refreshed the token; a holder that stalled past the renewed JWT's lifetime left later copies stranded with a 401 they could not resolve. The retry limit is now per holder — each delete is attempted once with the current token and once more after a bounded renewal — so a slow middle holder cannot strand the rest. * operation: log the volume server's error body on a failed cleanup delete Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * operation: count test upload attempts atomically The chunk upload loop fans AssignFunc out to parallel goroutines, so the plain int counter in the partial-results test raced under -race. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
cec96c02ea |
s3: reject requests carrying more than one routed subresource (#11942)
* s3: reject requests carrying more than one routed subresource Routing picks the first matching subresource route while authorization resolves a single action from the query, and the two can disagree. A bucket-level PUT ?tagging&policy is authorized as s3:PutBucketTagging but served by PutBucketPolicyHandler, letting a tagger rewrite the bucket policy; the same shape lets a list grant read the policy via ?list-type=2&policy or ?versions&policy, and lets an object ACL writer retag via PUT ?acl&tagging. Declining ambiguous requests keeps the authorized action and the served handler identical. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: reuse hasAmbiguousSubresource in the routed-subresource guard The standalone key list dropped versioning, so ?versioning&policy still reached route matching and auth with two operations. The bucket-level check already keys off operationSubresources plus bucketQueryActions; running the same predicate keeps the lists from drifting apart. --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
1aad4cfe70 |
iam: optionally require an iam: grant for self-service access-key actions (#11937)
* iam: optionally require an iam: grant for self-service access-key actions
AuthorizeIamAction lets every authenticated identity run CreateAccessKey,
DeleteAccessKey, UpdateAccessKey, ListAccessKeys and GetUser on itself with
no grant. On AWS these actions need an IAM policy (the usual one grants them
on arn:aws:iam::*:user/${aws:username}); nothing is allowed implicitly.
Where identities hold data-plane rights only, the implicit carve-out lets a
leaked key mint further keys for its own identity, with no cap, that keep
working after the operator deletes the key that leaked; it can also
deactivate or delete the keys the operator issued.
A new option, off by default, makes these actions need the iam:<Action> grant
like every other IAM action: -s3.iam.selfServiceRequiresGrant on weed
server, filer and mini, -iam.selfServiceRequiresGrant on weed s3. With it
set, the grant is authorized against the target user's ARN, the caller's own
when UserName is empty, so a policy can confine it to the caller's own keys
(Resource arn:aws:iam:::user/${aws:username}), the same resource scoping
CreateServiceAccount already uses. The admin and iam:* grants are unchanged;
with the option off nothing changes.
Tests (s3api_embedded_iam_authz_test.go): with the option set, an identity
holding only s3:* and a bare identity are refused all five actions on an
empty, own and other target (fails without the change); a grant on the
caller's own user ARN, literal or ${aws:username}, allows them on itself and
not on another user; the admin and an iam:* grant keep every action; with the
option off self-service is allowed as before.
* iam: wire selfServiceRequiresGrant on the standalone iam server
Every other command that runs the embedded IAM API accepts the flag; the
deprecated weed iam could not enable the enforcement at all.
* iam: wire selfServiceRequiresGrant on weed server and filer -iam
The IamOptions used by 'weed server -iam' and 'weed filer -iam' never
received the flag, so startIamServer dereferenced a nil pointer at
startup. Share the -s3.iam.selfServiceRequiresGrant pointer with them.
---------
Co-authored-by: Javier de la Torre <jatorre@lakehousebox.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
|
||
|
|
c0152e6be1 |
s3: keep '\' a literal object-key character behind -s3.allowBackslashInKey (#11911)
* s3: keep '\' a literal object-key character when AllowBackslashInKey is set NormalizeObjectKey rewrites every S3 object key: '\' becomes '/' and duplicate slashes collapse. On AWS S3 both are ordinary key characters, so keys that are distinct there alias one object here — writing probe/back/slash.txt silently overwrites probe/back\slash.txt. The filer only treats '/' as a path separator, so a verbatim '\' stays inside one entry name. Gate the backslash rewrite and the matching '\' handling in IsValidObjectKey behind a process-wide mode the S3 server sets from the new S3ApiServerOption. Duplicate-slash collapsing stays: an entry name cannot contain an empty segment. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * command: add -s3.allowBackslashInKey flag for AWS-compatible key handling Registers the flag on all four S3 entry points (s3, server -s3, filer -s3, mini) and passes it through S3Options into S3ApiServerOption. Default off, so existing normalization is unchanged. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: correct IsValidObjectKey/NormalizeObjectKey docs under allowBackslashInKey Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: normalize DeleteObjects body keys the same as path keys DeleteObjects keys arrive in the XML body, so they bypassed the normalization applied to route-var keys. The lock, the authorization checks, the table-bucket layout check and the filer delete itself all addressed the raw key while the conditional check resolved the normalized one, so a key spelled with '\' or '//' could be reported deleted while the stored entry survived. Echo the client-sent key in the result while operating on the normalized form. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: report a normalized-empty DeleteObjects key as a delete no-op A multi-delete key of only slashes normalizes to the empty string. Left to reach the filer delete, the empty name resolves to the bucket entry itself, so an unauthorized caller could remove a bucket through the body-key path. Such a key can never name a stored entry, so like a missing key the delete is an idempotent no-op reported before any permission check or filer call. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: drop unused AllowBackslashInObjectKey getter * s3: answer conditional delete of a normalized-empty key with NoSuchKey * s3: normalize the probed key in authorizeAnonymousBucketList The masked-miss probe read the raw mux var, so a spelling like folder// or folder\ was authorized against a key that can never exist while the request itself targets the normalized folder/. Probe the normalized key so the answer matches what the read path authorizes. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: cover anonymous authz of a literal-backslash key under allowBackslashInKey A public grant on the slash key must not authorize an anonymous read of the distinct backslash object when the flag keeps '\' literal; grant the backslash key's own ACL and it reads back. Default mode still folds the spelling onto the covered slash key. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: publish the key mode only after the S3 server is constructed A failed NewS3ApiServerWithStore could previously flip the process-wide key mode out from under an already-running gateway. * s3: normalize the copy-source key before validation and authorization pathToBucketObjectAndVersion returned the raw header spelling, so an equivalent spelling (a//b, a\b) was authorized and compared against the normalized destination while resolveCopySourceEntry looked up the normalized key — a deny on the canonical key could be bypassed and self-copy detection missed. Normalize once at parse so the CopyObject and UploadPartCopy paths agree. --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
106fd31af1 |
s3: resolve versionId ACL and attributes requests to the version-scoped actions (#11916)
* s3: resolve versionId ACL requests to the version ACL actions A request for an object's ACL carrying versionId acted on the historical version but authorized against the current-object action (s3:GetObjectAcl/s3:PutObjectAcl), because the acl block in resolveFromQueryParameters returned before versionId was considered - the same gap closed for tagging. An identity granted only current-object ACL access - or explicitly denied s3:*ObjectVersionAcl - could still read and modify ACLs on noncurrent versions. ?acl&versionId=<id> on an object now resolves to s3:GetObjectVersionAcl/s3:PutObjectVersionAcl; ?acl alone keeps the current-object actions and bucket ACL is unaffected. s3:PutObjectVersionAcl is mapped onto the WriteAcp identity action so policies can name it. * s3: resolve versionId attributes requests to the version attributes action GET /bucket/key?attributes&versionId=<id> fetched the historical version's attributes but authorized against s3:GetObjectAttributes, so a grant limited to the current-object attributes action could reach noncurrent versions. The request now resolves to s3:GetObjectVersionAttributes, and both attributes actions map onto the Read identity action so policies can name them (s3:GetObjectAttributes was previously rejected as an unmapped action). * s3api: recheck the version action on versioned ACL/attributes requests The phase-2 policy recheck inside GetObjectAclHandler, PutObjectAclHandler, and GetObjectAttributesHandler passed the current-object action even when the request carried versionId and phase 1 had resolved the version action. A Deny scoped to s3:*VersionAcl or s3:GetObjectVersionAttributes could never fire in the recheck, and an Allow limited to the version action went unevaluated. Select the action the same way the resolver does — versioned whenever versionId is present. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: recheck the version action on versioned tagging requests The same phase-2 gap exists in the tagging handlers left by the earlier version-tagging resolution change: versioned GetObjectTagging / PutObjectTagging / DeleteObjectTagging rechecks evaluated the current-object tagging action, so a Deny on s3:*VersionTagging could not fire. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: resolve HEAD ?acl as the head-object action, not an ACL action No HEAD acl route exists, so HEAD /bucket/key?acl lands on HeadObjectHandler — which serves object headers, not the ACL. Resolving it to an ACL action denied readers who hold only GetObject(Version) and let ACL grants reach a head-object read. Dropping HEAD from the acl branch lets the request fall through to GetObject/GetObjectVersion, matching how the tagging branch already treats HEAD. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: require the version read grant for versioned attributes AWS asks for s3:GetObjectVersion alongside s3:GetObjectVersionAttributes when a GetObjectAttributes request names a versionId; the resolved version-scoped action on its own left a lone s3:GetObjectVersion Deny unable to cover the attributes read. Check the version read grant too: the identity side through VerifyActionPermission, the bucket-policy side through the same recheck that evaluates the scoped action. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: check the version read grant on a synthesized versioned GET The versioned attributes check passed the literal s3:GetObjectVersion action, but both policy paths re-resolve the action from the request, so the attributes query parameter mapped it back to s3:GetObjectVersionAttributes and a lone version-read Deny never fired. The literal action also reached the legacy CanDo path, where a plain Read grant no longer matched. Evaluate the grant on a request shaped like a plain versioned GET instead. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: reject a named versionId on buckets without versioning Tagging, ACL, and attributes handlers answered versionId requests on never-versioned buckets as the current object while evaluating the version-scoped action, so a grant limited to the version action could authorize changes to the live entry. Reject the request up front through the existing checkVersionIdConfigured gate. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: carry presign params onto synthesized policy requests objectKeyPolicyRequest rebuilt the query with only versionId and the STS token, so a presigned request's s3:authType condition value silently changed from REST-QUERY-STRING to unset during phase-2 rechecks (version read grant, copy source, delete keys, post-policy writes). A policy conditioned on s3:authType would then deny a request it already allowed. Carry the SigV2/SigV4 presign keys through; none of them steer ResolveS3Action. --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
f40267db44 |
s3: answer InvalidBucketName to a denied request on a malformed bucket name (#11893)
* s3: answer InvalidBucketName to a denied request on a malformed bucket name The store authorizes a request before it looks at the bucket, so a caller denied on a bucket whose name breaks the S3 naming rules (upper case, an underscore, too short, two adjacent periods, a non-ASCII letter) gets 403 AccessDenied, where AWS S3 answers 400 InvalidBucketName. Clients and compatibility suites that check the error code read the 403 as a permission problem. Auth and AuthPostPolicy now turn an AccessDenied for a resolved identity into InvalidBucketName when the bucket name fails VerifyS3BucketName or uses a character outside a-z, 0-9, '.' and '-' (VerifyS3BucketName checks with unicode.IsLower/IsNumber, which accept letters such as 'ü'). The answer depends on the name alone, so it reveals nothing about which buckets exist. An authentication failure, an allowed request and a denial on a well-formed name answer as before. Test: TestAuthDeniedInvalidBucketName drives iam.Auth with signed and anonymous requests; on master every malformed name answers 403, with the change 400, while the identity's own bucket stays allowed and a well-formed foreign name stays 403. TestRefineDenialForBucketName covers the rule table. * s3: refine POST-policy and deferred anonymous-read denials on a malformed bucket name Two denial paths bypass the refinement in Auth and AuthPostPolicy: - A browser POST upload carries its credentials in the form, so AuthPostPolicy delegates it to PostPolicyBucketHandler, which verifies the form and writes AccessDenied itself when the signer may not write the bucket or the per-key authorization denies the object. Both denials now go through refineDenialForBucketName with the verified identity. The coarse Write check used to run inside doesPolicySignatureV2Match and doesPolicySignatureV4Match before the signature was compared, so a form with a wrong signature was told whether the key may write the bucket. It now runs in doesPolicySignatureMatch after the signature verifies, as on the header-signed path; a form that fails verification answers SignatureDoesNotMatch (or MissingFields) and is never refined. - Unsigned GET/HEAD object reads are deferred by AuthWithPublicRead to the object handlers, where writeAnonymousAwareNotFound masks a miss as AccessDenied. That denial is refined with the anonymous identity, so a missing malformed bucket answers InvalidBucketName when an anonymous identity is configured, as Auth does. A denial on an entry that was found is left alone: the bucket exists. Test: TestPostPolicyDeniedInvalidBucketName drives AuthPostPolicy with signed forms (Write denied, per-key policy deny, bad signature, well-formed name); TestAnonymousReadDeniedInvalidBucketName drives AuthWithPublicRead with GET and HEAD, with and without an anonymous identity. Both fail before this change. * s3: refine a denied anonymous read of an existing key on a malformed bucket name A deferred anonymous GET/HEAD refined only its masked miss to InvalidBucketName, so in a bucket whose name breaks the S3 rules (one VerifyS3BucketName still accepts, such as a non-ASCII name) a missing key answered 400 and an existing private key 403, telling the caller which keys exist. The entry check now refines its denial the same way, so both answer alike. Without an anonymous identity no identity resolves and both stay 403, as in Auth. The deny-precedence case in TestAnonymousObjectACLConfiguredIdentity runs on the fixture bucket "b", shorter than S3's three-character minimum, so its denial now answers InvalidBucketName. --------- Co-authored-by: Javier de la Torre <jatorre@lakehousebox.com> |
||
|
|
e596be10f0 |
s3api: evaluate object-tag policy conditions on delete, ACL and lock operations (#11807)
* s3api: resolve the target version in tag-condition policy lookups * s3api: apply tag-conditioned policy to object deletes * s3api: apply tag-conditioned policy to object ACL reads and writes * s3api: apply tag-conditioned policy to retention and legal hold * s3api: cover tag-conditioned delete, ACL and object-lock rechecks * s3api: let tag-conditioned grants redecide denied batch deletes * s3api: resolve the tagged version in delete policy tests |
||
|
|
2d06e2d6c1 |
s3: evaluate tag conditions on copy-source and tagging subresources (#11771)
* s3: evaluate tag conditions on copy-source and tagging subresources Policy evaluation ran without the object entry on several paths, so a Deny conditioned on s3:ExistingObjectTag never matched: - CopyObject, UploadPartCopy and RenameObject checked the source key before its entry was fetched; repeat the check on a synthesized GET once the entry resolves. - GetObjectAttributes and Get/Put/DeleteObjectTagging never supplied the entry; recheck with the resolved entry. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: fail closed on tag-policy lookups and honor tag-conditioned grants - recheckTagConditionedPolicyWithLookup returned success when the entry lookup errored, letting a tag-gated Deny slip past a transient miss; only ErrNotFound still falls through to the handler's own NoSuchKey. - A read or delete denied in the tagless first phase now gets one more evaluation with the resolved entry's tags in hand, so an s3:ExistingObjectTag-conditioned Allow can still grant a copy-source read or rename. The deferred recheck requires an explicit Allow; indeterminate results keep the original verdict, and the existence of the key never leaks past a deny. - RenameObject now applies the same tag-aware recheck to the source removal, so a tag-gated Deny on s3:DeleteObject blocks a rename the way it blocks a direct DELETE. - GetObjectAttributes evaluates the object-entry policy recheck before conditional headers, so a 304/412 response can no longer bypass a tag-based Deny. * s3: honor identity denies in the tag-aware source recheck The deferred recheck re-evaluates only the bucket policy, so a bucket Allow could lift an explicit Deny in the caller's attached or session policies on a copy/rename source. Apply the same applicable-policy Deny check the first phase uses. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
56fbc3deb5 |
s3api: align S3/IAM error responses with AWS (#11632)
* s3err: add InvalidArgument and AuthorizationHeaderMalformed codes Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: answer unrecognized bucket PUT sub-resources with 501 A PUT on a bucket carrying an unrecognized query (logging, metrics, intelligent-tiering, ...) fell through to the bare CreateBucket route and returned BucketAlreadyOwnedByYou or re-created the bucket. AWS answers these with NotImplemented. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: reject malformed copy-source and multipart PUT parameters A malformed X-Amz-Copy-Source or a non-numeric partNumber fell through to the plain PutObject route and stored the body as a regular object. Answer them with InvalidArgument-class errors instead of writing data. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: verify x-amz-content-sha256 against the streamed body A PUT carrying a hex or base64 payload hash now streams through a verifier that reports a mismatch once the stream is exhausted, instead of storing an object that does not match its declared hash. The error is deferred so intermediate reads that drop (n>0, err) results cannot silently swallow it. Sentinel values (unsigned/streaming payloads) remain exempt and malformed values fail fast. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: map truncated SigV4 headers to the error for the missing field AWS answers an Authorization header missing Credential= with InvalidArgument and one missing or malformed Signature= with AuthorizationHeaderMalformed, instead of a generic MissingFields. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: answer IAM/STS failures in the query-protocol envelope Embedded IAM and STS routes now report authentication, form-parse and authorization failures with the IAM ErrorResponse body instead of the S3 Error envelope, so IAM SDK clients can parse them. Requests signed for s3 keep the S3 envelope, keyed off the credential scope. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: return 403 AccessDenied when the request has no Date Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: answer throttling rejections as SlowDown ErrTooManyRequest and ErrRequestBytesExceed reported made-up codes; AWS serves these throttling rejections as SlowDown. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: reject versionId requests on buckets that never had versioning GET, HEAD and DELETE carrying a non-empty versionId on an unversioned bucket now fail with InvalidArgument instead of being answered as a plain object request. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: answer DeleteObjects over 1000 keys with MalformedXML Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: InvalidArgument for non-numeric or out-of-range part numbers partNumber=abc, 0 and >10000 all resolve to InvalidArgument, matching AWS, instead of InvalidPart. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * iam: correct LimitExceeded, InvalidAction and ServiceFailure mappings LimitExceeded is a conflict (409), an unknown Action is InvalidAction (404) rather than NotImplemented, and internal failures report the IAM receiver fault type. Applies to both the embedded IAM endpoint and the standalone iamapi server. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * iam: refuse DeleteUser while access keys remain Deleting a user with live credentials orphaned its access keys; AWS answers DeleteConflict until they are removed first. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test/s3: add S3/IAM error-response compatibility harness * s3: return InvalidArgument for malformed x-amz-content-sha256 A header value that decodes to neither 32-byte hex nor base64 is a malformed argument, not a hash mismatch. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: stop spawned mini when readiness times out A slow-starting server otherwise survives the failure path and keeps the S3 port occupied for the next run. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: register atexit cleanup before setup A failed setup previously skipped cleanup, leaking the bucket and IAM user on persistent servers. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3api: reject unrouted subresources on the DELETE bucket catch-all PutBucketHandler gained the same guard when the route-level check moved into the handlers; DeleteBucketHandler was missed, so an authorized DELETE /bucket?logging could delete the bucket instead of answering NotImplemented. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: tolerate unset fixture variables in cleanup and cover DELETE ?logging Cleanup now runs its IAM/multipart steps only when setup reached them, so an early setup failure still removes the bucket. Added a DELETE bucket-subresource case asserting NotImplemented and bucket survival. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test: fail a case when its side-effect check reports a regression A non-empty check note now fails the case, so a deleted bucket or an object created by a malformed request cannot slip through behind a passing status check. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
aa5b337716 |
fix(s3): honor object ACLs for anonymous GET and HEAD (#11605)
* fix(s3): honor object ACLs for anonymous reads Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> * s3: drop unsigned session tokens on deferred anonymous reads An unsigned GET/HEAD carrying X-Amz-Security-Token is anonymous, not a session request; strip the token before authentication and authorization so it cannot influence identity or policy evaluation. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
483dd4b12e |
s3api: persist ACLs on PutObject uploads (#11592)
* s3api: persist ACLs on PutObject uploads Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> * s3api: fix PutObject ACL edge cases found in review - Only enforce BucketOwnerEnforced when explicitly configured; buckets without a stored ownership control keep accepting upload ACLs - Ignore ACL query parameters on SigV2 requests, which do not sign them - Mirror signed-query ACL values into headers after authentication so grant parsing and resolveFileMode agree on presigned uploads - Validate only caller-supplied grantees against the account registry; default grants now work for accounts outside the local registry - Reject unknown grantee keys and accept comma-separated grantee lists without spaces in ParseCustomAclHeader - Guard against identities without an account * s3api: harden upload ACL parsing and authorization Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> * s3api: evaluate upload ACL grantees individually in policies A comma-joined grant header or a signed query parameter reached policy conditions as one value, so a deny on a later grantee did not fire. Split grant headers into per-grantee values for policy evaluation and share the grantee pair parser with ParseCustomAclHeader. * s3api: keep raw grant header values visible to policy conditions Exact-match conditions written against the signed header value stopped matching once grantees were split for evaluation. Preserve the original wire values alongside the per-grantee values so deny policies fire on either granularity. * s3api: evaluate upload ACL grants as one canonical list in policies Conditions on s3:x-amz-grant-* now see a single comma-separated canonical grant list identical for a single line, repeated header lines, or a signed query parameter. This keeps StringEquals allows and exact-list or allowlist (StringNotEquals) denies accurate regardless of wire encoding. * s3api: preserve upload ACL denies and align policy checks Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> * s3api: retain upload owner grants and literal policy values Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> --------- Signed-off-by: zhaoyuchen <43179751+zhao-yc@users.noreply.github.com> Co-authored-by: Chris Lu <chris.lu@gmail.com> |
||
|
|
52fb9f93ff |
s3: track filer joins and leaves pushed by the master (#11563)
* fix(s3): track filer joins and leaves pushed by the master The S3 FilerClient replaced its -filer seed with a master snapshot of filer IPs at boot and refreshed it only every 5 minutes. A rolling restart replaces every filer well inside that window, leaving S3 servers with only dead addresses and failing every write until the next poll. Apply the master's ClusterNodeUpdate pushes to the filer list as they arrive, keeping the poll as a backstop. The last filer is never removed, and a poll snapshot requested before a push was applied is discarded rather than overwriting newer membership. * Defer last-filer leaves; bump the generation only on real changes * fix(s3): cancel deferred filer leaves on rejoin and on discovery A deferred last-filer leave outlived the filer it was recorded for: a rejoin at the same address looked like a duplicate add, and a discovery snapshot left the entry behind. The next join then removed a live filer until the following poll. A join now cancels any deferred leave for its address, and an applied snapshot clears them, since it is the master's current membership. * Bump the push generation when a rejoin cancels a deferred leave --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> |
||
|
|
895d49b55b |
s3/iam: manage roles through the IAM API, with an opt-in persistent role store (#11522)
* s3/iam: manage roles through the IAM API, with an opt-in persistent role store
Roles could only come from the IAM config file: the S3 server pinned the
role store to memory and the embedded IAM API had no role actions, so a
role could not be created, retrusted or revoked without editing the file
and restarting every gateway.
Role store
- Read the `roleStore` key (the IAMConfig field already existed). With an
IAM config file the default stays memory; with none it is the filer, as
for OIDC providers, so zero-config clusters keep runtime-created roles.
- Roles from the IAM config file never go into a persistent role store,
which outlives the file and may be shared by S3 servers with different
files. They are served from memory beneath the store, as OIDC providers
are: a stored role of the same name takes precedence, and deleting it
restores the file's. A config-file role cannot be changed or deleted
through the API (UnmodifiableEntity), and removing one from the file
removes it at the next start. An in-memory store holds them as records,
as before. They have no creation time, so CreateDate is omitted rather
than reporting when this server started. SetRoleStore installs a store
the same way, so a store set after startup keeps the config-file roles,
as SetOIDCProviderStore does for providers.
- Watch /etc/iam/roles and drop the cached role definitions on change. The
cached filer store otherwise serves a peer's stale role for up to its 5m
TTL, which keeps a revoked trust policy in force on the other gateways.
- Role stores wrap ErrRoleNotFound for a missing role; the filer store
used to report any failed lookup as "role not found". CreateRole proceeds
only on a confirmed absence, so an unreadable store cannot let it write
over an existing role.
IAM actions
- CreateRole, GetRole, ListRoles, DeleteRole, UpdateAssumeRolePolicy,
AttachRolePolicy, DetachRolePolicy, ListAttachedRolePolicies. The reads
are allowed in read-only mode.
- A role defined in the config file is reloaded from it at every start, so
changing or deleting it through the API is refused (UnmodifiableEntity)
rather than silently reverted.
- DeleteRole with policies attached is refused (DeleteConflict), as on AWS.
- Role names follow AWS's rules ([\w+=,.@-]{1,64}); a role is stored as
<name>.json in the filer, so this also keeps a name from leaving the role
store's directory. At most 10 managed policies per role (AWS's default
quota; MaxManagedPoliciesPerUser is 10 too), LimitExceeded beyond.
- DeletePolicy is refused (DeleteConflict) while a role attaches the
policy, as it already is for users and groups: roles attach policies by
name, so a policy created later under the deleted one's name would
otherwise take effect on the role.
- Role paths other than "/" and role tags are not stored, so they are
refused rather than dropped.
Role IDs and sessions
- Roles get a unique RoleId when first stored (random, AWS AROA form),
kept across updates; a config-file role gets a stable ID derived from its
name, since it is created again at every start.
- Sessions issued through AssumeRoleWithWebIdentity, AssumeRoleWithCredentials
and AssumeRole carry the role's ID (claim "rid"), and a request under a role
whose current ID differs is denied. Resolving a session's policies by role
name let a session outlive its role: once a role was deleted, a role later
created under the same name — with a different trust policy and different
policies — revived every unexpired session of the old one with the new
role's permissions. Sessions issued before this change carry no ID and are
unaffected until they expire.
Integration test (test/s3/iam, run with `make start-services`):
TestWebIdentityWithProviderAndRoleManagedThroughIAMAPI configures an OIDC
provider, a managed policy and a role entirely through the IAM API against a
JWKS served by the test, then checks the trusted subject gets credentials
scoped to the attached policy; another subject, a token signed by another
key, an unsigned token and a token for another audience are refused; and UpdateAssumeRolePolicy moves the
trust at once.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: bind every role session to its role, and change roles atomically
Review follow-ups.
Session binding
- The role-ID check ran only when a session carried no policy names, and
AssumeRole embeds the role's attached policies, so those sessions kept
their permissions after the role was deleted or recreated. The check
now runs for every session carrying a role ID, before policy selection.
- A named role that cannot be resolved at issuance gets no session,
instead of one with no role ID (which nothing binds).
- A config-file role's ID is derived from its name and trust policy, not
the name alone: a different role put in the file under the same name
gets a new ID, while an unchanged role keeps its sessions across restarts.
Role writes
- RoleStore gains UpdateRole, a read-modify-write that lands only if the
role is unchanged since the read, and otherwise re-reads and retries. The
filer store uses the filer's write conditions (IF_NOT_EXISTS for a new
role, IF_ENTRY_EQUAL otherwise). CreateRole, UpdateAssumeRolePolicy and
Attach/DetachRolePolicy all go through it, so two gateways no longer
overwrite each other's changes, a change racing a delete no longer
writes the role back, and of two concurrent creates one gets
EntityAlreadyExists.
- The filer store's ListRoles pages past 1,000 entries and fails on a
broken stream instead of returning what arrived, so DeletePolicy's
attachment check sees every role. ListRoles skips a role deleted between
listing and reading it.
- CreateRole validates first; a failed write is ServiceFailure, not
InvalidInput. Any Tags.* parameter is refused, not only the first key.
- ExecuteAction's skipPersist covers the S3ApiConfiguration only; the
comment now says so. Role and OIDC provider actions write their own stores.
Each fix has a test that fails without it. Against a real filer with two
gateways, concurrent AttachRolePolicy calls lost 1-4 of 8 attachments per
run before this change and none after.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: one role snapshot per decision; DeleteRole is atomic; watch a custom role store path
Review follow-ups.
- Authorization evaluates the policies of the role definition the session's
binding was checked against, instead of reading the role again: a role
replaced in between cannot lend a session its policies.
- AssumeRole and AssumeRoleWithLDAPIdentity issue the session from the
definition whose trust admits the caller (IAMManager.ResolveRoleForPrincipal),
and take its ID, duration cap and embedded policies from that same
definition. A role replaced after the caller's trust check by one that does
not trust the caller now yields AccessDenied, not a session bound to the
replacement.
- A RoleUpdate that returns nil deletes the role, on the same condition as a
write: the filer store deletes with ObjectTransaction on IF_ENTRY_EQUAL,
routed and locked like the conditional CreateEntry. DeleteRole decides
against the role it deletes, so a policy attached meanwhile on another
server is a DeleteConflict, and a delete never removes a role written
after its check.
- S3 servers watch the role store's configured basePath, not only
/etc/iam/roles, so a custom path also drops peers' cached roles on change.
Each has a test that fails without it. Live against a real filer: DeleteRole
refuses while a policy is attached and removes the entry once detached; all
test/s3/iam CI stages pass.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: state which roles DeletePolicy's attachment check can see
RolesAttachingPolicy sees the stored roles and this server's config-file
roles. A role defined only in another server's IAM config file is invisible
to it, so a config-file role that attaches a managed policy is protected
only on the servers whose file defines it. The doc comment now says so and
how to avoid it: keep such roles in every server's file, or attach only
config-file policies to config-file roles.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* iam: note that a role store set after startup is not watched for peer changes
S3 servers build their metadata watch list once, at startup, from the role
store installed then. SetRoleStore's doc now says that a filer-backed store
installed later with a different basePath is not watched, so peers' changes
to it reach this server's cached roles only when the cache expires.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
||
|
|
5da137233d |
s3/iam: persist IAM-managed OIDC providers in the filer, and trust them after a restart (#11510)
* s3/iam: persist IAM-managed OIDC providers in the filer, and trust them after a restart
The S3 server's IAM config loader never read the documented
`oidcProviderStore` key, so the OIDC provider store was always in memory:
a provider created with CreateOpenIDConnectProvider lived in one gateway's
process, was lost on restart, and was never seen by peers. The
/etc/iam/oidc-providers metadata subscription refreshed from that empty
in-memory store.
- Read `oidcProviderStore` and pass it to the IAM manager. With an IAM
config file the default stays memory. With no config file (zero-config
IAM, as `weed filer -s3` and operator-managed clusters run) it defaults
to the filer: there is nothing static to shadow, and providers created at
runtime otherwise vanish on restart.
- With a store that outlives the process, load the STS runtime view from it
at startup, so providers created on an earlier boot or on a peer are
trusted without waiting for the next mutation.
- If the store cannot be read at startup (a filer not up yet), the load is
retried in the background with backoff until it succeeds: the metadata
subscription reports only later changes, so providers already stored would
otherwise stay unknown to STS until one of them changed.
- Mark records mirrored from STS.Providers as `source: static-config`, and
at startup delete such records whose provider has left the config, so
removing a provider from the config file still revokes it. Records created
through the IAM API are never pruned.
- The filer store reported every failed lookup, an unreachable filer
included, as ErrOIDCProviderNotFound, which CreateOIDCProvider reads as
"free to create". Only a confirmed absence is now not-found.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: keep config-file OIDC providers out of a persistent store
Review of the previous commit found that mirroring the IAM config file's
providers into a persistent store, and pruning them when they leave the
file, breaks as soon as S3 servers share a filer:
- a server prunes stored config-file providers its own file does not list,
including ones a peer's file still defines (a zero-config server prunes
them all);
- mirroring overwrites an API-created provider with the same ARN and marks
it config-owned, so a later prune deletes it;
- a failed mirror write or a failed prune leaves a stale record trusted;
- a mirrored record is loaded into STS at startup as an IAM-managed provider
and shadows the config-file provider, dropping the settings a record does
not carry (jwksUri, roleMapping, policyClaim, ...).
A persistent store now never receives the config file's providers. STS keeps
serving them from its static configuration, as it always has; the IAM API
lists and returns them from memory, refuses to change or delete them
(UnmodifiableEntity; change them in the file) and to create another provider
with their ARN (EntityAlreadyExists). The store holds only providers created
through the IAM API, and those are what startup loads into STS. There is
nothing to prune, so the source marker is gone. An in-memory store keeps its
behaviour: the config file's providers are records in it, as before.
buildOIDCProviderFromRecord also carries PolicyClaim and
AllowedPrincipalTagKeys now; they were dropped whenever an API-created
provider was loaded into STS.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: send UnmodifiableEntity as a 400, not an internal error
The IAM API's error writer had no case for UnmodifiableEntity, which the
previous commit returns for a change to a config-file provider, so it went
out as a 500 ServiceFailure that clients retry. AWS sends it as a 400.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* s3/iam: document stored-over-config precedence, drop invented CreateDate, cancel superseded retries
Follow-ups from review of
|
||
|
|
f31a026b2a |
master,filer: fix lock ring poisoning after leader change (#11453)
* cluster: never broadcast an empty lock ring An empty member list is never a usable ring state, but a delayed RemoveServer on a former leader can fire after the new leader already broadcast the recovered ring. That late broadcast carries a newer wall-clock version, so clients accept the empty ring and permanently reject the good one. Skip the broadcast entirely when the member list is empty, keeping the last non-empty snapshot for reconnecting clients. * cluster: periodically rebroadcast the lock ring Ring updates are purely event-driven, so one lost or poisoned update is permanent until the next membership change — with a single filer that may never come. Re-arm a per-group timer after every broadcast so the current leader keeps re-sending the ring; clients reject nothing newer than their last accepted version, so a re-sent snapshot always heals a stale view. * filer,s3api: reset the lock ring on master change Ring versions are per-master monotonic — each master stamps wall-clock nanoseconds — so a late high-version update accepted from a former leader makes the new leader's snapshot look stale forever. Detect a leader change across the reconnect gap (currentMaster is cleared between attempts, so remember the last served master) and reset the ring to bootstrap state so the new leader's view always applies. * cluster: fail lock acquisition when no lock server exists retryUntilLocked loops forever, so a filer reporting an empty lock ring wedges every append write indefinitely. Bound only the "no lock server found" case — ordinary contention is still waited out since the holder releases eventually. The constructors now return nil on failure: the filer append path and S3 object writes fail fast, while mounts degrade to their existing lockless mode. * cluster: reset only the ring version on master change Ring versions are per-master monotonic, so a version gate reset is all a leader change needs. Clearing the whole ring made every filer its own write owner until the next update and dropped the prior-owner window for keys the new leader remaps; the last ring now keeps routing until the new leader's snapshot transitions off it. * cluster: skip redundant ring installs and defer rebroadcasts An unchanged member list now only bumps the accepted version instead of installing a snapshot: periodic rebroadcasts no longer fire the topology-change callback or restart the prior-owner window. And a rebroadcast that lands inside a membership stabilization window yields to the pending timer rather than publishing an intermediate ring. * cluster,mount: bound lock unavailability, fail ops that cannot lock Only 'lock already owned' contention retries without bound now; every other failure — no lock server, or a dead ring member refusing connections — shares the same unavailability budget, so a ring naming departed filers can no longer hang a lock forever. Mount open-write, create, and rename fail with EAGAIN when the required lock cannot be acquired instead of proceeding without cross-mount serialization. * cluster: check pending stabilization inside the broadcast critical section rebroadcast released the mutex between the pending-timer check and nextBroadcastUpdate, so a membership change arriving in the gap could arm a stabilization timer while the rebroadcast emitted an intermediate ring. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: acquire path locks before mutating create/rename state Create took the DLM lock only after the filer create, so a lock failure returned EAGAIN with an eagerly persisted file left behind. Rename marked source handles renamed before acquiring locks, so a failed acquisition left them suppressing old-path flushes for a rename that never happened. Both now take the locks first; the create's lock is released again if the entry race loses to another creator and AcquireHandle takes over. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: keep the old-path lock when rename lock migration fails The migration stopped the handle's lock before acquiring the replacement, so a nil result left the handle writing with no lock at all. Acquiring the new-path lock first means failure keeps the existing lock instead of reporting success with serialization dropped. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: skip new-path rename lock when a handle already holds it A target file open for write on this mount already carries a lock on newPath; the lock manager does not grant a second lock to the same owner, so the rename would wait on itself until the handle closed. Also avoid locking twice when old and new paths coincide. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: hand the rename's target lock to the migrating handle The rename holds a lock on newPath for its duration, so the response migration's fresh acquisition waited on that same lock until the handle released — under fhLockTable, blocking the handle's own close. Adopt the rename's lock directly; nested move responses still acquire their own. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: move the replaced target's lock to the renamed handle When the target path was already locked by an open handle on this mount, the migrated source handle kept only its stale old-path lock — the target's close would then release the last lock on the new path while the renamed handle was still open. Adopt the replaced handle's lock instead. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: stop the handle lock inside the fh lock on release ReleaseHandle stopped fh.dlmLock before taking the fhLockTable slot, so a rename migration holding that slot could still observe and adopt a lock that was already stopping. Stopping under the fh lock makes the transfer serialize against the release. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: claim the replaced target's lock for the renamed handle When the target path is already locked by an open handle on this mount, adopting it at migration time keeps the renamed path protected after that handle closes, without waiting on a lock this mount already holds. If the handle was released mid-migration the claimed lock is stopped, and a fresh acquire covers the case where it was already gone. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: claim the target handle's lock before the rename runs Skipping the new-path lock when a handle already holds it let that handle's close release the lock mid-rename, leaving the path unguarded until the response migrated it. Take over the lock at check time and hold it for the rename's duration: the response adopts it for the migrating handle, or it returns to the target handle / is released on failure. The target handle lookup also falls back to the entry's stored inode for a forgotten path mapping. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * mount: read handle locks only under the fh lock during rename The loose dlmLock reads raced ReleaseHandle, which now mutates the lock inside the handle lock; check and claim it under the same hold. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> |
||
|
|
c72eda50a8 |
s3: drop implicit reader cache budget that throttled S3 GETs (#11384)
* fix(filer): leave reader cache unbounded without an explicit budget NewReaderCache silently installed a 256MiB ReaderCacheBudget when the caller passed none. Only weed mount opts into a budget; every other caller (S3 gateway, WebDAV, query engine, mq logstore) inherited the cap. Under ~90 concurrent S3 GETs of medium objects, prefetch wants far more than 64 chunk buffers, so reserve() serialized chunk fetches, clients timed out and retried, and the retry re-downloaded chunks the cancelled request had already fetched. A nil budget now means unbounded, restoring the pre-4.47 behavior for callers that never asked for a memory cap; reserve/complete/release are nil-safe. The mount path is unchanged and still enforces -readerCacheSizeMB. Fixes #11380 * feat(s3): expose -s3.readerCacheSizeMB reader buffer budget Operators who want the S3 gateway read path memory-bounded can now opt in: -s3.readerCacheSizeMB on weed filer/server/mini and -readerCacheSizeMB on standalone weed s3, matching the mount flag. The default 0 keeps the unbounded pre-4.47 behavior; a positive value installs a shared ReaderCacheBudget across in-flight and retained chunk buffers for all S3 GETs. * fix(filer): validate chunk size before consulting the reader budget A nil budget returned early and skipped the negative chunkSize check, letting a corrupted size reach mem.Allocate and panic. Also drop the command-specific flag prefix from the S3 validation error since standalone weed s3 exposes the option as -readerCacheSizeMB. * filer: drop chunk buffers once fully consumed ReaderCache retained every completed chunk buffer in the downloaders map until the slot limit evicted it, so buffers lingered after all readers finished with them. Track attached readers on each SingleChunkCacher and remove the cacher when the last reader consumes the buffer to its end. In-flight download deduplication and the prefetch handoff are unchanged: a buffer always survives until fully read, partial reads keep it available, and an attached reader pins a consumed buffer until it detaches. Repeat reads now go through the chunk cache where enabled, or refetch. * filer: drop consumed buffers on last detach, rechecked under cache lock Two review findings on the drop-on-consume change: - Removal only fired when the detaching reader itself reached the chunk end. If the end-reaching reader finished first and the last remaining reader did a partial read or cancelled, the consumed buffer and its budget reservation lingered until eviction. Track a persistent consumed flag instead, so any end-reaching read marks the buffer and the last detach drops it. - remove() checked only map identity, so a reader attaching between the reader count hitting zero and removal could attach to a cacher that was then deleted underneath it. removeConsumed() re-checks identity, readers == 0, and consumed under the ReaderCache lock; a raced attach keeps the cacher and its own detach retries the removal. |