Compare commits

...
Author SHA1 Message Date
Chris Lu eed4474e61 master: deprecate legacy seaweedfs/raft
Warn at startup when the legacy raft engine is selected and note the
deprecation in the -raftHashicorp help. The default is unchanged so a
multi-master rolling upgrade is not silently switched to an incompatible
engine mid-cluster; operators opt in, and the identity migration carries
state across.
2026-06-05 14:46:31 -07:00
Chris Lu c5121f3dba master: carry cluster identity from legacy raft into hashicorp raft
On a master's first start on hashicorp raft, import TopologyId and MaxVolumeId
from an existing seaweedfs/raft (legacy) snapshot so the cluster keeps its
identity instead of generating a fresh one. A marker in the hashicorp stable
store makes the import one-time; later restarts skip it. With no legacy state
the marker is still set, so a fresh install never re-scans.
2026-06-05 14:45:33 -07:00
Chris Lu ab7be7867d security: hot-reload JWT signing keys on SIGHUP (#9826)
* security: reload JWT signing keys on SIGHUP

Signing keys were read once in the server constructors and never
refreshed. After a key rotation (Secret update, divergent reads) the
in-memory key stayed stale and every request kept failing "wrong jwt"
until the affected process was restarted.

Add Guard.UpdateSigningKeys and call it from the master, volume and
filer reload paths and the s3 reload hook, next to the existing
whitelist refresh. Make the global chunk-read JWT cache reloadable via
an atomic swap, and register the master's Reload with grace.OnReload --
it was never wired, so the master ignored SIGHUP entirely.

Mirror the same refresh in the Rust volume server's SIGHUP handler.

* security: swap signing keys behind an atomic pointer

Addresses review feedback on the in-place key swap: SigningKey is a
[]byte, so reassigning the Guard fields while a request handler reads
them is a data race that can tear the multi-word slice header and read
out of bounds.

Hold the four signing-key fields in an immutable signingConfig snapshot
behind atomic.Pointer; UpdateSigningKeys swaps the whole pointer, so a
reader sees either the old keys or the new ones. Reads go through new
SigningKey/ExpiresAfterSec/ReadSigningKey/ReadExpiresAfterSec accessors.

The Rust guard is already safe: every read and the SIGHUP write go
through the shared RwLock<Guard>.

* security: fold whitelist + auth state into the atomic snapshot

Review follow-up. UpdateSigningKeys still wrote isWriteActive while the
request path read it (and the whitelist maps) unsynchronized, so a SIGHUP
under load could expose an inconsistent mix of activation bits and
whitelist contents.

Move all hot-reloadable Guard state -- keys, expirations, whitelist, and
the activation flags -- into a single immutable guardState swapped behind
one atomic.Pointer. The Update* methods take a small mutex to serialize
the read-modify-write; readers stay lock-free. The concurrency test now
also rotates the whitelist and probes IsWhiteListed under -race.

Also read each signing key once per branch in the volume/filer JWT auth
checks, so a reload landing mid-check can't take the allow-fast-path
after auth was enabled or verify against a different key than the branch
saw.
2026-06-04 22:26:08 -07:00
Chris Lu 0d72023fac fix(master): advance maxVolumeId when registering EC shards (#9827)
* fix(master): advance maxVolumeId when registering EC shards

After EC encoding the original normal volume is deleted, so a
high-numbered volume can exist only as EC shards. Only regular volumes
advanced maxVolumeId (Disk.doAddOrUpdateVolume), so a master that
rebuilt its state from heartbeats (raft state not resumed) undercounted
the max and NextVolumeId could re-issue an id that EC shards still
occupy. A new volume then gets created on top of the EC volume id; new
writes land on it, but reads route to the old EC shards whose .ecx never
held the new needle, returning 404 and corrupting that object.

Advance maxVolumeId when EC shards are registered, mirroring the
regular-volume path. RegisterEcShards is the chokepoint both the full
and incremental heartbeat sync paths funnel through.

* test: cover incremental heartbeat path for EC maxVolumeId

Both SyncDataNodeEcShards and IncrementalSyncDataNodeEcShards funnel
through RegisterEcShards; assert the invariant on the incremental path
too.
2026-06-04 22:25:30 -07:00
Chris Lu 8d59069a0a s3: return BucketAlreadyOwnedByYou when recreating your own bucket (#9822)
* s3: return BucketAlreadyOwnedByYou when recreating your own bucket

PutBucket returned BucketAlreadyExists for every existing bucket, even
when the caller already owns it, so idempotent re-creation (e.g. a
container that creates its bucket on startup) couldn't tell "someone
else took the name" from "it's already mine".

Recreating a bucket you own now returns BucketAlreadyOwnedByYou, unless
the request conflicts with the existing bucket: a different Object Lock
setting, or an ACL on the request or the existing bucket. To detect the
latter, a requested non-default canned/grant ACL is now persisted on
creation instead of being dropped.

* s3: fail PutBucket when the existing bucket's config can't be read

When a bucket already exists, an unreadable config left the recreate
defaulting to BucketAlreadyOwnedByYou, masking the backend error and
possibly accepting a conflicting recreate (Object Lock / ACL unknown).
Surface the read error instead.

* s3: return the stored bucket ACL from GetBucketAcl

GetBucketAcl always returned the owner's default full-control grant and
ignored any stored ACL, so a bucket created with a canned ACL or one set
via PutBucketAcl never read back correctly. Decode the stored grants
instead, sharing one grants-to-XML helper with the object ACL handler.

The shared helper also emits each grantee's real xsi:type (e.g. Group for
public-read) instead of a hardcoded CanonicalUser, so group grants read
back correctly for both bucket and object ACLs.

* s3: resolve the right already-exists error on the concurrent-create race

When two requests create the same bucket at once, the loser's mkdir
fails and the handler fell back to a flat BucketAlreadyExists, bypassing
the same-owner idempotency check. Route both the pre-check and the race
fallback through one existingBucketError helper so a same-owner recreate
still gets BucketAlreadyOwnedByYou.

* s3: record the bucket owner's account id at creation

setBucketOwner only stored the creating identity name, so the canonical
account id wasn't available later. Persist it under ExtAmzOwnerKey too,
the same field PutBucketAcl writes, so the bucket owner can be reported
independently of whoever reads it.

* s3: report the bucket owner from GetBucketAcl, not the caller

GetBucketAcl built the ACL Owner from the caller's account header, so an
admin or cross-account read returned the wrong owner. Use the owner
persisted on the bucket, falling back to the caller only when none is
recorded.
2026-06-04 15:33:03 -07:00
Chris Lu a24f4844d3 filer: keep S3 list order byte-lexicographic regardless of SQL name column collation (#9824)
* mysql: keep S3 list order byte-lexicographic regardless of name column collation

ORDER BY name and the name > ? pagination predicate follow the column
collation, so a case-insensitive filemeta.name (e.g. utf8mb3_general_ci)
returns S3 keys out of byte order and breaks clients that merge two sorted
listings.

Detect the live name collation at startup; only when it isn't binary, wrap
the list comparison, prefix, and ORDER BY in BINARY name so order and
pagination stay consistent. Correctly configured utf8mb4_bin tables keep
their indexed range scan unchanged, and the operator gets a warning to
convert the column.

* postgres: keep S3 list order byte-lexicographic regardless of name column collation

ORDER BY name and the name > $n pagination predicate follow the column or
database collation, so a locale-aware filemeta.name (e.g. the en_US.UTF-8
database default) returns S3 keys out of byte order and breaks clients that
merge two sorted listings.

Detect the live name collation at startup; only when it isn't byte-ordered,
wrap the list comparison, prefix, and ORDER BY in COLLATE "C" so order and
pagination stay consistent. A byte-ordered (C/POSIX/C.UTF-8) column keeps its
indexed range scan unchanged, and the operator gets a warning to declare the
column COLLATE "C".
2026-06-04 14:33:41 -07:00
Chris Lu 8c2d9f466f filer: stream persisted log files when serving metadata subscriptions (#9821)
* filer: stream persisted log files when serving metadata subscriptions

readFileEntries buffered every LogEntry of a whole log file into memory
before returning them one by one, making a subscription read O(entries in
one log file) instead of O(one entry). On a filer with large per-entry
metadata, many concurrent SubscribeMetadata streams each loading a full
log file exhausted memory.

Keep a current LogFileIterator and return one entry at a time, advancing
files as each is exhausted. The deleted-volume skip is preserved.

* filer: close the log file iterator on read errors too

A genuine read error returned early without closing the current
LogFileIterator, leaving its ChunkStreamReader alive until GC. Close on
every exit path and propagate only a real error.

* filer: close persisted-log iterators when a subscription stops early

The streaming iterator keeps a log file reader open across calls, so a
subscription that returns before EOF (early stop, cancellation) left the
reader alive until GC. Add idempotent Close on LogFileQueueIterator and
OrderedLogVisitor, and have ReadPersistedLogBuffer wait for the readahead
goroutine and close the visitor on the way out.
2026-06-04 13:27:25 -07:00
7y-9andChris Lu 6e8002f065 fix: handle meta backup offset errors safely (#9818)
* fix: log meta backup offset errors

* fix: log meta backup offset errors

* fix: exit on meta backup offset errors

Exit with a non-zero status when the initial metadata backup offset cannot be persisted.

Classify offset-read failures during streaming so the backup process exits instead of retrying forever, allowing supervisors to restart and bootstrap from a missing checkpoint.

* meta backup: read offset in the loop, drop offset error type

Reading the saved offset inside the retry loop makes an offset read
failure a clean exit and a stream error a retry, without a typed error
to tell them apart. streamMetadataBackup now takes the start time.

---------

Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-04 10:53:23 -07:00
Chris Lu 3e8ec879c4 s3: keep dynamic IAM live when -iam.config is set (#9817)
* s3: keep dynamic IAM live when -iam.config is set

-iam.config was treated like a static -config identity file: it set
useStaticConfig, which makes the filer metadata subscription skip
reloads. Identities and policies created at runtime (the IAM gRPC API)
then never took effect, so advanced IAM (OIDC/STS) and dynamic IAM were
mutually exclusive.

Gate useStaticConfig on whether inline identities were actually loaded.
An OIDC/STS-only config carries none, so it keeps the dynamic credential
store live; a -config identity file still freezes its identities as
before.

* s3: mark static identities on config reload too

A -config reload (grace.OnReload) re-reads the file, but only the startup
path marked its identities static, so identities added to the file and
reloaded were left unprotected from dynamic filer updates. Move the
marking into loadS3ApiConfigurationFromFile and make it additive and
scoped to the file's identities, so a reload protects newly added ones
without freezing dynamic filer-managed identities.

* s3: sync reloaded static identities into the credential manager

After marking a (re)loaded config file's identities static, push the
updated set into the credential manager so reloaded identities still
appear in listings and survive later dynamic merges. Centralize the sync
in loadS3ApiConfigurationFromFile and drop the now-redundant call in the
reload hook.
2026-06-03 23:28:25 -07:00
ce6a51468a sftpd: support SSH user certificates signed by a trusted CA (#9815)
* sftpd: support SSH user certificates signed by a trusted CA

Adds a new "certificate" auth method to weed sftp. When enabled, the server
loads trusted CA public keys from -trustedUserCAKeysFile (OpenSSH
authorized_keys format, one or more keys) and accepts only ssh.Certificate
blobs of type UserCert on the public-key channel. Validation uses
ssh.CertChecker: CA signature, ValidAfter/ValidBefore, non-empty
ValidPrincipals and SSH login user must appear in ValidPrincipals. The
authenticated user must exist in the user store; home dir and permissions
resolve as before.

Behaviour mirrors MinIO's --sftp=trusted-user-ca-key and OpenSSH's
TrustedUserCAKeys: when certificate auth is active, plain (non-cert) public
keys are rejected even if "publickey" is also listed. Default authMethods
remain "password,publickey", so existing deployments are unaffected.

* Update weed/sftpd/auth/certificate.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* sftpd: address review feedback on certificate auth

- Pre-marshal trusted CA public keys in IsUserAuthority instead of
  re-marshaling on every authentication attempt (gemini-code-assist).
- Differentiate user-not-found from underlying store errors via
  errors.As(*user.UserNotFoundError) so backend/read failures are no
  longer reported as bad credentials (coderabbitai).
- Fix the corresponding sanity check in the missing-file test to use
  errors.As instead of errors.Is (UserNotFoundError has no Is method,
  so the previous check never matched) (coderabbitai).

* sftpd: register trustedUserCAKeysFile flag in filer and server commands

The new field on SftpOptions is dereferenced unconditionally in
resolvePaths(), but only the standalone `weed sftp` command was wiring
its flag. `weed filer` and `weed server` both embed an SftpOptions value
and call resolvePaths() on it, so they hit a nil pointer dereference at
startup.

Register `-sftp.trustedUserCAKeysFile` in both commands and update the
-sftp.authMethods help text to mention the new "certificate" method.

Fixes the SFTP Integration Tests CI failure on this PR.

* helm: expose SFTP certificate auth in the SeaweedFS chart

Adds Helm-chart support for the new SSH user-certificate auth method:

- values.yaml (sftp:) gains `trustedUserCAKeys` (inline OpenSSH
  authorized_keys-format CA public keys) and `existingCAKeysSecret`
  (reference an externally managed Secret). Same pair added under
  allInOne.sftp with a null default that falls back to the top-level
  sftp.* setting.
- New template templates/sftp/sftp-ca-secret.yaml renders a
  chart-managed Secret <release>-sftp-ca-secret with `ca_user.pub`,
  but only when SFTP is enabled, "certificate" is in authMethods,
  inline keys are provided, and no existingCAKeysSecret is set.
- templates/sftp/sftp-deployment.yaml and the all-in-one deployment
  template add `-trustedUserCAKeysFile=/etc/sw/sftp_ca/ca_user.pub`
  to the weed sftp command, mount the CA secret at /etc/sw/sftp_ca
  and add the corresponding volume. All cert-auth bits are guarded
  by `contains "certificate" authMethods` so existing users see no
  change.
- authMethods help text updated to mention "certificate".

Verified end-to-end on a local k3d cluster: cert login succeeds,
plain-pubkey login is rejected with "public key without certificate
not allowed".

* helm: fail render when SFTP certificate auth lacks CA keys

When certificate is in authMethods but neither trustedUserCAKeys nor
existingCAKeysSecret is set, the deployment mounted a secret that the
chart never renders, leaving the pod stuck on a missing volume. Fail at
template time with a clear message instead.

* sftpd: fix stale auth-method list in SFTPServiceOptions comment

keyboard-interactive was never implemented; certificate is the new
supported method. Match the CLI help text.

* sftpd: test Manager wiring of certificate vs public-key channel

Cover the channel takeover at the Manager level: certificate auth
displaces plain public-key auth when both are enabled, public-key auth
stays put otherwise, and enabling certificate without a CA file errors.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-03 22:32:47 -07:00
Chris Lu df879e1ed7 filer: bound TraverseBfsMetadata memory by queuing directory paths (#9814)
* filer: bound TraverseBfsMetadata memory by queuing directory paths

The BFS enqueued every entry, so it held the whole subtree in memory
including each file's chunk list. A filer serving a peer's first-time
bootstrap traversal of a large tree could exhaust memory and get killed.

Stream each entry as it is visited and queue only directory paths to
descend into. Memory is now bounded by the number of directories rather
than the entire tree, and the streamed output order is unchanged.

* filer: match excluded prefixes on path-component boundaries

Only treat an excluded prefix as a match when it ends at a path
boundary, so excluding /a/b does not also drop a sibling like /a/bc.
Short-circuit the trie walk on the first real match.
2026-06-03 10:28:42 -07:00
Konstantin Lebedev df833d485f [test] update docker image for s3test (#9811) 2026-06-03 09:45:00 -07:00
Lars Lehtonen d321e463e9 chore(weed/storage/needle): prune unused test functions (#9812) 2026-06-03 09:26:28 -07:00
Chris Lu ef1aa4f936 s3: defer a recently-unreachable owner that is also the current filer (#9808)
Blanking preferred kept route-by-key reads from dialing a flagged owner first,
but withFilerClientFailover always re-adds the current filer, so when the owner
is the gateway's current filer it stayed in the candidate list and got dialed
anyway. Treat a recently-unreachable filer as unhealthy in the health partition
so it is deferred to the last-resort tail instead of tried before healthy
replicas; preferred is still tried first, and a live owner is unaffected.
2026-06-03 00:28:56 -07:00
Chris Lu 2d1b8be22b s3: route object reads to the key's owner filer (#9806)
* s3: route object reads to the key's owner filer

Writes already route by key to the owner filer on the lock ring, where the
entry is created. Reads went to the gateway's local filer and treated its
NotFound as authoritative, so a GET on one gateway could miss an object
another gateway had just written until the filers' metadata replication
caught up.

Resolve an object's entry from the key's owner first, failing over to the
gateway's filer set only on transport errors. An owner NotFound stays
authoritative: no fan-out across filers, and no resurrecting a peer's
not-yet-replicated tombstone, so a delete routed to the owner is visible at
once and a genuine miss costs one lookup. Keys owned by the local filer are
unchanged. Objects written through the non-routed lock path land on a
gateway's local filer, so they can still read as absent on the owner until
they replicate.

withFilerClientFailover takes a preferred start filer; the object-entry
reads pass the owner, every other caller passes "" and keeps the
current-filer fast path.

* s3: consult the prior owner on a rebalance-window read miss

Owner-first reads route a key to its current ring owner. When a filer joins,
~1/N of keys reassign to it, and the new owner may not have replicated a
just-moved key yet, so an owner NotFound would surface a transient 404 for an
object that already exists elsewhere.

Retain the previous ring on the gateway's LockClient for a cooling-off window
(PriorOwnerForKey, mirroring the master's LockRing.PriorOwner) and, on the
owner's NotFound, probe the key's previous owner once before treating the miss
as final. The probe is scoped to keys whose ownership actually moved and only
within the window, so steady-state reads are untouched.

This trades the transient scale-up 404 for a transient stale read if a delete
routed to the new owner races the same window — the same authoritative-NotFound
tradeoff, narrowed to the rebalance.

* s3: try healthy filers before unhealthy ones on failover

The candidate list probed its first entry (usually the current filer)
unconditionally, so a health-flagged current filer cost a transport timeout on
every ordinary call before failover reached a replica. Partition candidates into
healthy and unhealthy, keep priority within each, and fall back to unhealthy
ones only when all healthy ones fail.

* reduce comments on the routed read and lock client paths

* s3: skip a recently-unreachable owner on route-by-key reads

The gateway's filer health tracking no-ops for an owner outside the static
-filer list, so during a sustained owner outage every route-by-key read
re-dials the dead owner before failing over. Flag an owner whose owner-first
read hit a transport error and skip it (read local-first) for a short TTL, so
reads pay one dead dial per TTL instead of one per request; the flag expires so
owner-first reads resume once the owner or the ring recovers.

* s3: always try the preferred owner first, health-order only the rest

The healthy/unhealthy partition also demoted a health-flagged preferred owner
behind healthy replicas, so a replica's authoritative NotFound could mask a
write that had only reached the owner — the read-after-write race this routing
exists to close. Pull preferred out of the partition and keep it first; the
recently-unreachable gate already steers reads away from a genuinely dead owner.
2026-06-03 00:12:28 -07:00
Chris Lu 4e5839ce82 fix(iam): return a valid user ARN from CreateUser and GetUser (#9794)
* fix(iam): return a valid user ARN from CreateUser and GetUser

The terraform aws provider 6.41 reads a user back after creating it and
blocks until GetUser returns a value that passes arn.IsARN. We only set
UserName, so the ARN was empty and apply hung until the 2m timeout.
Populate Arn (and Path) via a shared iam.NewUser helper in both the
embedded and standalone IAM handlers.

* fix(iam): use the userName parameter directly in NewUser

Drop the redundant local copy; the value parameter is already function-local.

* fix(iam): return full user objects with ARNs from GetGroup

GetGroup listed members with only UserName set. Build them via the shared
NewUser helper so group members carry a valid Arn and Path like the other
user responses, in both the embedded and standalone IAM handlers.
2026-06-02 22:01:57 -07:00
Chris Lu f711868fb6 fix(log_buffer): re-check buffer before bailing with ResumeFromDiskError (#9804)
ReadFromBuffer and HasData() take the read lock separately, so a write
that lands between them can make a subscriber which just read a
momentarily empty buffer return ResumeFromDiskError even though the data
is now servable from memory. Re-read under a fresh lock and only bail
when the position is genuinely behind the in-memory window (flushed to
disk); otherwise loop back and read it.
2026-06-02 21:37:15 -07:00
dependabot[bot]andChris Lu 24159fbff9 build(deps): bump opentofu/setup-opentofu from 1 to 2 (#9801)
Bumps [opentofu/setup-opentofu](https://github.com/opentofu/setup-opentofu) from 1 to 2.
- [Release notes](https://github.com/opentofu/setup-opentofu/releases)
- [Commits](https://github.com/opentofu/setup-opentofu/compare/v1...v2)

---
updated-dependencies:
- dependency-name: opentofu/setup-opentofu
  dependency-version: '2'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-06-02 21:37:05 -07:00
Chris Lu 7b44cf5627 fix(iam): implement CreatePolicyVersion for managed policies (#9795)
* fix(iam): implement CreatePolicyVersion for managed policies

The AWS Terraform provider updates a managed policy in place via
CreatePolicyVersion, which returned 501 NotImplemented and broke
terraform apply on any policy change.

Implement CreatePolicyVersion (plus ListPolicyVersions, GetPolicyVersion
and DeletePolicyVersion) on both the standalone IAM server and the
embedded S3 IAM API. Managed policies keep a single current document, so
each is modeled as one default version "v1": CreatePolicyVersion replaces
the document, List/GetPolicyVersion expose it, and DeletePolicyVersion
rejects deleting the default. GetPolicy now reports DefaultVersionId so
the provider's read can fetch the document. The standalone path also
refreshes the cached Identity.Actions of every identity the policy is
attached to so the new document takes effect.

* fix(iam): reject CreatePolicyVersion unless SetAsDefault=true

With a single always-default managed-policy version, a request with
SetAsDefault=false (or omitted) would stage a non-default version on AWS
but here silently replaced the active document. Reject it on both the
standalone and embedded paths.

Isolate the new policy-version tests from the shared package fixtures so
they stay order-independent, and assert IsDefaultVersion on the response.
2026-06-02 21:35:02 -07:00
Chris Lu b6a0bde16b test(s3/iam): scope ListBucket isolation via s3:prefix condition (#9805)
The username-isolation policy denied s3:ListBucket through an object-path
NotResource. ListBucket is bucket-level, so its resource ARN is the bucket
and never matches an object path: the Deny always fired and a user could
not list their own prefix. Scope the per-user List deny with a StringNotLike
s3:prefix condition instead, the same mechanism the matching Allow uses.
2026-06-02 18:41:10 -07:00
dependabot[bot] 6bffe3f56a build(deps): bump google.golang.org/grpc from 1.80.0 to 1.81.1 (#9797)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.80.0 to 1.81.1.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.80.0...v1.81.1)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-version: 1.81.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 18:27:52 -07:00
dependabot[bot]andChris Lu 69bc7325ca build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3 from 3.134.2 to 3.139.5 (#9796)
build(deps): bump github.com/ydb-platform/ydb-go-sdk/v3

Bumps [github.com/ydb-platform/ydb-go-sdk/v3](https://github.com/ydb-platform/ydb-go-sdk) from 3.134.2 to 3.139.5.
- [Release notes](https://github.com/ydb-platform/ydb-go-sdk/releases)
- [Changelog](https://github.com/ydb-platform/ydb-go-sdk/blob/master/CHANGELOG.md)
- [Commits](https://github.com/ydb-platform/ydb-go-sdk/compare/v3.134.2...v3.139.5)

---
updated-dependencies:
- dependency-name: github.com/ydb-platform/ydb-go-sdk/v3
  dependency-version: 3.139.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-06-02 17:22:03 -07:00
dependabot[bot] 348de64f13 build(deps): bump github.com/aws/aws-sdk-go-v2/config from 1.32.14 to 1.32.21 (#9798)
build(deps): bump github.com/aws/aws-sdk-go-v2/config

Bumps [github.com/aws/aws-sdk-go-v2/config](https://github.com/aws/aws-sdk-go-v2) from 1.32.14 to 1.32.21.
- [Release notes](https://github.com/aws/aws-sdk-go-v2/releases)
- [Commits](https://github.com/aws/aws-sdk-go-v2/compare/config/v1.32.14...config/v1.32.21)

---
updated-dependencies:
- dependency-name: github.com/aws/aws-sdk-go-v2/config
  dependency-version: 1.32.21
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 17:14:58 -07:00
dependabot[bot] 30e0116611 build(deps): bump go.etcd.io/etcd/client/pkg/v3 from 3.6.11 to 3.6.12 (#9799)
Bumps [go.etcd.io/etcd/client/pkg/v3](https://github.com/etcd-io/etcd) from 3.6.11 to 3.6.12.
- [Release notes](https://github.com/etcd-io/etcd/releases)
- [Commits](https://github.com/etcd-io/etcd/compare/v3.6.11...v3.6.12)

---
updated-dependencies:
- dependency-name: go.etcd.io/etcd/client/pkg/v3
  dependency-version: 3.6.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 17:14:50 -07:00
dependabot[bot] d6db545b4c build(deps): bump github.com/pierrec/lz4/v4 from 4.1.26 to 4.1.27 (#9800)
Bumps [github.com/pierrec/lz4/v4](https://github.com/pierrec/lz4) from 4.1.26 to 4.1.27.
- [Release notes](https://github.com/pierrec/lz4/releases)
- [Commits](https://github.com/pierrec/lz4/compare/v4.1.26...v4.1.27)

---
updated-dependencies:
- dependency-name: github.com/pierrec/lz4/v4
  dependency-version: 4.1.27
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 17:14:28 -07:00
dependabot[bot] cb67542d01 build(deps): bump docker/setup-qemu-action from 4.0.0 to 4.1.0 (#9802)
Bumps [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) from 4.0.0 to 4.1.0.
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v4...v4.1.0)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-version: 4.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 17:13:52 -07:00
dependabot[bot] 6908445c5d build(deps): bump actions/checkout from 5 to 6 (#9803)
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-02 16:26:55 -07:00
Chris Lu 160e68dd65 fix(s3api): keep ListBucket resource ARN at bucket level (#9792)
* fix(s3api): keep ListBucket resource ARN at bucket level

ListObjects with ?prefix= was denied for IAM users granted s3:ListBucket
on the bucket ARN. authRequestWithAuthType promotes the prefix into object
so the legacy CanDo path can honor prefix-scoped Action strings, and that
promoted object leaked into the policy resource ARN, producing
arn:aws:s3:::bucket/<prefix> which never matches a bucket-level statement.

Keep the resource bucket-level for List in the bucket-policy and
IAM-attached-policy evaluators; prefix scoping stays in the s3:prefix
Condition. The CanDo path is untouched.

* fix(s3api): resolve List action at bucket level when prefix is promoted

The IAM evaluator built a bucket-level resource ARN but still passed the
prefix-promoted object to ResolveS3Action, so listing with a prefix made
hasObject true and misresolved ListBucketVersions/ListBucketMultipartUploads
to ListBucket. Resolve the action against the same zeroed object, and trim
the resource-ARN comments.
2026-06-02 14:45:45 -07:00
Chris Lu 8e4022d5c7 fix(s3api): authorize DeleteObjects per key so object-scoped policies match (#9793)
Bulk DeleteObjects carries the keys in the request body, so the route Auth
middleware ran a single bucket-level check with object="", building the
resource ARN as arn:aws:s3:::<bucket>. That never matches an s3:DeleteObject
policy scoped to <bucket>/*, so the entire batch was denied even though the
single-key DELETE worked with the same credentials.

Defer authorization to the handler and check each key via AuthorizeBatchDeleteKey,
mirroring AuthorizeCopySource: a synthetic DELETE /<bucket>/<key> request resolves
s3:DeleteObject (or s3:DeleteObjectVersion when a versionId is given) against the
object ARN. Denied keys come back as per-key errors while authorized keys still
delete, matching AWS semantics.
2026-06-02 14:45:05 -07:00
Chris Lu b5a952bcb1 fix(mount): don't strand a directory cached-but-empty when an eviction races a rebuild (#9791)
* fix(mount): don't strand a directory cached-but-empty when an off-loop wipe races a rebuild

Idle eviction, kernel Forget, and the copy-range fallback cleared a
directory's cached entries directly, off the metaCache apply loop, after
resetting the cached flag in inodeToPath as a separate step. A concurrent
rebuild could publish a fresh listing (markCachedFn) in between, so the late
DeleteFolderChildren left the directory flagged cached over an empty store.
lookupEntry then returns an authoritative ENOENT and ReadDir returns nothing,
so every file in the directory disappears from the mount although it is still
present on the filer.

Route those wipes through a new apply-loop step that resets the flag and wipes
the store together, serialized with a build's markCachedFn, and skips a
directory while it is building.

* fix(mount): route the meta-event retry cleanup through the apply-loop purge

The subscription-retry callback wiped the mount root's cached children
directly off the apply loop and reset the cache flags as a separate step — the
same pattern that can leave a concurrently-rebuilding root cached-but-empty.
Invalidate all flags (safe on its own, it never deletes entries) then purge the
root's children through the apply loop.
2026-06-02 14:43:46 -07:00
ahalaun 3ce4e0dbdf fix(s3/lifecycle): report success to admin via JobCompleted (#9787) 2026-06-02 11:28:56 -07:00
ahalaun bcd2c958e1 fix(admin): make scheduler pruning lane-aware (#9790) 2026-06-02 11:17:52 -07:00
e3e02d3364 [CheckDisk]: implement disk health detection (#9560)
* [CheckDisk][GRPC]: implement MVP for disk health detection, added timeout for new grpc connections

* fix(volume): build disk health check on every platform

setDiskStatus only existed behind the statfs build tag, so disk.go failed
to compile on windows, openbsd, solaris, netbsd and plan9. Move the timeout
wrapper and failure tracking into the shared disk.go and have each platform's
fillInDiskStatus return an error, so every platform gets the same protection
from a stuck filesystem.

Also restore the uint64(fs.Bavail) cast: Bavail is int64 on freebsd, so the
unguarded multiply broke the freebsd build.

* fix(volume): keep one outstanding statfs probe per disk

A stuck statfs used to leave isChecking cleared by the timeout path, so the
next check spawned another goroutine while the previous one was still blocked
in the syscall, leaking one goroutine per minute on a hung disk. Clear the
flag only when statfs returns and treat an overlapping check as a failure, so
a hung filesystem keeps a single outstanding probe and still gets reported.

* fix(volume): assume disk available until the first health check

isDiskAvailable defaulted to false, and CollectHeartbeat skips locations that
are not available. A freshly started volume server would therefore omit every
volume from its first heartbeats until the async CheckDiskSpace ran, so the
master could briefly treat all of them as missing.

* fix(volume): label the disk error metric by data directory

The new gauge tagged the series with IdxDirectory while every neighbouring
resource gauge uses Directory, so the error series would not line up with them
in dashboards. Also log the underlying error instead of a generic message.

* test(volume): cover disk health success and repeated-failure paths

* fix(volume): make a healthy disk the zero-value default

Track the disk as isDiskUnavailable instead of isDiskAvailable so the safe
state is the zero value, matching isDiskSpaceLow. CollectHeartbeat only skips a
location once a check has actively marked it unavailable, so any DiskLocation
built without running CheckDiskSpace (tests, future call sites) still reports
its volumes instead of silently dropping them.

* feat(disk): detect degraded disks using IO latency probes

* feat(stats): introduce configurable disk I/O health probe with EWMA-based latency detection

* feat(disk): replace EWMA with sliding window algorithm for disk health detection and added user-friendly options

* feat(disk): improve disk health probing and recovery

* feat(volume): configure disk health checks via volume.toml

* fix(volume): Remove disk IO probe CLI options

---------

Co-authored-by: ptukha <ptukha@tochka.com>
Co-authored-by: Chris Lu <chris.lu@gmail.com>
2026-06-02 09:02:05 -07:00
7y-9 38a47d1dd3 fix(http): check delete request errors before auth (#9784)
Explain:

- problem: Delete and DeleteProxied could panic on malformed URLs when a JWT was provided.

- root cause: maybeAddAuth was called before checking the error returned by http.NewRequest, so req could be nil.

- fix: return the request construction error before adding the Authorization header.

- validation: go test ./weed/util/http -run 'TestDelete(ReturnsInvalidRequestErrorBeforeAddingAuth|ProxiedReturnsInvalidRequestErrorBeforeAddingAuth)' -count=1; git diff --check
2026-06-02 00:41:17 -07:00
128 changed files with 4663 additions and 579 deletions

No files matched your search

+1 -1
View File
@@ -111,7 +111,7 @@ jobs:
org.opencontainers.image.vendor=Chris Lu
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v4.1.0
- name: Create BuildKit config
run: |
@@ -126,7 +126,7 @@ jobs:
echo "seaweedfs_ref=$seaweed" >> "$GITHUB_OUTPUT"
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v4.1.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
+1 -1
View File
@@ -207,7 +207,7 @@ jobs:
org.opencontainers.image.vendor=Chris Lu
- name: Set up QEMU
if: matrix.platform != 'amd64'
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v4.1.0
- name: Create BuildKit config
run: |
cat > /tmp/buildkitd.toml <<EOF
@@ -43,7 +43,7 @@ jobs:
org.opencontainers.image.vendor=Chris Lu
-
name: Set up QEMU
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v4.1.0
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
@@ -220,7 +220,7 @@ jobs:
- name: Set up QEMU
if: (github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant) && contains(matrix.platforms, 'arm')
uses: docker/setup-qemu-action@v4
uses: docker/setup-qemu-action@v4.1.0
- name: Create BuildKit config
if: github.event_name != 'workflow_dispatch' || github.event.inputs.variant == 'all' || github.event.inputs.variant == matrix.variant
@@ -82,7 +82,7 @@ jobs:
echo "seaweedfs_ref=$seaweed" >> "$GITHUB_OUTPUT"
- name: Set up QEMU
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v1
uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v1
+2 -2
View File
@@ -45,7 +45,7 @@ jobs:
- name: Fix S3 tests bucket creation conflicts
run: |
python3 test/s3/fix_s3_tests_bucket_conflicts.py
python3 test/s3/compatibility/fix_s3_tests_bucket_conflicts.py
env:
S3_TESTS_PATH: s3-tests
@@ -388,7 +388,7 @@ jobs:
- name: Fix S3 tests bucket creation conflicts
run: |
python3 test/s3/fix_s3_tests_bucket_conflicts.py
python3 test/s3/compatibility/fix_s3_tests_bucket_conflicts.py
env:
S3_TESTS_PATH: s3-tests
+4 -4
View File
@@ -16,10 +16,10 @@ jobs:
name: fmt, validate, plan-level tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Set up OpenTofu
uses: opentofu/setup-opentofu@v1
uses: opentofu/setup-opentofu@v2
with:
tofu_version: 1.12.1
@@ -56,7 +56,7 @@ jobs:
name: local cluster smoke test (real weed)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
@@ -67,7 +67,7 @@ jobs:
run: go build -o "$RUNNER_TEMP/weed" ./weed
- name: Set up OpenTofu
uses: opentofu/setup-opentofu@v1
uses: opentofu/setup-opentofu@v2
with:
tofu_version: 1.12.1
+23 -24
View File
@@ -102,7 +102,7 @@ require (
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
google.golang.org/api v0.278.0
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
google.golang.org/grpc v1.80.0
google.golang.org/grpc v1.81.1
google.golang.org/protobuf v1.36.11
gopkg.in/inf.v0 v0.9.1 // indirect
modernc.org/b v1.0.0 // indirect
@@ -122,9 +122,9 @@ require (
github.com/apple/foundationdb/bindings/go v0.0.0-20250911184653-27f7192f47c3
github.com/arangodb/go-driver v1.6.9
github.com/armon/go-metrics v0.4.1
github.com/aws/aws-sdk-go-v2 v1.41.7
github.com/aws/aws-sdk-go-v2/config v1.32.14
github.com/aws/aws-sdk-go-v2/credentials v1.19.14
github.com/aws/aws-sdk-go-v2 v1.41.10
github.com/aws/aws-sdk-go-v2/config v1.32.21
github.com/aws/aws-sdk-go-v2/credentials v1.19.20
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
github.com/cognusion/imaging v1.0.3
github.com/fluent/fluent-logger-golang v1.10.1
@@ -153,8 +153,8 @@ require (
github.com/tikv/client-go/v2 v2.0.7
github.com/xeipuuv/gojsonschema v1.2.0
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1
github.com/ydb-platform/ydb-go-sdk/v3 v3.134.2
go.etcd.io/etcd/client/pkg/v3 v3.6.11
github.com/ydb-platform/ydb-go-sdk/v3 v3.139.5
go.etcd.io/etcd/client/pkg/v3 v3.6.12
go.uber.org/atomic v1.11.0
golang.org/x/sync v0.20.0
golang.org/x/tools/godoc v0.1.0-deprecated
@@ -179,7 +179,7 @@ require (
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/apache/arrow-go/v18 v18.5.2-0.20260220015023-a886a5722b87 // indirect
github.com/apache/thrift v0.23.0 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/bazelbuild/rules_go v0.46.0 // indirect
github.com/biogo/store v0.0.0-20201120204734-aad293a2328f // indirect
@@ -321,22 +321,21 @@ require (
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
github.com/arangodb/go-velocypack v0.0.0-20200318135517-5af53c29c67e // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 // indirect
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
github.com/aws/aws-sdk-go-v2/service/sns v1.39.7 // indirect
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.17 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10
github.com/aws/smithy-go v1.25.1
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0
github.com/aws/smithy-go v1.26.0
github.com/boltdb/bolt v1.3.1 // indirect
github.com/bradenaw/juniper v0.15.3 // indirect
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
@@ -347,7 +346,7 @@ require (
github.com/cloudinary/cloudinary-go/v2 v2.15.0 // indirect
github.com/cloudsoda/go-smb2 v0.0.0-20250228001242-d4c70e6251cc // indirect
github.com/cloudsoda/sddl v0.0.0-20250224235906-926454e91efc // indirect
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect
github.com/colinmarc/hdfs/v2 v2.4.0 // indirect
github.com/creasty/defaults v1.8.0 // indirect
github.com/cronokirby/saferith v0.33.1-0.20250226174546-1f11f94ce488 // indirect
@@ -359,8 +358,8 @@ require (
github.com/elastic/gosigar v0.14.3 // indirect
github.com/emersion/go-message v0.18.2 // indirect
github.com/emersion/go-vcard v0.0.0-20241024213814-c9703dde27ff // indirect
github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect
github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect
github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect
github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/flynn/noise v1.1.0 // indirect
@@ -438,7 +437,7 @@ require (
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pengsrc/go-shared v0.2.1-0.20190131101655-1999055a4a14 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/pierrec/lz4/v4 v4.1.26
github.com/pierrec/lz4/v4 v4.1.27
github.com/pingcap/errors v0.11.5-0.20211224045212-9687c2b0f87c // indirect
github.com/pingcap/failpoint v0.0.0-20220801062533-2eaa32854a6c // indirect
github.com/pingcap/kvproto v0.0.0-20230403051650-e166ae588106 // indirect
@@ -475,7 +474,7 @@ require (
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/yandex-cloud/go-genproto v0.0.0-20211115083454-9ca41db5ed9e // indirect
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260311095541-ebbf792c1180 // indirect
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260428144813-1c07baab7f7b // indirect
github.com/ydb-platform/ydb-go-yc v0.12.1 // indirect
github.com/ydb-platform/ydb-go-yc-metadata v0.6.1 // indirect
github.com/yunify/qingstor-sdk-go/v3 v3.2.0 // indirect
@@ -485,7 +484,7 @@ require (
go.etcd.io/bbolt v1.4.3 // indirect
go.etcd.io/etcd/api/v3 v3.6.10 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
+46 -48
View File
@@ -715,50 +715,48 @@ github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
github.com/aws/aws-sdk-go-v2 v1.41.10 h1:i/Ezw+xWTo/EtO/lEq6xBYu9RXpRb3QPN5UlTsJg8Ck=
github.com/aws/aws-sdk-go-v2 v1.41.10/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
github.com/aws/aws-sdk-go-v2/config v1.32.14/go.mod h1:U4/V0uKxh0Tl5sxmCBZ3AecYny4UNlVmObYjKuuaiOo=
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8THYELoX6gVcUvgl6fI=
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21/go.mod h1:YWNWJQNjKigKY1RHVJCuupeWDrrHjRqHm0N9rdrWzYI=
github.com/aws/aws-sdk-go-v2/config v1.32.21 h1:1i1v5jWn6iNPl7zkH4VwIXQOb+OMqMRFNjdHQeZbFVo=
github.com/aws/aws-sdk-go-v2/config v1.32.21/go.mod h1:7NXDJjk0e4QOMv3Y3ppwALx3ifdSQHzCACFtRX5J1hI=
github.com/aws/aws-sdk-go-v2/credentials v1.19.20 h1:nIGz0+cQKwijxSsWNpggvPxjxFMtrAHNj16RYzGbu2Q=
github.com/aws/aws-sdk-go-v2/credentials v1.19.20/go.mod h1:/UQHYia3DSeilGdchXJDEVzJws15XuZSdnTlwbTBg0Q=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26 h1:a1VPHz7eG7mVNHWHXUcCyC8rQDBEr4k+o4HJYbSoYZ0=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.26/go.mod h1:9G8LPblMwaodeQdS+IfDBgPqABDctJLpyZ/M6jflE6s=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13 h1:uMC4oL6G3MNhodo358QEqSDjrgvzV3TUQ58nyQSGq2E=
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.13/go.mod h1:Cer86AE2686DvVUe57LPve3jUBmbujuaonSX8pNzGgw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 h1:qYQ4pzQ2Oz6WpQ8T3HvGHnZydA72MnLuFK9tJwmrbHw=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6/go.mod h1:O3h0IK87yXci+kg6flUKzJnWeziQUKciKrLjcatSNcY=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26 h1:dx1qc6V0exl5SK5/kwSc2IdOKCxLHoNbl/zXuYRwopw=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.26/go.mod h1:iDMGb+drKqPTqRjv1kWc5meMYzT6HsvPXxJV/Axq1t0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26 h1:ZjsIjuahUd/OxnxgfeK6OZqrReRNru1BcPfFD95IoN0=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.26/go.mod h1:57VbRA0K0Xxx5XUUTUrVxZ/gm4u8Bk3LBflfufwHtKQ=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27 h1:i49S7g2smFWmlconi97Nn8dxb7jSQ0TeOFD20NX3M+o=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.27/go.mod h1:qiLes3uVQAK+cpb837HUEhypYKGBz2ZCDcDl5BYQtpM=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26 h1:oIRaBVJ2CxT7T61l3JkBCW/rnyh2TFZIRL71MvJTKRI=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.26/go.mod h1:1gCTZPMlqAUSFoFbkl35hKtTpE96WFl7ORvDXmSLpRc=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9 h1:QKZH0S178gCmFEgst8hN0mCX1KxLgHBKKY/CLqwP8lg=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.9/go.mod h1:7yuQJoT+OoH8aqIxw9vwF+8KpvLZ8AWmvmUWHsGQZvI=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2 h1:qwU4CNor4G2gRW3Na24FWOCZSEvr967IAV3D+MXxdE0=
github.com/aws/aws-sdk-go-v2/service/signin v1.1.2/go.mod h1:vwIj2P3URYf7ZtOQkO2iVbAaR8qFhqMv05w3aPPA5XA=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.7 h1:fovS7qGMT+BBSuifkySdVaMWxXTyaYT6qaBx/1y6Ij4=
github.com/aws/aws-sdk-go-v2/service/sns v1.39.7/go.mod h1:gFahrattA8ulEtiS4XL/fQiQ77l+Urc52Y96/r1e6ks=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.17 h1:ZNMxVFPayuHe14u/vn+BwLi3wxQvxcNTw8WdPv2gqBc=
github.com/aws/aws-sdk-go-v2/service/sqs v1.42.17/go.mod h1:ZxqweFQ2w6NNznWMUvWV9AvkAfM6J8F/MC250Mb4n1I=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 h1:lFd1+ZSEYJZYvv9d6kXzhkZu07si3f+GQ1AaYwa2LUM=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15/go.mod h1:WSvS1NLr7JaPunCXqpJnWk1Bjo7IxzZXrZi1QQCkuqM=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 h1:dzztQ1YmfPrxdrOiuZRMF6fuOwWlWpD2StNLTceKpys=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19/go.mod h1:YO8TrYtFdl5w/4vmjL8zaBSsiNp3w0L1FfKVKenZT7w=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUdErbMnAFFp12Lm/U=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0 h1:cMDUWhi7vlmGFj6rldHofjnAQhLLBWwRvNRbtEoyZo4=
github.com/aws/aws-sdk-go-v2/service/sso v1.31.0/go.mod h1:VfGCm6HLUGwcouY6zjQJd81PoFsb8sfSmKd5QCg9XXc=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3 h1:/pKy3mNES+ppFHf3g/XmI95+f3vdeXnkWYObByoYGAg=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.3/go.mod h1:0z2rhlVAjsYeBzV8fdT4jR23Nq+fYhoJNSJN+4SBlqM=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0 h1:HN43uYvF8D2NtaPTeE4L3HMvXgd+RtqEqrea4uUztkM=
github.com/aws/aws-sdk-go-v2/service/sts v1.43.0/go.mod h1:qzhDlfw1BRYyoNofevemNzrlRpUXa0BJamWx7klrR8w=
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bazelbuild/rules_go v0.46.0 h1:CTefzjN/D3Cdn3rkrM6qMWuQj59OBcuOjyIp3m4hZ7s=
@@ -854,8 +852,8 @@ github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20220314180256-7f1daf1720fc/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cncf/xds/go v0.0.0-20230105202645-06c439db220b/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cncf/xds/go v0.0.0-20230310173818-32f1caf87195/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/cockroachdb/apd/v3 v3.2.1 h1:U+8j7t0axsIgvQUqthuNm82HIrYXodOV2iWLWtEaIwg=
github.com/cockroachdb/apd/v3 v3.2.1/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc=
github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I=
@@ -1000,16 +998,16 @@ github.com/envoyproxy/go-control-plane v0.10.3/go.mod h1:fJJn/j26vwOu972OllsvAgJ
github.com/envoyproxy/go-control-plane v0.11.0/go.mod h1:VnHyVMpzcLvCFt9yUz1UnCwHLhwx1WguiVDV7pTG/tI=
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=
github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/envoyproxy/protoc-gen-validate v0.6.7/go.mod h1:dyJXwwfPK2VSqiB9Klm1J6romD608Ba7Hij42vrOBCo=
github.com/envoyproxy/protoc-gen-validate v0.9.1/go.mod h1:OKNgG7TCp5pF4d6XftA0++PMirau2/yoOwVac3AbF2w=
github.com/envoyproxy/protoc-gen-validate v0.10.0/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss=
github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a h1:yDWHCSQ40h88yih2JAcL6Ls/kVkSE8GFACTGVnMPruw=
github.com/facebookgo/clock v0.0.0-20150410010913-600d898af40a/go.mod h1:7Ga40egUymuWXxAe151lTNnCv97MddSOVsjpPPkityA=
github.com/facebookgo/ensure v0.0.0-20200202191622-63f1cf65ac4c h1:8ISkoahWXwZR41ois5lSJBSVw4D0OV19Ht/JSTzvSv0=
@@ -1691,8 +1689,8 @@ github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2
github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI=
github.com/phpdave11/gofpdi v1.0.13/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI=
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pierrec/lz4/v4 v4.1.27 h1:+PhzhWDrjRj89TH2sw43nE3+4+W8lSxIuQadEHZyjUk=
github.com/pierrec/lz4/v4 v4.1.27/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
github.com/pierrre/compare v1.0.2 h1:k4IUsHgh+dbcAOIWCfxVa/7G6STjADH2qmhomv+1quc=
github.com/pierrre/compare v1.0.2/go.mod h1:8UvyRHH+9HS8Pczdd2z5x/wvv67krDwVxoOndaIIDVU=
github.com/pierrre/geohash v1.0.0 h1:f/zfjdV4rVofTCz1FhP07T+EMQAvcMM2ioGZVt+zqjI=
@@ -2058,14 +2056,14 @@ github.com/yandex-cloud/go-genproto v0.0.0-20211115083454-9ca41db5ed9e h1:9LPdmD
github.com/yandex-cloud/go-genproto v0.0.0-20211115083454-9ca41db5ed9e/go.mod h1:HEUYX/p8966tMUHHT+TsS0hF/Ca/NYwqprC5WXSDMfE=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20221215182650-986f9d10542f/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20230528143953-42c825ace222/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260311095541-ebbf792c1180 h1:avIdi8eGXjKbn1WLokNR1Ofnz1k8t7tJ88YQLD/iCi8=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260311095541-ebbf792c1180/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260428144813-1c07baab7f7b h1:xeiobG1riqe6dTMZuTcOvwOY0BbFidSk3gRLyVeLfJA=
github.com/ydb-platform/ydb-go-genproto v0.0.0-20260428144813-1c07baab7f7b/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I=
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1 h1:XaRxeVrOyl3y6v9CiYMWaFdZ6zevvYe+TRxOR8ifa2s=
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.1/go.mod h1:9YzkhlIymWaJGX6KMU3vh5sOf3UKbCXkG/ZdjaI3zNM=
github.com/ydb-platform/ydb-go-sdk/v3 v3.44.0/go.mod h1:oSLwnuilwIpaF5bJJMAofnGgzPJusoI3zWMNb8I+GnM=
github.com/ydb-platform/ydb-go-sdk/v3 v3.47.3/go.mod h1:bWnOIcUHd7+Sl7DN+yhyY1H/I61z53GczvwJgXMgvj0=
github.com/ydb-platform/ydb-go-sdk/v3 v3.134.2 h1:Bzra5hUQIWrxknQ0oV6HE5q/eZU1VhHMKSZ/XWpqMgM=
github.com/ydb-platform/ydb-go-sdk/v3 v3.134.2/go.mod h1:VYUUkRJkKuQPkIpgtZJj6+58Fa2g8ccAqdmaaK6HP5k=
github.com/ydb-platform/ydb-go-sdk/v3 v3.139.5 h1:mTih9wy1RbI4PplGlFn/CMnkgxm1HzD/nKSdnNMy4pE=
github.com/ydb-platform/ydb-go-sdk/v3 v3.139.5/go.mod h1:b9NEO6mgaiqsnOMkS003uS82XsKh6GL+ZTFfPqXWz+c=
github.com/ydb-platform/ydb-go-yc v0.12.1 h1:qw3Fa+T81+Kpu5Io2vYHJOwcrYrVjgJlT6t/0dOXJrA=
github.com/ydb-platform/ydb-go-yc v0.12.1/go.mod h1:t/ZA4ECdgPWjAb4jyDe8AzQZB5dhpGbi3iCahFaNwBY=
github.com/ydb-platform/ydb-go-yc-metadata v0.6.1 h1:9E5q8Nsy2RiJMZDNVy0A3KUrIMBPakJ2VgloeWbcI84=
@@ -2105,8 +2103,8 @@ go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
go.etcd.io/bbolt v1.4.3/go.mod h1:tKQlpPaYCVFctUIgFKFnAlvbmB3tpy1vkTnDWohtc0E=
go.etcd.io/etcd/api/v3 v3.6.10 h1:jlwjtELjA8yi2VWpOFH+0w0lGr3K6mVDyn0RDB9aaAY=
go.etcd.io/etcd/api/v3 v3.6.10/go.mod h1:pdV4VeFmvhdNjB4LWRkC8ReLyRBAxUOze3GarMhE2sk=
go.etcd.io/etcd/client/pkg/v3 v3.6.11 h1:e41mp315Yn3QMGPmEzCyLsMINgJXTY/dX8kM++1csxU=
go.etcd.io/etcd/client/pkg/v3 v3.6.11/go.mod h1:DysuMe/inqRyC/1tjRR6hReH/VV9Lufs27YKSKBWWJg=
go.etcd.io/etcd/client/pkg/v3 v3.6.12 h1:36zzB+pQOdHbhN+kH2iJz/K8bJn0ZLtLfPPO7jozTDo=
go.etcd.io/etcd/client/pkg/v3 v3.6.12/go.mod h1:hh2+ZXtfLzs3o6mn92ntgNPBrTJJOvXqICM5g3L3DMY=
go.etcd.io/etcd/client/v3 v3.6.10 h1:J598zJ+C/ZPvImypmq5waj84+bovePrlZERHklf34y0=
go.etcd.io/etcd/client/v3 v3.6.10/go.mod h1:iHhUDUcEwaKs1YFq3MgmI9U4zhTVasp/vgdVbFf1RS8=
go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5tU=
@@ -2122,8 +2120,8 @@ go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=
go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.60.0 h1:0tY123n7CdWMem7MOVdKOt0YfshufLCwfE5Bob+hQuM=
@@ -2886,8 +2884,8 @@ google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsA
google.golang.org/grpc v1.52.0/go.mod h1:pu6fVzoFb+NBYNAvQL08ic+lvB2IojljRYuun5vorUY=
google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw=
google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8=
google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=
google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw=
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6 h1:ExN12ndbJ608cboPYflpTny6mXSzPrDLh0iTaVrRrds=
google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8=
@@ -272,6 +272,9 @@ spec:
{{- $authMethods := .Values.allInOne.sftp.authMethods | default .Values.sftp.authMethods }}
{{- if $authMethods }}
-sftp.authMethods={{ $authMethods }} \
{{- if contains "certificate" $authMethods }}
-sftp.trustedUserCAKeysFile=/etc/sw/sftp_ca/ca_user.pub \
{{- end }}
{{- end }}
{{- $maxAuthTries := .Values.allInOne.sftp.maxAuthTries | default .Values.sftp.maxAuthTries }}
{{- if $maxAuthTries }}
@@ -319,6 +322,12 @@ spec:
name: config-users
readOnly: true
{{- end }}
{{- $aioAuthMethods := .Values.allInOne.sftp.authMethods | default .Values.sftp.authMethods }}
{{- if and $aioAuthMethods (contains "certificate" $aioAuthMethods) }}
- mountPath: /etc/sw/sftp_ca
name: config-sftp-ca
readOnly: true
{{- end }}
{{- end }}
{{- if .Values.filer.notificationConfig }}
- name: notification-config
@@ -454,6 +463,18 @@ spec:
defaultMode: 420
secretName: {{ default (printf "%s-sftp-secret" (include "seaweedfs.fullname" .)) (or .Values.allInOne.sftp.existingConfigSecret .Values.sftp.existingConfigSecret) }}
{{- end }}
{{- $aioAuthMethodsVol := .Values.allInOne.sftp.authMethods | default .Values.sftp.authMethods }}
{{- if and $aioAuthMethodsVol (contains "certificate" $aioAuthMethodsVol) }}
{{- $aioCASecret := or .Values.allInOne.sftp.existingCAKeysSecret .Values.sftp.existingCAKeysSecret }}
{{- $aioCAKeys := or .Values.allInOne.sftp.trustedUserCAKeys .Values.sftp.trustedUserCAKeys }}
{{- if and (not $aioCASecret) (not $aioCAKeys) }}
{{- fail "allInOne.sftp.authMethods includes \"certificate\" but neither trustedUserCAKeys nor existingCAKeysSecret is set" }}
{{- end }}
- name: config-sftp-ca
secret:
defaultMode: 420
secretName: {{ default (printf "%s-sftp-ca-secret" (include "seaweedfs.fullname" .)) $aioCASecret }}
{{- end }}
{{- end }}
{{- if .Values.filer.notificationConfig }}
- name: notification-config
@@ -0,0 +1,40 @@
{{- include "seaweedfs.compat" . -}}
{{- /*
Render a chart-managed Secret carrying the SSH user CA public key(s) for
certificate-based SFTP authentication, but only when:
- SFTP (standalone or all-in-one) is enabled,
- "certificate" is in the relevant authMethods list,
- the user provided inline CA keys via sftp.trustedUserCAKeys, and
- no existingCAKeysSecret is set (which would supersede this Secret).
*/}}
{{- $sftpEnabled := or .Values.sftp.enabled (and .Values.allInOne.enabled .Values.allInOne.sftp.enabled) -}}
{{- $authMethods := .Values.sftp.authMethods -}}
{{- if and .Values.allInOne.enabled .Values.allInOne.sftp.authMethods -}}
{{- $authMethods = .Values.allInOne.sftp.authMethods -}}
{{- end -}}
{{- $certInMethods := and $authMethods (contains "certificate" $authMethods) -}}
{{- $inlineCAKeys := .Values.sftp.trustedUserCAKeys -}}
{{- if and .Values.allInOne.enabled .Values.allInOne.sftp.trustedUserCAKeys -}}
{{- $inlineCAKeys = .Values.allInOne.sftp.trustedUserCAKeys -}}
{{- end -}}
{{- $existingSecret := .Values.sftp.existingCAKeysSecret -}}
{{- if and .Values.allInOne.enabled .Values.allInOne.sftp.existingCAKeysSecret -}}
{{- $existingSecret = .Values.allInOne.sftp.existingCAKeysSecret -}}
{{- end -}}
{{- if and $sftpEnabled $certInMethods $inlineCAKeys (not $existingSecret) }}
apiVersion: v1
kind: Secret
type: Opaque
metadata:
name: {{ include "seaweedfs.fullname" . }}-sftp-ca-secret
namespace: {{ .Release.Namespace }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: sftp
stringData:
ca_user.pub: |
{{ $inlineCAKeys | indent 4 }}
{{- end }}
@@ -135,6 +135,9 @@ spec:
{{- end }}
{{- if .Values.sftp.authMethods }}
-authMethods={{ .Values.sftp.authMethods }} \
{{- if contains "certificate" .Values.sftp.authMethods }}
-trustedUserCAKeysFile=/etc/sw/sftp_ca/ca_user.pub \
{{- end }}
{{- end }}
{{- if .Values.sftp.maxAuthTries }}
-maxAuthTries={{ .Values.sftp.maxAuthTries }} \
@@ -176,6 +179,11 @@ spec:
- mountPath: /etc/sw/ssh
name: config-ssh
readOnly: true
{{- if and .Values.sftp.authMethods (contains "certificate" .Values.sftp.authMethods) }}
- mountPath: /etc/sw/sftp_ca
name: config-sftp-ca
readOnly: true
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
readOnly: true
@@ -256,6 +264,19 @@ spec:
{{- else }}
secretName: {{ include "seaweedfs.fullname" . }}-sftp-ssh-secret
{{- end }}
{{- if and .Values.sftp.authMethods (contains "certificate" .Values.sftp.authMethods) }}
{{- if and (not .Values.sftp.existingCAKeysSecret) (not .Values.sftp.trustedUserCAKeys) }}
{{- fail "sftp.authMethods includes \"certificate\" but neither sftp.trustedUserCAKeys nor sftp.existingCAKeysSecret is set" }}
{{- end }}
- name: config-sftp-ca
secret:
defaultMode: 420
{{- if .Values.sftp.existingCAKeysSecret }}
secretName: {{ .Values.sftp.existingCAKeysSecret }}
{{- else }}
secretName: {{ include "seaweedfs.fullname" . }}-sftp-ca-secret
{{- end }}
{{- end }}
{{- if eq .Values.sftp.logs.type "hostPath" }}
- name: logs
hostPath:
+17 -1
View File
@@ -1138,7 +1138,7 @@ sftp:
# SSH server configuration
sshPrivateKey: "/etc/sw/seaweedfs_sftp_ssh_private_key" # Path to the SSH private key file for host authentication
hostKeysFolder: "/etc/sw/ssh" # path to folder containing SSH private key files for host authentication
authMethods: "password,publickey" # Comma-separated list of allowed auth methods: password, publickey, keyboard-interactive
authMethods: "password,publickey" # Comma-separated list of allowed auth methods: password, publickey, certificate
maxAuthTries: 6 # Maximum number of authentication attempts per connection
bannerMessage: "SeaweedFS SFTP Server" # Message displayed before authentication
loginGraceTime: "2m" # Timeout for authentication
@@ -1155,6 +1155,18 @@ sftp:
# Set to the name of an existing kubernetes Secret with the list of ssh private keys for sftp
existingSshConfigSecret: null
# SSH user-certificate authentication (CA-signed user certs). Mirrors
# OpenSSH `TrustedUserCAKeys` and MinIO `--sftp=trusted-user-ca-key`.
# Add "certificate" to `authMethods` to activate; when active, plain
# public keys are rejected on the public-key channel.
#
# Inline CA public keys in OpenSSH authorized_keys format (one per
# line). Ignored when `existingCAKeysSecret` is set.
trustedUserCAKeys: ""
# Set to the name of an existing kubernetes Secret carrying the CA
# public keys under data key `ca_user.pub`.
existingCAKeysSecret: null
# Additional resources
sidecars: []
initContainers: ""
@@ -1545,6 +1557,10 @@ allInOne:
existingConfigSecret: null
# Set to the name of an existing kubernetes Secret with the SSH keys
existingSshConfigSecret: null
# SSH user-certificate authentication. See sftp.trustedUserCAKeys above.
# (null on either field inherits from the top-level sftp.* setting.)
trustedUserCAKeys: null
existingCAKeysSecret: null
# Service settings
service:
+6
View File
@@ -545,6 +545,12 @@ async fn run(
whitelist.extend(sec.guard_white_list.iter().cloned());
let mut guard = state_reload.guard.write().unwrap();
guard.update_whitelist(&whitelist);
guard.update_signing_keys(
SigningKey(sec.jwt_signing_key),
sec.jwt_signing_expires,
SigningKey(sec.jwt_read_signing_key),
sec.jwt_read_signing_expires,
);
}
// Trigger heartbeat to report new volumes
+57
View File
@@ -172,6 +172,26 @@ impl Guard {
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
}
/// Refresh the JWT signing keys and their expirations in place so operators
/// can rotate keys via SIGHUP without restarting the process. Mirrors Go's
/// `Guard::UpdateSigningKeys`: it swaps the fields and recomputes
/// `is_write_active`.
pub fn update_signing_keys(
&mut self,
signing_key: SigningKey,
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
) {
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
self.read_expires_after_sec = read_expires_after_sec;
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
}
/// Check if a remote IP is in the whitelist.
/// Returns true if write security is inactive (no whitelist and no signing key),
/// if the whitelist is empty, or if the IP matches.
@@ -463,6 +483,43 @@ mod tests {
assert!(matches!(err, Err(JwtError::FileIdMismatch { .. })));
}
#[test]
fn test_update_signing_keys_rotates() {
let mut guard = Guard::new(
&[],
SigningKey::from_string("old-write"),
10,
SigningKey::from_string("old-read"),
60,
);
guard.update_signing_keys(
SigningKey::from_string("new-write"),
11,
SigningKey::from_string("new-read"),
61,
);
let token = gen_jwt(&guard.signing_key, 60, "3,01637037d6").unwrap();
// Validates with the rotated key, not the old one.
assert!(decode_jwt(&guard.signing_key, &token).is_ok());
assert!(decode_jwt(&SigningKey::from_string("old-write"), &token).is_err());
assert_eq!(guard.expires_after_sec, 11);
assert_eq!(guard.read_expires_after_sec, 61);
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.check_jwt(None, true).is_ok());
guard.update_signing_keys(SigningKey::from_string("write"), 10, SigningKey(vec![]), 0);
assert!(guard.is_write_active);
guard.update_signing_keys(SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(!guard.is_write_active);
}
#[test]
fn test_extract_host() {
assert_eq!(extract_host("192.168.1.1:8080"), "192.168.1.1");
+10 -8
View File
@@ -1,21 +1,23 @@
# the tests only support python 3.6, not newer
#FROM ubuntu:latest
FROM python:3.6.15-slim-buster
FROM python:3.6.15-slim-bullseye
# Installed required system deps
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get install -y git-core sudo tzdata
&& DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt-get install -y -qq git-core sudo tzdata ca-certificates libxml2-dev libxslt1-dev zlib1g-dev python3-lxml gcc python3-dev \
&& rm -rf /var/lib/apt/lists/*
# Install python deps
RUN pip install virtualenv
# Clone Ceph S3 tests
RUN git clone https://github.com/ceph/s3-tests.git
COPY fix_s3_tests_bucket_conflicts.py /tmp/fix_s3_tests_bucket_conflicts.py
ENV S3_TESTS_PATH=s3-tests
RUN git clone https://github.com/ceph/s3-tests.git \
&& python3 /tmp/fix_s3_tests_bucket_conflicts.py
WORKDIR s3-tests
# Pin to a certain commit on ceph/s3-tests
# https://github.com/ceph/s3-tests/commit/9a6a1e9f197fc9fb031b809d1e057635c2ff8d4e
RUN git checkout 9a6a1e9f197fc9fb031b809d1e057635c2ff8d4e
RUN ./bootstrap
RUN pip install -r requirements.txt \
&& pip install tox \
&& pip install -e .
+13 -2
View File
@@ -210,10 +210,21 @@ func TestS3PolicyVariablesUsernameIsolation(t *testing.T) {
"Sid": "DenyOtherFolders",
"Effect": "Deny",
"Principal": "*",
"Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
"Action": ["s3:GetObject", "s3:PutObject"],
"NotResource": "arn:aws:s3:::%s/${aws:username}/*"
}, {
"Sid": "DenyListOtherPrefixes",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::%s",
"Condition": {
"StringNotLike": {
"s3:prefix": ["${aws:username}/*", "${aws:username}"]
}
}
}]
}`, bucketName, bucketName, bucketName)
}`, bucketName, bucketName, bucketName, bucketName)
_, err = adminClient.PutBucketPolicy(&s3.PutBucketPolicyInput{
Bucket: aws.String(bucketName),
+15 -6
View File
@@ -186,8 +186,8 @@ func (r *Plugin) runLaneSchedulerIterationLocked(ls *schedulerLaneState, jobType
}
}
r.pruneSchedulerState(active)
r.pruneDetectorLeases(active)
r.pruneSchedulerState(ls.lane, active)
r.pruneDetectorLeases(ls.lane, active)
r.setLaneLoopState(ls, "", "idle")
return hadJobs
}
@@ -213,8 +213,8 @@ func (r *Plugin) runLaneSchedulerIterationConcurrent(ls *schedulerLaneState, job
}
wg.Wait()
r.pruneSchedulerState(active)
r.pruneDetectorLeases(active)
r.pruneSchedulerState(ls.lane, active)
r.pruneDetectorLeases(ls.lane, active)
r.setLaneLoopState(ls, "", "idle")
return hadJobs.Load()
}
@@ -746,11 +746,16 @@ func (r *Plugin) finishDetection(jobType string) {
r.schedulerMu.Unlock()
}
func (r *Plugin) pruneSchedulerState(activeJobTypes map[string]struct{}) {
// pruneSchedulerState removes next-detection state for inactive job types
// in lane only. Prune must not touch other lanes' entries in the global map.
func (r *Plugin) pruneSchedulerState(lane SchedulerLane, activeJobTypes map[string]struct{}) {
r.schedulerMu.Lock()
defer r.schedulerMu.Unlock()
for jobType := range r.nextDetectionAt {
if JobTypeLane(jobType) != lane {
continue
}
if _, ok := activeJobTypes[jobType]; !ok {
delete(r.nextDetectionAt, jobType)
delete(r.detectionInFlight, jobType)
@@ -766,11 +771,15 @@ func (r *Plugin) clearSchedulerJobType(jobType string) {
r.clearDetectorLease(jobType, "")
}
func (r *Plugin) pruneDetectorLeases(activeJobTypes map[string]struct{}) {
// pruneDetectorLeases removes detector leases for inactive job types in lane only.
func (r *Plugin) pruneDetectorLeases(lane SchedulerLane, activeJobTypes map[string]struct{}) {
r.detectorLeaseMu.Lock()
defer r.detectorLeaseMu.Unlock()
for jobType := range r.detectorLeases {
if JobTypeLane(jobType) != lane {
continue
}
if _, ok := activeJobTypes[jobType]; !ok {
delete(r.detectorLeases, jobType)
}
+115
View File
@@ -673,3 +673,118 @@ func TestRunLaneSchedulerIterationLockBehavior(t *testing.T) {
})
}
}
// ---------- lane-scoped prune ----------
func TestPruneSchedulerState_DefaultLaneKeepsForeignLanesAndPrunesOwnStale(t *testing.T) {
p, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer p.Shutdown()
now := time.Now().UTC()
p.schedulerMu.Lock()
p.nextDetectionAt["s3_lifecycle"] = now.Add(24 * time.Hour) // lifecycle lane
p.nextDetectionAt["vacuum"] = now.Add(time.Minute) // default lane, active
p.nextDetectionAt["ec_balance"] = now.Add(time.Minute) // default lane, stale
p.detectionInFlight["ec_balance"] = true
p.schedulerMu.Unlock()
// Default-lane iteration prunes with only its own active job types.
p.pruneSchedulerState(LaneDefault, map[string]struct{}{"vacuum": {}})
p.schedulerMu.Lock()
defer p.schedulerMu.Unlock()
if _, ok := p.nextDetectionAt["s3_lifecycle"]; !ok {
t.Fatal("default-lane prune must not delete lifecycle-lane nextDetectionAt[s3_lifecycle]")
}
if _, ok := p.nextDetectionAt["vacuum"]; !ok {
t.Fatal("active default-lane job (vacuum) must be kept")
}
if _, ok := p.nextDetectionAt["ec_balance"]; ok {
t.Fatal("stale default-lane job (ec_balance) must still be pruned within its own lane")
}
if _, ok := p.detectionInFlight["ec_balance"]; ok {
t.Fatal("pruned job must also drop its detectionInFlight entry")
}
}
func TestPruneSchedulerState_LifecycleLaneLeavesDefaultLane(t *testing.T) {
p, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer p.Shutdown()
now := time.Now().UTC()
p.schedulerMu.Lock()
p.nextDetectionAt["vacuum"] = now.Add(time.Minute) // default lane
p.nextDetectionAt["s3_lifecycle"] = now.Add(24 * time.Hour) // lifecycle lane, active
p.schedulerMu.Unlock()
p.pruneSchedulerState(LaneLifecycle, map[string]struct{}{"s3_lifecycle": {}})
p.schedulerMu.Lock()
defer p.schedulerMu.Unlock()
if _, ok := p.nextDetectionAt["vacuum"]; !ok {
t.Fatal("lifecycle-lane prune must not delete default-lane nextDetectionAt[vacuum]")
}
if _, ok := p.nextDetectionAt["s3_lifecycle"]; !ok {
t.Fatal("active lifecycle job (s3_lifecycle) must be kept")
}
}
func TestPruneDetectorLeases_IsLaneScoped(t *testing.T) {
p, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer p.Shutdown()
p.detectorLeaseMu.Lock()
p.detectorLeases["s3_lifecycle"] = "worker-a" // lifecycle lane
p.detectorLeases["vacuum"] = "worker-b" // default lane, active
p.detectorLeases["ec_balance"] = "worker-c" // default lane, stale
p.detectorLeaseMu.Unlock()
p.pruneDetectorLeases(LaneDefault, map[string]struct{}{"vacuum": {}})
p.detectorLeaseMu.Lock()
defer p.detectorLeaseMu.Unlock()
if _, ok := p.detectorLeases["s3_lifecycle"]; !ok {
t.Fatal("default-lane prune must not delete lifecycle-lane detector lease")
}
if _, ok := p.detectorLeases["vacuum"]; !ok {
t.Fatal("active default-lane detector lease (vacuum) must be kept")
}
if _, ok := p.detectorLeases["ec_balance"]; ok {
t.Fatal("stale default-lane detector lease (ec_balance) must still be pruned within its own lane")
}
}
func TestLaneStatus_LifecycleNextDetectionSurvivesDefaultLanePrune(t *testing.T) {
p, err := New(Options{})
if err != nil {
t.Fatalf("New: %v", err)
}
defer p.Shutdown()
now := time.Now().UTC()
expected := now.Add(24 * time.Hour)
p.schedulerMu.Lock()
p.nextDetectionAt["s3_lifecycle"] = expected
p.nextDetectionAt["vacuum"] = now.Add(time.Minute)
p.schedulerMu.Unlock()
p.pruneSchedulerState(LaneDefault, map[string]struct{}{"vacuum": {}})
status := p.GetLaneSchedulerStatus(LaneLifecycle)
if status.NextDetectionAt == nil {
t.Fatal("lifecycle lane status lost next_detection_at after a default-lane prune")
}
if !status.NextDetectionAt.Equal(expected) {
t.Fatalf("next_detection_at = %v, want %v (must be the 24h schedule, not the idle-sleep fallback)",
status.NextDetectionAt, expected)
}
}
+37 -3
View File
@@ -28,6 +28,13 @@ type LockClient struct {
ringMu sync.RWMutex
ring *lock_manager.HashRing
ringVersion int64
// priorRing is the ring before the most recent change, kept for priorWindow so a
// route-by-key caller can consult a just-moved key's previous owner during a
// rebalance. Mirrors the master's lock_manager.LockRing.PriorOwner cooling-off.
priorRing *lock_manager.HashRing
ringChangedAt time.Time
priorWindow time.Duration
}
func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *LockClient {
@@ -36,6 +43,7 @@ func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *
maxLockDuration: 5 * time.Second,
sleepDuration: 2473 * time.Millisecond,
seedFiler: seedFiler,
priorWindow: 5 * time.Second,
}
}
@@ -50,10 +58,15 @@ func (lc *LockClient) SetRing(servers []pb.ServerAddress, version int64) {
return
}
lc.ringVersion = version
if lc.ring == nil {
lc.ring = lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
// Build a fresh ring (not an in-place mutation) so the outgoing ring survives as
// priorRing with its own servers for the cooling-off window.
newRing := lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
newRing.SetServers(servers)
if lc.ring != nil {
lc.priorRing = lc.ring
lc.ringChangedAt = time.Now()
}
lc.ring.SetServers(servers)
lc.ring = newRing
}
// hostForKey returns the filer that should own key per the current ring view,
@@ -82,6 +95,27 @@ func (lc *LockClient) PrimaryForKey(key string) pb.ServerAddress {
return lc.ring.GetPrimary(key)
}
// PriorOwnerForKey returns key's owner from the prior ring while a rebalance is
// within the cooling-off window and ownership actually moved, else "". Lets a
// route-by-key reader consult a just-moved key's previous owner before the new
// owner's NotFound is final (the new owner may not have replicated the key yet).
func (lc *LockClient) PriorOwnerForKey(key string) pb.ServerAddress {
lc.ringMu.RLock()
defer lc.ringMu.RUnlock()
if lc.ring == nil || lc.priorRing == nil {
return ""
}
if time.Since(lc.ringChangedAt) > lc.priorWindow {
return ""
}
current := lc.ring.GetPrimary(key)
prior := lc.priorRing.GetPrimary(key)
if prior != "" && prior != current {
return prior
}
return ""
}
type LiveLock struct {
key string
renewToken string
+60
View File
@@ -1,7 +1,9 @@
package cluster
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
"github.com/seaweedfs/seaweedfs/weed/pb"
@@ -90,3 +92,61 @@ func TestLockClientPrimaryForKey(t *testing.T) {
t.Errorf("PrimaryForKey %q disagrees with hostForKey %q", got, lc.hostForKey("k"))
}
}
// A moved key reports its previous owner within the cooling-off window; an unmoved
// key reports none.
func TestLockClientPriorOwnerForKey(t *testing.T) {
lc := NewLockClient(nil, "seed:8888")
setA := []pb.ServerAddress{"filer-a:8888", "filer-b:8888", "filer-c:8888"}
lc.SetRing(setA, 1)
// One ring: nothing to fall back to.
if got := lc.PriorOwnerForKey("any"); got != "" {
t.Fatalf("single ring should have no prior owner, got %q", got)
}
priorRing := lock_manager.NewHashRing(lock_manager.DefaultVnodeCount)
priorRing.SetServers(setA)
// Add a server so some keys' ownership moves.
setB := []pb.ServerAddress{"filer-a:8888", "filer-b:8888", "filer-c:8888", "filer-d:8888"}
lc.SetRing(setB, 2)
var moved, stable string
for i := 0; i < 2000 && (moved == "" || stable == ""); i++ {
key := fmt.Sprintf("key-%d", i)
if lc.PrimaryForKey(key) != priorRing.GetPrimary(key) {
if moved == "" {
moved = key
}
} else if stable == "" {
stable = key
}
}
if moved == "" || stable == "" {
t.Skip("could not find both a moved and a stable key")
}
if got, want := lc.PriorOwnerForKey(moved), priorRing.GetPrimary(moved); got != want {
t.Fatalf("PriorOwnerForKey(moved)=%q, want %q", got, want)
}
if got := lc.PriorOwnerForKey(stable); got != "" {
t.Fatalf("unmoved key should have no prior owner, got %q", got)
}
}
// The prior owner is only offered within the cooling-off window.
func TestLockClientPriorOwnerForKeyExpires(t *testing.T) {
lc := NewLockClient(nil, "seed:8888")
lc.priorWindow = 20 * time.Millisecond
lc.SetRing([]pb.ServerAddress{"filer-a:8888", "filer-b:8888", "filer-c:8888"}, 1)
lc.SetRing([]pb.ServerAddress{"filer-a:8888", "filer-b:8888", "filer-c:8888", "filer-d:8888"}, 2)
time.Sleep(40 * time.Millisecond)
for i := 0; i < 2000; i++ {
if got := lc.PriorOwnerForKey(fmt.Sprintf("key-%d", i)); got != "" {
t.Fatalf("prior owner should expire after the cooling window, got %q", got)
}
}
}
+2 -1
View File
@@ -178,13 +178,14 @@ func init() {
filerSftpOptions.port = cmdFiler.Flag.Int("sftp.port", 2022, "SFTP server listen port")
filerSftpOptions.sshPrivateKey = cmdFiler.Flag.String("sftp.sshPrivateKey", "", "path to the SSH private key file for host authentication")
filerSftpOptions.hostKeysFolder = cmdFiler.Flag.String("sftp.hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
filerSftpOptions.authMethods = cmdFiler.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, keyboard-interactive")
filerSftpOptions.authMethods = cmdFiler.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
filerSftpOptions.maxAuthTries = cmdFiler.Flag.Int("sftp.maxAuthTries", 6, "maximum number of authentication attempts per connection")
filerSftpOptions.bannerMessage = cmdFiler.Flag.String("sftp.bannerMessage", "SeaweedFS SFTP Server - Unauthorized access is prohibited", "message displayed before authentication")
filerSftpOptions.loginGraceTime = cmdFiler.Flag.Duration("sftp.loginGraceTime", 2*time.Minute, "timeout for authentication")
filerSftpOptions.clientAliveInterval = cmdFiler.Flag.Duration("sftp.clientAliveInterval", 5*time.Second, "interval for sending keep-alive messages")
filerSftpOptions.clientAliveCountMax = cmdFiler.Flag.Int("sftp.clientAliveCountMax", 3, "maximum number of missed keep-alive messages before disconnecting")
filerSftpOptions.userStoreFile = cmdFiler.Flag.String("sftp.userStoreFile", "", "path to JSON file containing user credentials and permissions")
filerSftpOptions.trustedUserCAKeysFile = cmdFiler.Flag.String("sftp.trustedUserCAKeysFile", "", "path to a file with trusted user CA public keys (OpenSSH authorized_keys format); required when 'certificate' is in -sftp.authMethods")
filerSftpOptions.dataCenter = cmdFiler.Flag.String("sftp.dataCenter", "", "prefer to read and write to volumes in this data center")
filerSftpOptions.bindIp = cmdFiler.Flag.String("sftp.ip.bind", "", "ip address to bind to. If empty, default to same as -ip.bind option.")
filerSftpOptions.localSocket = cmdFiler.Flag.String("sftp.localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
+8 -8
View File
@@ -115,15 +115,19 @@ func runFilerMetaBackup(cmd *Command, args []string) bool {
glog.Errorf("traverse meta data: %v", err)
return true
}
glog.V(0).Infof("metadata copied up to %v", startTime)
if err := metaBackup.setOffset(startTime); err != nil {
startTime = time.Now()
glog.Exitf("set metadata backup offset: %v", err)
return true
}
glog.V(0).Infof("metadata copied up to %v", startTime)
}
for {
err := metaBackup.streamMetadataBackup()
startTime, err := metaBackup.getOffset()
if err != nil {
glog.Exitf("read metadata backup offset from %s: %v", *metaBackup.filerAddress, err)
}
if err := metaBackup.streamMetadataBackup(startTime); err != nil {
glog.Errorf("filer meta backup from %s: %v", *metaBackup.filerAddress, err)
time.Sleep(1747 * time.Millisecond)
}
@@ -177,12 +181,8 @@ var (
MetaBackupKey = []byte("metaBackup")
)
func (metaBackup *FilerMetaBackupOptions) streamMetadataBackup() error {
func (metaBackup *FilerMetaBackupOptions) streamMetadataBackup(startTime time.Time) error {
startTime, err := metaBackup.getOffset()
if err != nil {
startTime = time.Now()
}
glog.V(0).Infof("streaming from %v", startTime)
store := metaBackup.store
+3 -1
View File
@@ -103,7 +103,7 @@ func init() {
m.raftResumeState = cmdMaster.Flag.Bool("resumeState", true, "resume previous state on start master server")
m.heartbeatInterval = cmdMaster.Flag.Duration("heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
m.electionTimeout = cmdMaster.Flag.Duration("electionTimeout", 10*time.Second, "election timeout of master servers")
m.raftHashicorp = cmdMaster.Flag.Bool("raftHashicorp", false, "use hashicorp raft")
m.raftHashicorp = cmdMaster.Flag.Bool("raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
m.raftBootstrap = cmdMaster.Flag.Bool("raftBootstrap", false, "Whether to bootstrap the Raft cluster")
m.telemetryUrl = cmdMaster.Flag.String("telemetry.url", "https://telemetry.seaweedfs.com/api/collect", "telemetry server URL to send usage statistics")
m.telemetryEnabled = cmdMaster.Flag.Bool("telemetry", false, "enable telemetry reporting")
@@ -229,6 +229,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
glog.Fatalf("NewHashicorpRaftServer: %s", err)
}
} else {
glog.Warningf("legacy seaweedfs/raft is deprecated and will be removed; restart with -raftHashicorp to switch (cluster state is migrated automatically)")
raftServer, err = weed_server.NewRaftServer(raftServerOption)
if raftServer == nil {
glog.Fatalf("please verify %s is writable, see https://github.com/seaweedfs/seaweedfs/issues/717: %s", *masterOption.metaFolder, err)
@@ -355,6 +356,7 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
grace.OnInterrupt(ms.Shutdown)
grace.OnInterrupt(grpcS.Stop)
grace.OnReload(ms.Reload)
grace.OnReload(func() {
if ms.Topo.HashicorpRaft != nil && ms.Topo.HashicorpRaft.State() == hashicorpRaft.Leader {
ms.Topo.HashicorpRaft.LeadershipTransfer()
+4 -1
View File
@@ -430,7 +430,7 @@ func initMiniMasterFlags() {
miniMasterOptions.raftResumeState = cmdMini.Flag.Bool("master.resumeState", true, "resume previous state on start master server")
miniMasterOptions.heartbeatInterval = cmdMini.Flag.Duration("master.heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
miniMasterOptions.electionTimeout = cmdMini.Flag.Duration("master.electionTimeout", 10*time.Second, "election timeout of master servers")
miniMasterOptions.raftHashicorp = cmdMini.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft")
miniMasterOptions.raftHashicorp = cmdMini.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
miniMasterOptions.raftBootstrap = cmdMini.Flag.Bool("master.raftBootstrap", false, "whether to bootstrap the Raft cluster")
miniMasterOptions.telemetryUrl = cmdMini.Flag.String("master.telemetry.url", "https://telemetry.seaweedfs.com/api/collect", "telemetry server URL")
miniMasterOptions.telemetryEnabled = cmdMini.Flag.Bool("master.telemetry", false, "enable telemetry reporting")
@@ -486,6 +486,7 @@ func initMiniVolumeFlags() {
miniOptions.v.readBufferSizeMB = cmdMini.Flag.Int("volume.readBufferSizeMB", 4, "read buffer size in MB")
miniOptions.v.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
miniOptions.v.preStopSeconds = cmdMini.Flag.Int("volume.preStopSeconds", 1, "number of seconds between stop send heartbeats and stop volume server (default: 1 for mini)")
miniOptions.v.setDiskIOProbeDefaults()
}
// initMiniS3Flags initializes S3 server flag options
@@ -1137,6 +1138,8 @@ func runMini(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
util.LoadConfiguration("master", false)
util.LoadConfiguration("volume", false)
miniOptions.v.applyDiskIOProbeConfig()
// applyConfigFileOptions above may have overwritten -dir from the
// mini.options file, so re-resolve it here alongside the other paths.
+4 -2
View File
@@ -14,7 +14,7 @@ func init() {
}
var cmdScaffold = &Command{
UsageLine: "scaffold -config=[filer|notification|replication|security|master|shell|credential]",
UsageLine: "scaffold -config=[filer|notification|replication|security|master|volume|shell|credential]",
Short: "generate basic configuration files",
Long: `Generate configuration files with all possible configurations for you to customize.
@@ -31,7 +31,7 @@ var cmdScaffold = &Command{
var (
outputPath = cmdScaffold.Flag.String("output", "", "if not empty, save the configuration file to this directory")
config = cmdScaffold.Flag.String("config", "filer", "[filer|notification|replication|security|master|shell|credential] the configuration file to generate")
config = cmdScaffold.Flag.String("config", "filer", "[filer|notification|replication|security|master|volume|shell|credential] the configuration file to generate")
)
func runScaffold(cmd *Command, args []string) bool {
@@ -48,6 +48,8 @@ func runScaffold(cmd *Command, args []string) bool {
content = scaffold.Security
case "master":
content = scaffold.Master
case "volume":
content = scaffold.Volume
case "shell":
content = scaffold.Shell
case "credential":
+3
View File
@@ -27,6 +27,9 @@ var Security string
var masterTemplate string
var Master string
//go:embed volume.toml
var Volume string
//go:embed shell.toml
var Shell string
+27
View File
@@ -0,0 +1,27 @@
# Put this file to one of the location, with descending priority
# ./volume.toml
# $HOME/.seaweedfs/volume.toml
# /etc/seaweedfs/volume.toml
# this file is read by volume servers
[volume.disk.io]
# Disk IO probing is disabled by default. When enabled, a volume server can
# stop advertising a disk after sustained IO errors or latency degradation.
probe = false
timeout = "2s"
interval = "60s"
window = "1m"
min.samples = 10
max.stat.failures = 5
recovery.coef = 0.5
[volume.disk.io.slow]
percent = 20
[volume.disk.io.error]
percent = 10
[volume.disk.io.slow.latency]
hdd = "500ms"
ssd = "100ms"
nvme = "50ms"
+6 -2
View File
@@ -103,7 +103,7 @@ func init() {
masterOptions.metricsAddress = cmdServer.Flag.String("master.metrics.address", "", "Prometheus gateway address")
masterOptions.metricsIntervalSec = cmdServer.Flag.Int("master.metrics.intervalSeconds", 15, "Prometheus push interval in seconds")
masterOptions.raftResumeState = cmdServer.Flag.Bool("master.resumeState", true, "resume previous state on start master server")
masterOptions.raftHashicorp = cmdServer.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft")
masterOptions.raftHashicorp = cmdServer.Flag.Bool("master.raftHashicorp", false, "use hashicorp raft (recommended; legacy seaweedfs/raft is deprecated)")
masterOptions.raftBootstrap = cmdServer.Flag.Bool("master.raftBootstrap", false, "Whether to bootstrap the Raft cluster")
masterOptions.heartbeatInterval = cmdServer.Flag.Duration("master.heartbeatInterval", 300*time.Millisecond, "heartbeat interval of master servers, and will be randomly multiplied by [1, 1.25)")
masterOptions.electionTimeout = cmdServer.Flag.Duration("master.electionTimeout", 10*time.Second, "election timeout of master servers")
@@ -156,6 +156,7 @@ func init() {
serverOptions.v.hasSlowRead = cmdServer.Flag.Bool("volume.hasSlowRead", true, "<experimental> if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.")
serverOptions.v.readBufferSizeMB = cmdServer.Flag.Int("volume.readBufferSizeMB", 4, "<experimental> larger values can optimize query performance but will increase some memory usage,Use with hasSlowRead normally")
serverOptions.v.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
serverOptions.v.setDiskIOProbeDefaults()
s3Options.port = cmdServer.Flag.Int("s3.port", 8333, "s3 server http listen port")
s3Options.portHttps = cmdServer.Flag.Int("s3.port.https", 0, "s3 server https listen port")
@@ -187,13 +188,14 @@ func init() {
sftpOptions.port = cmdServer.Flag.Int("sftp.port", 2022, "SFTP server listen port")
sftpOptions.sshPrivateKey = cmdServer.Flag.String("sftp.sshPrivateKey", "", "path to the SSH private key file for host authentication")
sftpOptions.hostKeysFolder = cmdServer.Flag.String("sftp.hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
sftpOptions.authMethods = cmdServer.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, keyboard-interactive")
sftpOptions.authMethods = cmdServer.Flag.String("sftp.authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
sftpOptions.maxAuthTries = cmdServer.Flag.Int("sftp.maxAuthTries", 6, "maximum number of authentication attempts per connection")
sftpOptions.bannerMessage = cmdServer.Flag.String("sftp.bannerMessage", "SeaweedFS SFTP Server - Unauthorized access is prohibited", "message displayed before authentication")
sftpOptions.loginGraceTime = cmdServer.Flag.Duration("sftp.loginGraceTime", 2*time.Minute, "timeout for authentication")
sftpOptions.clientAliveInterval = cmdServer.Flag.Duration("sftp.clientAliveInterval", 5*time.Second, "interval for sending keep-alive messages")
sftpOptions.clientAliveCountMax = cmdServer.Flag.Int("sftp.clientAliveCountMax", 3, "maximum number of missed keep-alive messages before disconnecting")
sftpOptions.userStoreFile = cmdServer.Flag.String("sftp.userStoreFile", "", "path to JSON file containing user credentials and permissions")
sftpOptions.trustedUserCAKeysFile = cmdServer.Flag.String("sftp.trustedUserCAKeysFile", "", "path to a file with trusted user CA public keys (OpenSSH authorized_keys format); required when 'certificate' is in -sftp.authMethods")
sftpOptions.localSocket = cmdServer.Flag.String("sftp.localSocket", "", "default to /tmp/seaweedfs-sftp-<port>.sock")
iamOptions.port = cmdServer.Flag.Int("iam.port", 8111, "iam server http listen port")
@@ -224,6 +226,8 @@ func runServer(cmd *Command, args []string) bool {
util.LoadSecurityConfiguration()
util.LoadConfiguration("master", false)
util.LoadConfiguration("volume", false)
serverOptions.v.applyDiskIOProbeConfig()
*serverOptions.cpuprofile = util.ResolvePath(*serverOptions.cpuprofile)
*serverOptions.memprofile = util.ResolvePath(*serverOptions.memprofile)
+21 -17
View File
@@ -25,22 +25,23 @@ var (
// SftpOptions holds configuration options for the SFTP server.
type SftpOptions struct {
filer *string
bindIp *string
port *int
sshPrivateKey *string
hostKeysFolder *string
authMethods *string
maxAuthTries *int
bannerMessage *string
loginGraceTime *time.Duration
clientAliveInterval *time.Duration
clientAliveCountMax *int
userStoreFile *string
dataCenter *string
metricsHttpPort *int
metricsHttpIp *string
localSocket *string
filer *string
bindIp *string
port *int
sshPrivateKey *string
hostKeysFolder *string
authMethods *string
maxAuthTries *int
bannerMessage *string
loginGraceTime *time.Duration
clientAliveInterval *time.Duration
clientAliveCountMax *int
userStoreFile *string
trustedUserCAKeysFile *string
dataCenter *string
metricsHttpPort *int
metricsHttpIp *string
localSocket *string
}
// cmdSftp defines the SFTP command similar to the S3 command.
@@ -64,13 +65,14 @@ func init() {
sftpOptionsStandalone.port = cmdSftp.Flag.Int("port", 2022, "SFTP server listen port")
sftpOptionsStandalone.sshPrivateKey = cmdSftp.Flag.String("sshPrivateKey", "", "path to the SSH private key file for host authentication")
sftpOptionsStandalone.hostKeysFolder = cmdSftp.Flag.String("hostKeysFolder", "", "path to folder containing SSH private key files for host authentication")
sftpOptionsStandalone.authMethods = cmdSftp.Flag.String("authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, keyboard-interactive")
sftpOptionsStandalone.authMethods = cmdSftp.Flag.String("authMethods", "password,publickey", "comma-separated list of allowed auth methods: password, publickey, certificate")
sftpOptionsStandalone.maxAuthTries = cmdSftp.Flag.Int("maxAuthTries", 6, "maximum number of authentication attempts per connection")
sftpOptionsStandalone.bannerMessage = cmdSftp.Flag.String("bannerMessage", "SeaweedFS SFTP Server - Unauthorized access is prohibited", "message displayed before authentication")
sftpOptionsStandalone.loginGraceTime = cmdSftp.Flag.Duration("loginGraceTime", 2*time.Minute, "timeout for authentication")
sftpOptionsStandalone.clientAliveInterval = cmdSftp.Flag.Duration("clientAliveInterval", 5*time.Second, "interval for sending keep-alive messages")
sftpOptionsStandalone.clientAliveCountMax = cmdSftp.Flag.Int("clientAliveCountMax", 3, "maximum number of missed keep-alive messages before disconnecting")
sftpOptionsStandalone.userStoreFile = cmdSftp.Flag.String("userStoreFile", "", "path to JSON file containing user credentials and permissions")
sftpOptionsStandalone.trustedUserCAKeysFile = cmdSftp.Flag.String("trustedUserCAKeysFile", "", "path to a file with trusted user CA public keys (OpenSSH authorized_keys format); required when 'certificate' is in -authMethods. Analogous to OpenSSH TrustedUserCAKeys and MinIO --sftp=trusted-user-ca-key")
sftpOptionsStandalone.dataCenter = cmdSftp.Flag.String("dataCenter", "", "prefer to read and write to volumes in this data center")
sftpOptionsStandalone.metricsHttpPort = cmdSftp.Flag.Int("metricsPort", 0, "Prometheus metrics listen port")
sftpOptionsStandalone.metricsHttpIp = cmdSftp.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.")
@@ -101,6 +103,7 @@ func (sftpOpt *SftpOptions) resolvePaths() {
*sftpOpt.sshPrivateKey = util.ResolvePath(*sftpOpt.sshPrivateKey)
*sftpOpt.hostKeysFolder = util.ResolvePath(*sftpOpt.hostKeysFolder)
*sftpOpt.userStoreFile = util.ResolvePath(*sftpOpt.userStoreFile)
*sftpOpt.trustedUserCAKeysFile = util.ResolvePath(*sftpOpt.trustedUserCAKeysFile)
}
func (sftpOpt *SftpOptions) startSftpServer() bool {
@@ -165,6 +168,7 @@ func (sftpOpt *SftpOptions) startSftpServer() bool {
ClientAliveInterval: *sftpOpt.clientAliveInterval,
ClientAliveCountMax: *sftpOpt.clientAliveCountMax,
UserStoreFile: *sftpOpt.userStoreFile,
TrustedUserCAKeysFile: *sftpOpt.trustedUserCAKeysFile,
FilerSigningKey: []byte(filerSigningKey),
FilerSigningExpiresAfter: filerSigningExpiresAfter,
})
+144
View File
@@ -78,12 +78,119 @@ type VolumeServerOptions struct {
allowUntrustedRemoteEndpoints *bool
debug *bool
debugPort *int
diskIOProbe *bool
diskIOTimeout *time.Duration
diskIOInterval *time.Duration
diskHDDIOSlowLatency *time.Duration
diskSSDIOSlowLatency *time.Duration
diskNVMEIOSlowLatency *time.Duration
diskIOWindow *time.Duration
diskIOMinSamples *int
diskIOSlowPercent *float64
diskIOErrorPercent *float64
diskIOMaxStatFailures *int
diskRecoveryCoef *float64
// shutdownCtx, when non-nil, tells startVolumeServer to shut down once the
// ctx is cancelled. Used by integration tests and by weed mini; nil for
// standalone weed volume.
shutdownCtx context.Context
}
func (v *VolumeServerOptions) setDiskIOProbeDefaults() {
if v.diskIOProbe == nil {
defaultValue := false
v.diskIOProbe = &defaultValue
}
if v.diskIOTimeout == nil {
defaultValue := 2 * time.Second
v.diskIOTimeout = &defaultValue
}
if v.diskIOInterval == nil {
defaultValue := 60 * time.Second
v.diskIOInterval = &defaultValue
}
if v.diskHDDIOSlowLatency == nil {
defaultValue := 500 * time.Millisecond
v.diskHDDIOSlowLatency = &defaultValue
}
if v.diskSSDIOSlowLatency == nil {
defaultValue := 100 * time.Millisecond
v.diskSSDIOSlowLatency = &defaultValue
}
if v.diskNVMEIOSlowLatency == nil {
defaultValue := 50 * time.Millisecond
v.diskNVMEIOSlowLatency = &defaultValue
}
if v.diskIOWindow == nil {
defaultValue := time.Minute
v.diskIOWindow = &defaultValue
}
if v.diskIOMinSamples == nil {
defaultValue := 10
v.diskIOMinSamples = &defaultValue
}
if v.diskIOSlowPercent == nil {
defaultValue := 20.0
v.diskIOSlowPercent = &defaultValue
}
if v.diskIOErrorPercent == nil {
defaultValue := 10.0
v.diskIOErrorPercent = &defaultValue
}
if v.diskIOMaxStatFailures == nil {
defaultValue := 5
v.diskIOMaxStatFailures = &defaultValue
}
if v.diskRecoveryCoef == nil {
defaultValue := 0.5
v.diskRecoveryCoef = &defaultValue
}
}
func (v *VolumeServerOptions) applyDiskIOProbeConfig() {
v.setDiskIOProbeDefaults()
config := util.GetViper()
if config.IsSet("volume.disk.io.probe") {
*v.diskIOProbe = config.GetBool("volume.disk.io.probe")
}
if config.IsSet("volume.disk.io.timeout") {
*v.diskIOTimeout = config.GetDuration("volume.disk.io.timeout")
}
if config.IsSet("volume.disk.io.slow.latency.hdd") {
*v.diskHDDIOSlowLatency = config.GetDuration("volume.disk.io.slow.latency.hdd")
}
if config.IsSet("volume.disk.io.slow.latency.ssd") {
*v.diskSSDIOSlowLatency = config.GetDuration("volume.disk.io.slow.latency.ssd")
}
if config.IsSet("volume.disk.io.slow.latency.nvme") {
*v.diskNVMEIOSlowLatency = config.GetDuration("volume.disk.io.slow.latency.nvme")
}
if config.IsSet("volume.disk.io.interval") {
*v.diskIOInterval = config.GetDuration("volume.disk.io.interval")
}
if config.IsSet("volume.disk.io.window") {
*v.diskIOWindow = config.GetDuration("volume.disk.io.window")
}
if config.IsSet("volume.disk.io.min.samples") {
*v.diskIOMinSamples = config.GetInt("volume.disk.io.min.samples")
}
if config.IsSet("volume.disk.io.slow.percent") {
*v.diskIOSlowPercent = config.GetFloat64("volume.disk.io.slow.percent")
}
if config.IsSet("volume.disk.io.error.percent") {
*v.diskIOErrorPercent = config.GetFloat64("volume.disk.io.error.percent")
}
if config.IsSet("volume.disk.io.max.stat.failures") {
*v.diskIOMaxStatFailures = config.GetInt("volume.disk.io.max.stat.failures")
}
if config.IsSet("volume.disk.io.recovery.coef") {
*v.diskRecoveryCoef = config.GetFloat64("volume.disk.io.recovery.coef")
}
}
func init() {
cmdVolume.Run = runVolume // break init cycle
v.port = cmdVolume.Flag.Int("port", 8080, "http listen port")
@@ -124,6 +231,7 @@ func init() {
v.allowUntrustedRemoteEndpoints = cmdVolume.Flag.Bool("volume.allowUntrustedRemoteEndpoints", false, "if true, FetchAndWriteNeedle accepts arbitrary remote S3 endpoints including loopback / link-local hosts. Default rejects internal / metadata endpoints.")
v.debug = cmdVolume.Flag.Bool("debug", false, "serves runtime profiling data via pprof on the port specified by -debug.port")
v.debugPort = cmdVolume.Flag.Int("debug.port", 6060, "http port for debugging")
v.setDiskIOProbeDefaults()
}
var cmdVolume = &Command{
@@ -151,6 +259,8 @@ func runVolume(cmd *Command, args []string) bool {
}
util.LoadSecurityConfiguration()
util.LoadConfiguration("volume", false)
v.applyDiskIOProbeConfig()
// If --pprof is set we assume the caller wants to be able to collect
// cpu and memory profiles via go tool pprof
@@ -201,6 +311,7 @@ func runVolume(cmd *Command, args []string) bool {
}
func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, volumeWhiteListOption string, minFreeSpaces []util.MinFreeSpace) {
v.setDiskIOProbeDefaults()
// Set multiple folders and each folder's max volume count limit'
v.folders = strings.Split(volumeFolders, ",")
@@ -306,7 +417,39 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
// Determine volume server ID: if not specified, use ip:port
volumeServerId := util.GetVolumeServerId(*v.id, *v.ip, *v.port)
var slowLatency time.Duration
switch *v.diskType {
case "hdd":
slowLatency = *v.diskHDDIOSlowLatency
case "ssd":
slowLatency = *v.diskSSDIOSlowLatency
case "nvme":
slowLatency = *v.diskNVMEIOSlowLatency
default:
slowLatency = *v.diskHDDIOSlowLatency
}
diskProbeConfig := stats_collect.DiskIOProbeConfig{
Enabled: *v.diskIOProbe,
Timeout: *v.diskIOTimeout,
Interval: *v.diskIOInterval,
SlowLatency: slowLatency,
Window: *v.diskIOWindow,
MinSamples: *v.diskIOMinSamples,
SlowPercent: *v.diskIOSlowPercent,
ErrorPercent: *v.diskIOErrorPercent,
MaxStatFailures: *v.diskIOMaxStatFailures,
RecoveryCoef: *v.diskRecoveryCoef,
}
if diskProbeConfig.Enabled && len(v.folders) > 1 {
glog.Warningf("disk IO probe is disabled for multiple volume directories: %v", v.folders)
diskProbeConfig.Enabled = false
}
volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
*v.ip, *v.port, *v.portGrpc, *v.publicUrl, volumeServerId,
v.folders, v.folderMaxLimits, minFreeSpaces, diskTypes, folderTags,
@@ -326,6 +469,7 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
*v.readBufferSizeMB,
*v.ldbTimeout,
*v.allowUntrustedRemoteEndpoints,
diskProbeConfig,
)
// starting grpc server
grpcS := v.startGrpcService(volumeServer)
+9 -2
View File
@@ -220,8 +220,10 @@ func (f *Filer) ReadPersistedLogBuffer(startPosition log_buffer.MessagePosition,
}
ch := make(chan entryOrErr, readaheadSize)
stopReadahead := make(chan struct{})
readaheadDone := make(chan struct{})
go func() {
defer close(ch)
defer close(readaheadDone)
for {
entry, readErr := visitor.GetNext()
if readErr != nil {
@@ -240,7 +242,13 @@ func (f *Filer) ReadPersistedLogBuffer(startPosition log_buffer.MessagePosition,
}
}
}()
defer close(stopReadahead)
// Stop the readahead goroutine, wait for it to exit, then release any log
// file readers it left open (e.g. on early return or cancellation).
defer func() {
close(stopReadahead)
<-readaheadDone
visitor.Close()
}()
for item := range ch {
if item.err != nil {
@@ -261,4 +269,3 @@ func (f *Filer) ReadPersistedLogBuffer(startPosition log_buffer.MessagePosition,
return
}
+53 -48
View File
@@ -197,6 +197,15 @@ func (o *OrderedLogVisitor) GetNext() (logEntry *filer_pb.LogEntry, err error) {
return item.Entry, nil
}
// Close releases any log file readers still open across the per-filer
// iterators, e.g. when a subscription stops before reaching the end. Safe to
// call more than once.
func (o *OrderedLogVisitor) Close() {
for _, it := range o.perFilerIteratorMap {
it.Close()
}
}
func getFilerId(name string) string {
idx := strings.LastIndex(name, ".")
if idx < 0 {
@@ -329,12 +338,11 @@ func (c *LogFileEntryCollector) collectMore(v *OrderedLogVisitor) (err error) {
// ----------
type LogFileQueueIterator struct {
q *util.Queue[*LogFileEntry]
masterClient *wdclient.MasterClient
startTsNs int64
stopTsNs int64
pendingEntries []*filer_pb.LogEntry
pendingIndex int
q *util.Queue[*LogFileEntry]
masterClient *wdclient.MasterClient
startTsNs int64
stopTsNs int64
currentFileIterator *LogFileIterator
}
func newLogFileQueueIterator(masterClient *wdclient.MasterClient, q *util.Queue[*LogFileEntry], startTsNs, stopTsNs int64) *LogFileQueueIterator {
@@ -346,20 +354,48 @@ func newLogFileQueueIterator(masterClient *wdclient.MasterClient, q *util.Queue[
}
}
// getNext will return io.EOF when done
// Close releases the current log file reader, if any. Safe to call more than once.
func (iter *LogFileQueueIterator) Close() {
if iter.currentFileIterator != nil {
if err := iter.currentFileIterator.Close(); err != nil {
glog.Warningf("close log file %s: %v", iter.currentFileIterator.filePath, err)
}
iter.currentFileIterator = nil
}
}
// getNext streams one log entry at a time from the current file, advancing to
// the next file as each is exhausted. It returns io.EOF when done. Entries are
// not buffered per file, so memory stays O(1) regardless of log file size.
func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer_pb.LogEntry, err error) {
for {
// return pending entries first
if iter.pendingIndex < len(iter.pendingEntries) {
logEntry = iter.pendingEntries[iter.pendingIndex]
iter.pendingIndex++
return logEntry, nil
if iter.currentFileIterator != nil {
logEntry, err = iter.currentFileIterator.getNext()
if err == nil {
return logEntry, nil
}
// The current file is done (io.EOF), its volume was deleted, or it is
// unreadable. Close it on every path so the reader is not left alive
// until GC; only a genuine read error is propagated.
readErr := err
switch {
case readErr == io.EOF:
readErr = nil
case isChunkNotFoundError(readErr):
// Volume or chunk was deleted, skip the rest of this log file
glog.Warningf("skipping rest of %s: %v", iter.currentFileIterator.filePath, readErr)
readErr = nil
}
if closeErr := iter.currentFileIterator.Close(); closeErr != nil {
glog.Warningf("close log file %s: %v", iter.currentFileIterator.filePath, closeErr)
}
iter.currentFileIterator = nil
if readErr != nil {
return nil, readErr
}
}
// reset for next file
iter.pendingEntries = nil
iter.pendingIndex = 0
// read entries from next file
// advance to the next file
if iter.q.Len() == 0 {
return nil, io.EOF
}
@@ -382,38 +418,7 @@ func (iter *LogFileQueueIterator) getNext(v *OrderedLogVisitor) (logEntry *filer
if next != nil && next.TsNs <= iter.startTsNs {
continue
}
// read all entries from this file
iter.pendingEntries, err = iter.readFileEntries(t.FileEntry)
if err != nil {
return nil, err
}
}
}
// readFileEntries reads all log entries from a single file
func (iter *LogFileQueueIterator) readFileEntries(fileEntry *Entry) (entries []*filer_pb.LogEntry, err error) {
fileIterator := newLogFileIterator(iter.masterClient, fileEntry, iter.startTsNs, iter.stopTsNs)
defer func() {
if closeErr := fileIterator.Close(); closeErr != nil && err == nil {
err = closeErr
}
}()
for {
logEntry, err := fileIterator.getNext()
if err == io.EOF {
return entries, nil
}
if err != nil {
if isChunkNotFoundError(err) {
// Volume or chunk was deleted, skip the rest of this log file
glog.Warningf("skipping rest of %s: %v", fileIterator.filePath, err)
return entries, nil
}
return nil, err
}
entries = append(entries, logEntry)
iter.currentFileIterator = newLogFileIterator(iter.masterClient, t.FileEntry, iter.startTsNs, iter.stopTsNs)
}
}
+41
View File
@@ -0,0 +1,41 @@
package mysql
import (
"database/sql"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
// ConfigureListOrdering switches the list queries to BINARY byte ordering when
// the live filemeta.name collation is not binary, so S3 ListObjectsV2 stays
// lexicographic. The fallback costs a filesort, so warn the operator to fix it.
func ConfigureListOrdering(db *sql.DB, gen *SqlGenMysql) {
collation, isBinary, err := nameColumnCollation(db)
if err != nil {
glog.V(1).Infof("mysql: skip filemeta.name collation check: %v", err)
return
}
if isBinary {
return
}
gen.ForceBinaryCollation = true
glog.Warningf("mysql: filemeta.name collation %q is not binary, so S3 list order is not byte-lexicographic and clients that merge sorted listings may report spurious diffs. Falling back to a slower BINARY sort; convert the name column to a *_bin collation (e.g. utf8mb4_bin) for correct, indexed ordering.", collation)
}
func nameColumnCollation(db *sql.DB) (collation string, isBinary bool, err error) {
row := db.QueryRow("SELECT COLLATION_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = 'name'", abstract_sql.DEFAULT_TABLE)
var c sql.NullString
if err = row.Scan(&c); err != nil {
return "", false, err
}
return c.String, isBinaryCollation(c.String), nil
}
// isBinaryCollation reports whether a collation orders by byte value: a NULL
// collation (BINARY column) or any *_bin collation.
func isBinaryCollation(collation string) bool {
c := strings.ToLower(strings.TrimSpace(collation))
return c == "" || c == "binary" || strings.HasSuffix(c, "_bin")
}
+14 -2
View File
@@ -11,6 +11,8 @@ type SqlGenMysql struct {
CreateTableSqlTemplate string
DropTableSqlTemplate string
UpsertQueryTemplate string
// Force byte ordering on a non-binary name column; see ConfigureListOrdering.
ForceBinaryCollation bool
}
// DefaultUpsertQuery keeps INSERTs idempotent so the inode-index KvPut
@@ -48,12 +50,22 @@ func (gen *SqlGenMysql) GetSqlDeleteFolderChildren(tableName string) string {
return fmt.Sprintf("DELETE FROM `%s` WHERE `dirhash` = ? AND `directory` = ?", tableName)
}
// nameExpr forces byte ordering on a non-binary column at the cost of a filesort.
func (gen *SqlGenMysql) nameExpr() string {
if gen.ForceBinaryCollation {
return "BINARY `name`"
}
return "`name`"
}
func (gen *SqlGenMysql) GetSqlListExclusive(tableName string) string {
return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND `name` > ? AND `directory` = ? AND `name` LIKE ? ORDER BY `name` ASC LIMIT ?", tableName)
name := gen.nameExpr()
return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s > ? AND `directory` = ? AND %s LIKE ? ORDER BY %s ASC LIMIT ?", tableName, name, name, name)
}
func (gen *SqlGenMysql) GetSqlListInclusive(tableName string) string {
return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND `name` >= ? AND `directory` = ? AND `name` LIKE ? ORDER BY `name` ASC LIMIT ?", tableName)
name := gen.nameExpr()
return fmt.Sprintf("SELECT `name`, `meta` FROM `%s` WHERE `dirhash` = ? AND %s >= ? AND `directory` = ? AND %s LIKE ? ORDER BY %s ASC LIMIT ?", tableName, name, name, name)
}
func (gen *SqlGenMysql) GetSqlCreateTable(tableName string) string {
+42
View File
@@ -26,3 +26,45 @@ func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) {
t.Fatalf("plain INSERT path should not contain ON DUPLICATE KEY UPDATE, got: %s", got)
}
}
func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) {
gen := &SqlGenMysql{}
for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} {
if strings.Contains(got, "BINARY") {
t.Fatalf("default list query should not force BINARY, got: %s", got)
}
if !strings.Contains(got, "ORDER BY `name` ASC") {
t.Fatalf("expected plain name ordering, got: %s", got)
}
}
}
func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) {
gen := &SqlGenMysql{ForceBinaryCollation: true}
for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} {
if !strings.Contains(got, "ORDER BY BINARY `name` ASC") {
t.Fatalf("expected BINARY ordering, got: %s", got)
}
if !strings.Contains(got, "BINARY `name` LIKE ?") {
t.Fatalf("expected BINARY prefix filter, got: %s", got)
}
if strings.Contains(got, "AND `name` > ?") || strings.Contains(got, "AND `name` >= ?") {
t.Fatalf("pagination comparison must also be BINARY, got: %s", got)
}
}
}
func TestIsBinaryCollation(t *testing.T) {
binary := []string{"", "binary", "utf8mb4_bin", "utf8mb3_bin", "latin1_bin", "UTF8MB4_BIN"}
for _, c := range binary {
if !isBinaryCollation(c) {
t.Fatalf("expected %q to be treated as binary", c)
}
}
ci := []string{"utf8mb4_general_ci", "utf8mb3_general_ci", "utf8mb4_0900_ai_ci", "latin1_swedish_ci"}
for _, c := range ci {
if isBinaryCollation(c) {
t.Fatalf("expected %q to be treated as non-binary", c)
}
}
}
+4 -1
View File
@@ -70,11 +70,12 @@ func (store *MysqlStore) initialize(dsn string, upsertQuery string, enableUpsert
} else if upsertQuery == "" {
upsertQuery = DefaultUpsertQuery
}
store.SqlGenerator = &SqlGenMysql{
gen := &SqlGenMysql{
CreateTableSqlTemplate: "",
DropTableSqlTemplate: "DROP TABLE `%s`",
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
store.RetryableErrorCallback = func(err error) bool {
var mysqlError *mysql.MySQLError
@@ -155,6 +156,8 @@ func (store *MysqlStore) initialize(dsn string, upsertQuery string, enableUpsert
return fmt.Errorf("connect to %s error:%v", maskedDSN(cfg), err)
}
ConfigureListOrdering(store.DB, gen)
return nil
}
+4 -1
View File
@@ -63,11 +63,12 @@ func (store *MysqlStore2) initialize(createTable, upsertQuery string, enableUpse
} else if upsertQuery == "" {
upsertQuery = mysql.DefaultUpsertQuery
}
store.SqlGenerator = &mysql.SqlGenMysql{
gen := &mysql.SqlGenMysql{
CreateTableSqlTemplate: createTable,
DropTableSqlTemplate: "DROP TABLE `%s`",
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
adaptedSqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, "<ADAPTED>", hostname, port, database)
@@ -96,5 +97,7 @@ func (store *MysqlStore2) initialize(createTable, upsertQuery string, enableUpse
return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err)
}
mysql.ConfigureListOrdering(store.DB, gen)
return nil
}
+53
View File
@@ -0,0 +1,53 @@
package postgres
import (
"database/sql"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
// ConfigureListOrdering switches the list queries to COLLATE "C" when the live
// filemeta.name collation is locale-aware, so S3 ListObjectsV2 stays
// lexicographic. The fallback costs a sort, so warn the operator to fix it.
func ConfigureListOrdering(db *sql.DB, gen *SqlGenPostgres) {
collation, isBinary, err := nameColumnCollation(db)
if err != nil {
glog.V(1).Infof("postgres: skip filemeta.name collation check: %v", err)
return
}
if isBinary {
return
}
gen.ForceBinaryCollation = true
glog.Warningf(`postgres: filemeta.name collation %q is not byte-ordered, so S3 list order is not byte-lexicographic and clients that merge sorted listings may report spurious diffs. Falling back to a slower COLLATE "C" sort; declare the name column COLLATE "C" (or use a C/C.UTF-8 database collation) for correct, indexed ordering.`, collation)
}
func nameColumnCollation(db *sql.DB) (collation string, isBinary bool, err error) {
// information_schema reports NULL for a column on the database default, so
// fall back to datcollate for the effective ordering.
row := db.QueryRow(`SELECT
(SELECT collation_name FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = $1 AND column_name = 'name'),
(SELECT datcollate FROM pg_database WHERE datname = current_database())`, abstract_sql.DEFAULT_TABLE)
var columnCollation, dbCollate sql.NullString
if err = row.Scan(&columnCollation, &dbCollate); err != nil {
return "", false, err
}
effective := columnCollation.String
if !columnCollation.Valid || effective == "" {
effective = dbCollate.String
}
return effective, isByteOrderedCollation(effective), nil
}
// isByteOrderedCollation reports whether a Postgres locale sorts by byte value
// (C, POSIX, C.UTF-8) rather than locale order (en_US.UTF-8, ICU, ...).
func isByteOrderedCollation(name string) bool {
switch strings.ToLower(strings.TrimSpace(name)) {
case "c", "posix", "c.utf-8", "c.utf8":
return true
}
return false
}
+14 -2
View File
@@ -11,6 +11,8 @@ type SqlGenPostgres struct {
CreateTableSqlTemplate string
DropTableSqlTemplate string
UpsertQueryTemplate string
// Force byte ordering on a locale-aware name column; see ConfigureListOrdering.
ForceBinaryCollation bool
}
// DefaultUpsertQuery keeps INSERTs idempotent so a duplicate-key failure
@@ -46,12 +48,22 @@ func (gen *SqlGenPostgres) GetSqlDeleteFolderChildren(tableName string) string {
return fmt.Sprintf(`DELETE FROM "%s" WHERE dirhash=$1 AND directory=$2`, tableName)
}
// nameExpr forces byte ordering on a locale-aware column via COLLATE "C".
func (gen *SqlGenPostgres) nameExpr() string {
if gen.ForceBinaryCollation {
return `name COLLATE "C"`
}
return "name"
}
func (gen *SqlGenPostgres) GetSqlListExclusive(tableName string) string {
return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND name>$2 AND directory=$3 AND name like $4 ORDER BY NAME ASC LIMIT $5`, tableName)
name := gen.nameExpr()
return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>$2 AND directory=$3 AND %s like $4 ORDER BY %s ASC LIMIT $5`, tableName, name, name, name)
}
func (gen *SqlGenPostgres) GetSqlListInclusive(tableName string) string {
return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND name>=$2 AND directory=$3 AND name like $4 ORDER BY NAME ASC LIMIT $5`, tableName)
name := gen.nameExpr()
return fmt.Sprintf(`SELECT NAME, meta FROM "%s" WHERE dirhash=$1 AND %s>=$2 AND directory=$3 AND %s like $4 ORDER BY %s ASC LIMIT $5`, tableName, name, name, name)
}
func (gen *SqlGenPostgres) GetSqlCreateTable(tableName string) string {
@@ -23,3 +23,45 @@ func TestEmptyUpsertTemplateFallsBackToPlainInsert(t *testing.T) {
t.Fatalf("plain INSERT path should not contain ON CONFLICT, got: %s", got)
}
}
func TestListSqlDefaultOrderingFollowsColumn(t *testing.T) {
gen := &SqlGenPostgres{}
for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} {
if strings.Contains(got, "COLLATE") {
t.Fatalf("default list query should not force a collation, got: %s", got)
}
if !strings.Contains(got, "ORDER BY name ASC") {
t.Fatalf("expected plain name ordering, got: %s", got)
}
}
}
func TestListSqlBinaryOrderingOnNonBinaryColumn(t *testing.T) {
gen := &SqlGenPostgres{ForceBinaryCollation: true}
for _, got := range []string{gen.GetSqlListExclusive("filemeta"), gen.GetSqlListInclusive("filemeta")} {
if !strings.Contains(got, `ORDER BY name COLLATE "C" ASC`) {
t.Fatalf(`expected COLLATE "C" ordering, got: %s`, got)
}
if !strings.Contains(got, `name COLLATE "C" like $4`) {
t.Fatalf(`expected COLLATE "C" prefix filter, got: %s`, got)
}
if strings.Contains(got, "AND name>$2") || strings.Contains(got, "AND name>=$2") {
t.Fatalf("pagination comparison must also be byte-ordered, got: %s", got)
}
}
}
func TestIsByteOrderedCollation(t *testing.T) {
byteOrdered := []string{"C", "POSIX", "c", "C.UTF-8", "C.utf8"}
for _, c := range byteOrdered {
if !isByteOrderedCollation(c) {
t.Fatalf("expected %q to be treated as byte-ordered", c)
}
}
locale := []string{"en_US.UTF-8", "en_US.utf8", "en-US-x-icu", "und-x-icu", ""}
for _, c := range locale {
if isByteOrderedCollation(c) {
t.Fatalf("expected %q to be treated as locale-aware", c)
}
}
}
+4 -1
View File
@@ -62,11 +62,12 @@ func (store *PostgresStore) initialize(upsertQuery string, enableUpsert bool, us
} else if upsertQuery == "" {
upsertQuery = DefaultUpsertQuery
}
store.SqlGenerator = &SqlGenPostgres{
gen := &SqlGenPostgres{
CreateTableSqlTemplate: "",
DropTableSqlTemplate: `drop table "%s"`,
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
// pgx-optimized connection string with better timeouts and connection handling
sqlUrl := "connect_timeout=30"
@@ -116,5 +117,7 @@ func (store *PostgresStore) initialize(upsertQuery string, enableUpsert bool, us
}
store.DB = db
ConfigureListOrdering(store.DB, gen)
return nil
}
+4 -1
View File
@@ -68,11 +68,12 @@ func (store *PostgresStore2) initialize(createTable, upsertQuery string, enableU
} else if upsertQuery == "" {
upsertQuery = postgres.DefaultUpsertQuery
}
store.SqlGenerator = &postgres.SqlGenPostgres{
gen := &postgres.SqlGenPostgres{
CreateTableSqlTemplate: createTable,
DropTableSqlTemplate: `drop table "%s"`,
UpsertQueryTemplate: upsertQuery,
}
store.SqlGenerator = gen
// pgx-optimized connection string with better timeouts and connection handling
sqlUrl := "connect_timeout=30"
@@ -126,5 +127,7 @@ func (store *PostgresStore2) initialize(createTable, upsertQuery string, enableU
return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err)
}
postgres.ConfigureListOrdering(store.DB, gen)
return nil
}
+4
View File
@@ -9,6 +9,10 @@ const (
// Policy document version
const PolicyDocumentVersion = "2012-10-17"
// DefaultAccountID is the placeholder AWS account id used in generated ARNs,
// matching the value used throughout the S3 API.
const DefaultAccountID = "000000000000"
// Error message templates
const UserDoesNotExist = "the user with name %s cannot be found."
+16
View File
@@ -7,6 +7,7 @@ import (
"math/big"
"sort"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
@@ -17,6 +18,21 @@ func Hash(s *string) string {
return fmt.Sprintf("%x", h.Sum(nil))
}
// UserArn builds an AWS-compatible IAM user ARN.
func UserArn(userName string) string {
return fmt.Sprintf("arn:aws:iam::%s:user/%s", DefaultAccountID, userName)
}
// NewUser builds an iam.User for IAM API responses. The Arn must be a real ARN:
// the terraform aws provider (>= 6.41) reads a user back after creating it and
// blocks until GetUser returns a value that passes arn.IsARN, so an empty Arn
// leaves apply hanging until it times out.
func NewUser(userName string) iam.User {
arn := UserArn(userName)
path := "/"
return iam.User{UserName: &userName, Arn: &arn, Path: &path}
}
// GenerateRandomString generates a cryptographically secure random string.
// Uses crypto/rand for security-sensitive credential generation.
func GenerateRandomString(length int, charset string) (string, error) {
+15
View File
@@ -183,6 +183,21 @@ type GetPolicyVersionResponse struct {
CommonResponse
}
// CreatePolicyVersionResponse is the response for CreatePolicyVersion action.
type CreatePolicyVersionResponse struct {
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ CreatePolicyVersionResponse"`
CreatePolicyVersionResult struct {
PolicyVersion iam.PolicyVersion `xml:"PolicyVersion"`
} `xml:"CreatePolicyVersionResult"`
CommonResponse
}
// DeletePolicyVersionResponse is the response for DeletePolicyVersion action.
type DeletePolicyVersionResponse struct {
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ DeletePolicyVersionResponse"`
CommonResponse
}
// CreateUserResponse is the response for CreateUser action.
type CreateUserResponse struct {
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ CreateUserResponse"`
+3 -2
View File
@@ -9,6 +9,7 @@ import (
"github.com/aws/aws-sdk-go/service/iam"
"github.com/seaweedfs/seaweedfs/weed/glog"
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
@@ -105,8 +106,8 @@ func (iama *IamApiServer) GetGroup(s3cfg *iam_pb.S3ApiConfiguration, values url.
if g.Name == groupName {
resp.GetGroupResult.Group.GroupName = &g.Name
for _, member := range g.Members {
m := member
resp.GetGroupResult.Users = append(resp.GetGroupResult.Users, &iam.User{UserName: &m})
user := iamlib.NewUser(member)
resp.GetGroupResult.Users = append(resp.GetGroupResult.Users, &user)
}
return resp, nil
}
+243 -3
View File
@@ -46,6 +46,11 @@ var policyLock = sync.RWMutex{}
const policyArnPrefix = "arn:aws:iam:::policy/"
// policyDefaultVersionId is the single managed-policy version SeaweedFS exposes.
// Managed policies are stored as one current document with no version history,
// so the API presents exactly one version ("v1") which is always the default.
const policyDefaultVersionId = "v1"
// parsePolicyArn validates an IAM policy ARN and extracts the policy name.
func parsePolicyArn(policyArn string) (string, *IamError) {
if !strings.HasPrefix(policyArn, policyArnPrefix) {
@@ -183,7 +188,8 @@ func validateAccessKeyStatus(status string) error {
func (iama *IamApiServer) ListUsers(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *ListUsersResponse) {
resp = &ListUsersResponse{}
for _, ident := range s3cfg.Identities {
resp.ListUsersResult.Users = append(resp.ListUsersResult.Users, &iam.User{UserName: &ident.Name})
user := iamlib.NewUser(ident.Name)
resp.ListUsersResult.Users = append(resp.ListUsersResult.Users, &user)
}
return resp
}
@@ -213,7 +219,7 @@ func (iama *IamApiServer) ListAccessKeys(s3cfg *iam_pb.S3ApiConfiguration, value
func (iama *IamApiServer) CreateUser(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *CreateUserResponse) {
resp = &CreateUserResponse{}
userName := values.Get("UserName")
resp.CreateUserResult.User.UserName = &userName
resp.CreateUserResult.User = iamlib.NewUser(userName)
s3cfg.Identities = append(s3cfg.Identities, &iam_pb.Identity{Name: userName})
return resp
}
@@ -248,7 +254,7 @@ func (iama *IamApiServer) GetUser(s3cfg *iam_pb.S3ApiConfiguration, userName str
resp = &GetUserResponse{}
for _, ident := range s3cfg.Identities {
if userName == ident.Name {
resp.GetUserResult.User = iam.User{UserName: &ident.Name}
resp.GetUserResult.User = iamlib.NewUser(ident.Name)
return resp, nil
}
}
@@ -618,9 +624,15 @@ func (iama *IamApiServer) GetPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url
}
policyId := Hash(&policyName)
path := "/"
defaultVersionId := policyDefaultVersionId
isAttachable := true
resp.GetPolicyResult.Policy.PolicyName = &policyName
resp.GetPolicyResult.Policy.Arn = &policyArn
resp.GetPolicyResult.Policy.PolicyId = &policyId
resp.GetPolicyResult.Policy.Path = &path
resp.GetPolicyResult.Policy.DefaultVersionId = &defaultVersionId
resp.GetPolicyResult.Policy.IsAttachable = &isAttachable
return resp, nil
}
@@ -692,6 +704,200 @@ func (iama *IamApiServer) ListPolicies(s3cfg *iam_pb.S3ApiConfiguration, values
return resp, nil
}
// CreatePolicyVersion replaces a managed policy's document with a new version.
// SeaweedFS keeps a single current document per managed policy (no version
// history), so the new document always becomes version "v1" / the default. This
// is what the AWS Terraform provider calls to update an aws_iam_policy in place.
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html
func (iama *IamApiServer) CreatePolicyVersion(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *CreatePolicyVersionResponse, iamError *IamError) {
resp = &CreatePolicyVersionResponse{}
policyArn := values.Get("PolicyArn")
policyName, iamError := parsePolicyArn(policyArn)
if iamError != nil {
return resp, iamError
}
policyDocumentString := values.Get("PolicyDocument")
if policyDocumentString == "" {
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("PolicyDocument is required")}
}
// SeaweedFS stores a single, always-default managed policy version. On AWS,
// SetAsDefault=false stages a non-default version without activating it; we
// can't honor that, so reject it rather than silently changing permissions.
if !strings.EqualFold(values.Get("SetAsDefault"), "true") {
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("SetAsDefault must be true: SeaweedFS stores a single managed policy version")}
}
policyDocument, err := GetPolicyDocument(&policyDocumentString)
if err != nil {
return resp, &IamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
}
if _, err := GetActions(&policyDocument); err != nil {
return resp, &IamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
}
policies := Policies{}
if err = iama.s3ApiConfig.GetPolicies(&policies); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
if _, exists := policies.Policies[policyName]; !exists {
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
policies.Policies[policyName] = policyDocument
if err = iama.s3ApiConfig.PutPolicies(&policies); err != nil {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
// The denormalized Identity.Actions caches were derived from the old
// document; refresh every identity that has this managed policy attached
// (directly or via group membership) so the new document takes effect.
recomputeActionsForManagedPolicy(iama, s3cfg, &policies, policyName)
versionId := policyDefaultVersionId
isDefault := true
document := policyDocumentString
resp.CreatePolicyVersionResult.PolicyVersion = iam.PolicyVersion{
VersionId: &versionId,
IsDefaultVersion: &isDefault,
Document: &document,
}
return resp, nil
}
// ListPolicyVersions lists the versions of a managed policy. SeaweedFS stores a
// single current document per policy, so exactly one version ("v1", the
// default) is reported.
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListPolicyVersions.html
func (iama *IamApiServer) ListPolicyVersions(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *ListPolicyVersionsResponse, iamError *IamError) {
resp = &ListPolicyVersionsResponse{}
policyName, iamError := parsePolicyArn(values.Get("PolicyArn"))
if iamError != nil {
return resp, iamError
}
policies := Policies{}
if err := iama.s3ApiConfig.GetPolicies(&policies); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
if _, exists := policies.Policies[policyName]; !exists {
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
versionId := policyDefaultVersionId
isDefault := true
resp.ListPolicyVersionsResult.Versions = []*iam.PolicyVersion{{
VersionId: &versionId,
IsDefaultVersion: &isDefault,
}}
resp.ListPolicyVersionsResult.IsTruncated = false
return resp, nil
}
// GetPolicyVersion returns the document for a managed policy version. Only the
// single stored version ("v1") exists.
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_GetPolicyVersion.html
func (iama *IamApiServer) GetPolicyVersion(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *GetPolicyVersionResponse, iamError *IamError) {
resp = &GetPolicyVersionResponse{}
policyName, iamError := parsePolicyArn(values.Get("PolicyArn"))
if iamError != nil {
return resp, iamError
}
versionId := values.Get("VersionId")
if versionId == "" {
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("VersionId is required")}
}
policies := Policies{}
if err := iama.s3ApiConfig.GetPolicies(&policies); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
policyDocument, exists := policies.Policies[policyName]
if !exists {
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
if versionId != policyDefaultVersionId {
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy version %s not found", versionId)}
}
policyDocumentJSON, err := json.Marshal(policyDocument)
if err != nil {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
isDefault := true
document := string(policyDocumentJSON)
resp.GetPolicyVersionResult.PolicyVersion = iam.PolicyVersion{
VersionId: &versionId,
IsDefaultVersion: &isDefault,
Document: &document,
}
return resp, nil
}
// DeletePolicyVersion is accepted for API completeness. With a single stored
// version that is always the default, the only valid responses are NoSuchEntity
// (unknown version) and the AWS "cannot delete the default version" conflict.
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeletePolicyVersion.html
func (iama *IamApiServer) DeletePolicyVersion(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *DeletePolicyVersionResponse, iamError *IamError) {
resp = &DeletePolicyVersionResponse{}
policyName, iamError := parsePolicyArn(values.Get("PolicyArn"))
if iamError != nil {
return resp, iamError
}
versionId := values.Get("VersionId")
if versionId == "" {
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("VersionId is required")}
}
policies := Policies{}
if err := iama.s3ApiConfig.GetPolicies(&policies); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
if _, exists := policies.Policies[policyName]; !exists {
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
if versionId == policyDefaultVersionId {
return resp, &IamError{Code: iam.ErrCodeDeleteConflictException, Error: fmt.Errorf("cannot delete the default version of policy %s", policyName)}
}
return resp, &IamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy version %s not found", versionId)}
}
// recomputeActionsForManagedPolicy refreshes Identity.Actions for every identity
// affected by a change to the managed policy named policyName: users with the
// policy attached directly, and members of groups the policy is attached to.
func recomputeActionsForManagedPolicy(iama *IamApiServer, s3cfg *iam_pb.S3ApiConfiguration, policies *Policies, policyName string) {
affected := make(map[string]*iam_pb.Identity)
identIndex := make(map[string]*iam_pb.Identity, len(s3cfg.Identities))
for _, ident := range s3cfg.Identities {
identIndex[ident.Name] = ident
for _, pn := range ident.PolicyNames {
if pn == policyName {
affected[ident.Name] = ident
break
}
}
}
for _, g := range s3cfg.Groups {
attached := false
for _, pn := range g.PolicyNames {
if pn == policyName {
attached = true
break
}
}
if !attached {
continue
}
for _, member := range g.Members {
if ident, ok := identIndex[member]; ok {
affected[member] = ident
}
}
}
for name, ident := range affected {
aggregatedActions, err := computeAllActionsForUser(iama, name, policies, ident, s3cfg)
if err != nil {
glog.Warningf("Failed to recompute actions for user %s after managed policy %s change: %v", name, policyName, err)
continue
}
ident.Actions = aggregatedActions
}
}
// AttachUserPolicy attaches a managed policy to a user.
func (iama *IamApiServer) AttachUserPolicy(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) (resp *AttachUserPolicyResponse, iamError *IamError) {
resp = &AttachUserPolicyResponse{}
@@ -1246,6 +1452,40 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
return
}
changed = false
case "CreatePolicyVersion":
var err *IamError
response, err = iama.CreatePolicyVersion(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
// CreatePolicyVersion persists the new document via PutPolicies and
// recomputes affected Identity.Actions on s3cfg; keep changed=true so the
// updated identities are saved.
case "ListPolicyVersions":
var err *IamError
response, err = iama.ListPolicyVersions(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
changed = false
case "GetPolicyVersion":
var err *IamError
response, err = iama.GetPolicyVersion(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
changed = false
case "DeletePolicyVersion":
var err *IamError
response, err = iama.DeletePolicyVersion(s3cfg, values)
if err != nil {
writeIamErrorResponse(w, r, reqID, err)
return
}
changed = false
case "AttachUserPolicy":
var err *IamError
response, err = iama.AttachUserPolicy(s3cfg, values)
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
@@ -631,6 +633,23 @@ func TestListAttachedUserPolicies(t *testing.T) {
assert.Equal(t, iam.ErrCodeNoSuchEntityException, iamErr.Code)
}
// TestUserArnIsValid is a regression test for issue #9786: the terraform aws
// provider (>= 6.41) reads a user back after creating it and blocks until
// GetUser returns a value that passes arn.IsARN.
func TestUserArnIsValid(t *testing.T) {
iama := newTestIamApiServer(Policies{})
s3cfg := &iam_pb.S3ApiConfiguration{}
createResp := iama.CreateUser(s3cfg, url.Values{"UserName": []string{"alice"}})
assert.True(t, arn.IsARN(aws.StringValue(createResp.CreateUserResult.User.Arn)),
"CreateUser must return a valid ARN, got %q", aws.StringValue(createResp.CreateUserResult.User.Arn))
getResp, iamErr := iama.GetUser(s3cfg, "alice")
assert.Nil(t, iamErr)
assert.True(t, arn.IsARN(aws.StringValue(getResp.GetUserResult.User.Arn)),
"GetUser must return a valid ARN, got %q", aws.StringValue(getResp.GetUserResult.User.Arn))
}
func TestCreateAccessKeyWithCallerSuppliedKeys(t *testing.T) {
iama := newTestIamApiServer(Policies{})
s3cfg := &iam_pb.S3ApiConfiguration{
+4
View File
@@ -27,6 +27,10 @@ type (
GetPolicyResponse = iamlib.GetPolicyResponse
DeletePolicyResponse = iamlib.DeletePolicyResponse
ListPoliciesResponse = iamlib.ListPoliciesResponse
ListPolicyVersionsResponse = iamlib.ListPolicyVersionsResponse
GetPolicyVersionResponse = iamlib.GetPolicyVersionResponse
CreatePolicyVersionResponse = iamlib.CreatePolicyVersionResponse
DeletePolicyVersionResponse = iamlib.DeletePolicyVersionResponse
AttachUserPolicyResponse = iamlib.AttachUserPolicyResponse
DetachUserPolicyResponse = iamlib.DetachUserPolicyResponse
ListAttachedUserPoliciesResponse = iamlib.ListAttachedUserPoliciesResponse
+170
View File
@@ -197,6 +197,176 @@ func TestCreatePolicy(t *testing.T) {
assert.Equal(t, http.StatusOK, response.Code)
}
// isolatedIamConfig is a self-contained IamS3ApiConfig backing whose state lives
// on the instance (not the package globals that executeRequest shares), so
// policy-version tests stay order-independent under -shuffle.
type isolatedIamConfig struct {
identities []*iam_pb.Identity
groups []*iam_pb.Group
policies Policies
}
func newIsolatedIamServer() *IamApiServer {
return &IamApiServer{s3ApiConfig: &isolatedIamConfig{
policies: Policies{Policies: make(map[string]policy_engine.PolicyDocument)},
}}
}
func (m *isolatedIamConfig) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
_ = copier.Copy(&s3cfg.Identities, &m.identities)
_ = copier.Copy(&s3cfg.Groups, &m.groups)
return nil
}
func (m *isolatedIamConfig) PutS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
_ = copier.Copy(&m.identities, &s3cfg.Identities)
_ = copier.Copy(&m.groups, &s3cfg.Groups)
return nil
}
func (m *isolatedIamConfig) GetPolicies(policies *Policies) error {
_ = copier.Copy(&policies, &m.policies)
return nil
}
func (m *isolatedIamConfig) PutPolicies(policies *Policies) error {
_ = copier.Copy(&m.policies, &policies)
return nil
}
// TestCreatePolicyVersion reproduces issue #9785: the AWS Terraform provider
// updates a managed policy in place via CreatePolicyVersion, which previously
// returned 501 NotImplemented. The whole read/update surface Terraform relies on
// is exercised here: GetPolicy (DefaultVersionId), CreatePolicyVersion,
// GetPolicyVersion and ListPolicyVersions.
func TestCreatePolicyVersion(t *testing.T) {
srv := newIsolatedIamServer()
svc := iam.New(session.New())
policyName := "tf-managed-policy"
policyArn := aws.String("arn:aws:iam:::policy/" + policyName)
// Create the managed policy.
createReq, _ := svc.CreatePolicyRequest(&iam.CreatePolicyInput{
PolicyName: aws.String(policyName),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*","s3:List*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = createReq.Build()
resp, err := executeRequestWith(srv, createReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
// Update it in place (what Terraform does). This used to return 501.
cpvReq, _ := svc.CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: policyArn,
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
SetAsDefault: aws.Bool(true),
})
_ = cpvReq.Build()
resp, err = executeRequestWith(srv, cpvReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
var cpvResp CreatePolicyVersionResponse
require.NoError(t, xml.Unmarshal(resp.Body.Bytes(), &cpvResp))
require.NotNil(t, cpvResp.CreatePolicyVersionResult.PolicyVersion.VersionId)
assert.Equal(t, "v1", *cpvResp.CreatePolicyVersionResult.PolicyVersion.VersionId)
require.NotNil(t, cpvResp.CreatePolicyVersionResult.PolicyVersion.IsDefaultVersion)
assert.True(t, *cpvResp.CreatePolicyVersionResult.PolicyVersion.IsDefaultVersion)
// GetPolicy must advertise a default version so Terraform's read can chain
// into GetPolicyVersion.
gpReq, _ := svc.GetPolicyRequest(&iam.GetPolicyInput{PolicyArn: policyArn})
_ = gpReq.Build()
resp, err = executeRequestWith(srv, gpReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
var gpResp GetPolicyResponse
require.NoError(t, xml.Unmarshal(resp.Body.Bytes(), &gpResp))
require.NotNil(t, gpResp.GetPolicyResult.Policy.DefaultVersionId)
assert.Equal(t, "v1", *gpResp.GetPolicyResult.Policy.DefaultVersionId)
// GetPolicyVersion must return the updated document (Get* only, List* gone).
gpvReq, _ := svc.GetPolicyVersionRequest(&iam.GetPolicyVersionInput{PolicyArn: policyArn, VersionId: aws.String("v1")})
_ = gpvReq.Build()
resp, err = executeRequestWith(srv, gpvReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
var gpvResp GetPolicyVersionResponse
require.NoError(t, xml.Unmarshal(resp.Body.Bytes(), &gpvResp))
require.NotNil(t, gpvResp.GetPolicyVersionResult.PolicyVersion.Document)
assert.Contains(t, *gpvResp.GetPolicyVersionResult.PolicyVersion.Document, "s3:Get*")
assert.NotContains(t, *gpvResp.GetPolicyVersionResult.PolicyVersion.Document, "s3:List*")
// ListPolicyVersions must report exactly the single default version.
lpvReq, _ := svc.ListPolicyVersionsRequest(&iam.ListPolicyVersionsInput{PolicyArn: policyArn})
_ = lpvReq.Build()
resp, err = executeRequestWith(srv, lpvReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
var lpvResp ListPolicyVersionsResponse
require.NoError(t, xml.Unmarshal(resp.Body.Bytes(), &lpvResp))
require.Len(t, lpvResp.ListPolicyVersionsResult.Versions, 1)
assert.Equal(t, "v1", *lpvResp.ListPolicyVersionsResult.Versions[0].VersionId)
}
// TestCreatePolicyVersionMissingPolicy verifies a NoSuchEntity (404) when the
// target policy does not exist, matching AWS.
func TestCreatePolicyVersionMissingPolicy(t *testing.T) {
srv := newIsolatedIamServer()
req, _ := iam.New(session.New()).CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: aws.String("arn:aws:iam:::policy/does-not-exist"),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
SetAsDefault: aws.Bool(true),
})
_ = req.Build()
resp, err := executeRequestWith(srv, req.HTTPRequest, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.Code)
code, _ := extractErrorCodeAndMessage(resp)
assert.Equal(t, "NoSuchEntity", code)
}
// TestCreatePolicyVersionRequiresSetAsDefault verifies that, given the
// single-version model, a request that does not set SetAsDefault=true is
// rejected rather than silently overwriting the active document.
func TestCreatePolicyVersionRequiresSetAsDefault(t *testing.T) {
srv := newIsolatedIamServer()
svc := iam.New(session.New())
policyArn := aws.String("arn:aws:iam:::policy/tf-managed-policy")
createReq, _ := svc.CreatePolicyRequest(&iam.CreatePolicyInput{
PolicyName: aws.String("tf-managed-policy"),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = createReq.Build()
resp, err := executeRequestWith(srv, createReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
// SetAsDefault omitted (defaults to false) must be rejected.
cpvReq, _ := svc.CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: policyArn,
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Put*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = cpvReq.Build()
resp, err = executeRequestWith(srv, cpvReq.HTTPRequest, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.Code)
code, _ := extractErrorCodeAndMessage(resp)
assert.Equal(t, "InvalidInput", code)
// The live document must be untouched (still Get*, not Put*).
gpvReq, _ := svc.GetPolicyVersionRequest(&iam.GetPolicyVersionInput{PolicyArn: policyArn, VersionId: aws.String("v1")})
_ = gpvReq.Build()
resp, err = executeRequestWith(srv, gpvReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
var gpvResp GetPolicyVersionResponse
require.NoError(t, xml.Unmarshal(resp.Body.Bytes(), &gpvResp))
require.NotNil(t, gpvResp.GetPolicyVersionResult.PolicyVersion.Document)
assert.Contains(t, *gpvResp.GetPolicyVersionResult.PolicyVersion.Document, "s3:Get*")
assert.NotContains(t, *gpvResp.GetPolicyVersionResult.PolicyVersion.Document, "s3:Put*")
}
func TestPutUserPolicy(t *testing.T) {
userName := aws.String("Test")
params := &iam.PutUserPolicyInput{
+36
View File
@@ -72,6 +72,7 @@ const (
metadataBeginBuild
metadataCompleteBuild
metadataAbortBuild
metadataPurgeDir
metadataShutdown
)
@@ -82,6 +83,7 @@ type metadataApplyRequest struct {
options MetadataResponseApplyOptions
buildPath util.FullPath
snapshotTsNs int64
resetFn func()
done chan error
}
@@ -272,6 +274,20 @@ func (mc *MetaCache) AbortDirectoryBuild(ctx context.Context, dirPath util.FullP
})
}
// PurgeDirectoryChildren asynchronously clears a directory's cached children and
// resets its cached flag (resetFn) via the apply loop. Asynchronous so callers
// like kernel Forget don't block; see purgeDirectoryChildrenNow for why off-loop
// callers must route through here rather than wiping the store directly.
func (mc *MetaCache) PurgeDirectoryChildren(dirPath util.FullPath, resetFn func()) {
_ = mc.enqueueApplyRequest(metadataApplyRequest{
ctx: context.Background(),
kind: metadataPurgeDir,
buildPath: dirPath,
resetFn: resetFn,
done: make(chan error, 1),
})
}
func (mc *MetaCache) UpdateEntry(ctx context.Context, entry *filer.Entry) error {
mc.Lock()
defer mc.Unlock()
@@ -465,6 +481,8 @@ func (mc *MetaCache) handleApplyRequest(req metadataApplyRequest) error {
return mc.completeDirectoryBuildNow(req.ctx, req.buildPath, req.snapshotTsNs)
case metadataAbortBuild:
return mc.abortDirectoryBuildNow(req.buildPath)
case metadataPurgeDir:
return mc.purgeDirectoryChildrenNow(req.ctx, req.buildPath, req.resetFn)
case metadataShutdown:
return nil
default:
@@ -621,6 +639,24 @@ func (mc *MetaCache) abortDirectoryBuildNow(dirPath util.FullPath) error {
return nil
}
// purgeDirectoryChildrenNow runs in the apply loop, serialized with
// completeDirectoryBuildNow's markCachedFn, so no build publish interleaves
// between resetFn (clears the cached flag) and the store wipe. Skipping a
// building directory avoids deleting entries the build inserted but hasn't yet
// published. Together these keep a directory from ending up flagged cached over
// an empty store — which hides every file in it though they remain on the filer.
func (mc *MetaCache) purgeDirectoryChildrenNow(ctx context.Context, dirPath util.FullPath, resetFn func()) error {
if mc.isBuildingDir(dirPath) {
return nil
}
if resetFn != nil {
resetFn()
}
mc.Lock()
defer mc.Unlock()
return mc.localStore.DeleteFolderChildren(ctx, dirPath)
}
func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util.FullPath, snapshotTsNs int64) error {
state := mc.buildingDirs[dirPath]
delete(mc.buildingDirs, dirPath)
@@ -0,0 +1,98 @@
package meta_cache
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func insertCacheEntry(t *testing.T, mc *MetaCache, path util.FullPath) {
t.Helper()
if err := mc.InsertEntry(context.Background(), &filer.Entry{
FullPath: path,
Attr: filer.Attr{
Crtime: time.Unix(1, 0),
Mtime: time.Unix(1, 0),
Mode: 0100644,
FileSize: 1,
},
}); err != nil {
t.Fatalf("insert %s: %v", path, err)
}
}
// barrier flushes the apply loop: enqueued before it, PurgeDirectoryChildren is
// asynchronous, so a synchronous apply-loop call afterward guarantees the purge
// has been processed (the loop is FIFO and single-threaded).
func barrier(t *testing.T, mc *MetaCache) {
t.Helper()
if err := mc.AbortDirectoryBuild(context.Background(), util.FullPath("/__barrier__")); err != nil {
t.Fatalf("barrier: %v", err)
}
}
// TestPurgeSkippedWhileDirectoryBuilding is the core regression guard: a purge
// (idle eviction / kernel Forget / copy-range fallback) that lands while a
// directory is being rebuilt must NOT wipe the entries the build just inserted.
// Otherwise CompleteDirectoryBuild marks the directory cached over an empty
// store, and every file in it vanishes from the mount though it is safe on the
// filer.
func TestPurgeSkippedWhileDirectoryBuilding(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true})
defer mc.Shutdown()
dir := util.FullPath("/dir")
if err := mc.BeginDirectoryBuild(context.Background(), dir); err != nil {
t.Fatalf("begin build: %v", err)
}
insertCacheEntry(t, mc, "/dir/a.txt")
insertCacheEntry(t, mc, "/dir/b.txt")
// A concurrent eviction tries to purge the directory mid-build. It is
// enqueued before CompleteDirectoryBuild, so the apply loop processes it
// first — while /dir is still building.
var resetCalls int32
mc.PurgeDirectoryChildren(dir, func() { atomic.AddInt32(&resetCalls, 1) })
if err := mc.CompleteDirectoryBuild(context.Background(), dir, 0); err != nil {
t.Fatalf("complete build: %v", err)
}
if got := atomic.LoadInt32(&resetCalls); got != 0 {
t.Fatalf("resetFn ran %d times during build; purge must be skipped", got)
}
if !mc.IsDirectoryCached(dir) {
t.Fatal("/dir should be cached after build completes")
}
for _, name := range []string{"/dir/a.txt", "/dir/b.txt"} {
if _, err := mc.FindEntry(context.Background(), util.FullPath(name)); err != nil {
t.Fatalf("%s missing after mid-build purge: %v", name, err)
}
}
}
// TestPurgeClearsWhenNotBuilding verifies the eviction path still works off the
// apply loop: with no build in flight, the purge resets the cached flag and
// wipes the store.
func TestPurgeClearsWhenNotBuilding(t *testing.T) {
mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true, "/dir": true})
defer mc.Shutdown()
dir := util.FullPath("/dir")
insertCacheEntry(t, mc, "/dir/a.txt")
var resetCalls int32
mc.PurgeDirectoryChildren(dir, func() { atomic.AddInt32(&resetCalls, 1) })
barrier(t, mc)
if got := atomic.LoadInt32(&resetCalls); got != 1 {
t.Fatalf("resetFn ran %d times; want 1", got)
}
if _, err := mc.FindEntry(context.Background(), util.FullPath("/dir/a.txt")); err == nil {
t.Fatal("/dir/a.txt should have been purged")
}
}
+18 -6
View File
@@ -505,10 +505,12 @@ func (wfs *WFS) StartBackgroundTasks() error {
startTime := time.Now()
go meta_cache.SubscribeMetaEvents(wfs.metaCache, wfs.signature, wfs, wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) {
glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err)
if deleteErr := wfs.metaCache.DeleteFolderChildren(context.Background(), util.FullPath(wfs.option.FilerMountRootPath)); deleteErr != nil {
glog.Warningf("meta cache cleanup failed: %v", deleteErr)
}
// A subscription gap may have dropped events, so distrust every cached
// listing. Reset the flags first (safe — it never deletes entries), then
// wipe the root's stale children through the apply loop so the delete
// cannot strand a concurrent rebuild cached-but-empty.
wfs.inodeToPath.InvalidateAllChildrenCache()
wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath))
}, follower)
go wfs.loopCheckQuota()
go wfs.loopFlushDirtyMetadata()
@@ -682,6 +684,9 @@ func (wfs *WFS) ClearCacheDir() {
os.RemoveAll(wfs.option.getUniqueCacheDirForRead())
}
// markDirectoryReadThrough drops a hot directory's cached listing. Only safe
// from the apply loop (onDirectoryUpdate), where it serializes with a build's
// markCachedFn; off-loop callers must use purgeDirectoryCache.
func (wfs *WFS) markDirectoryReadThrough(dirPath util.FullPath) {
if !wfs.inodeToPath.MarkDirectoryReadThrough(dirPath, time.Now()) {
return
@@ -691,6 +696,15 @@ func (wfs *WFS) markDirectoryReadThrough(dirPath util.FullPath) {
}
}
// purgeDirectoryCache drops a directory's cached listing from off the apply loop
// (idle eviction, kernel Forget, copy-range fallback), routing through it so a
// stale wipe can't strand a concurrently-rebuilt directory cached-but-empty.
func (wfs *WFS) purgeDirectoryCache(dirPath util.FullPath) {
wfs.metaCache.PurgeDirectoryChildren(dirPath, func() {
wfs.inodeToPath.InvalidateChildrenCache(dirPath)
})
}
func (wfs *WFS) loopEvictIdleDirCache() {
if wfs.dirIdleEvict <= 0 {
return
@@ -700,9 +714,7 @@ func (wfs *WFS) loopEvictIdleDirCache() {
for range ticker.C {
dirs := wfs.inodeToPath.CollectEvictableDirs(time.Now(), wfs.dirIdleEvict)
for _, dir := range dirs {
if err := wfs.metaCache.DeleteFolderChildren(context.Background(), dir); err != nil {
glog.V(2).Infof("evict dir cache %s: %v", dir, err)
}
wfs.purgeDirectoryCache(dir)
}
}
}
+1 -1
View File
@@ -267,7 +267,7 @@ func (wfs *WFS) updateServerSideWholeFileCopyMetaCache(dstPath util.FullPath, en
event := metadataUpdateEvent(dir, entry)
if applyErr := wfs.applyLocalMetadataEvent(context.Background(), event); applyErr != nil {
glog.Warningf("CopyFileRange metadata update %s: %v", dstPath, applyErr)
wfs.markDirectoryReadThrough(util.FullPath(dir))
wfs.purgeDirectoryCache(util.FullPath(dir))
}
}
+4 -3
View File
@@ -1,8 +1,6 @@
package mount
import (
"context"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -68,6 +66,9 @@ func (wfs *WFS) Forget(nodeid, nlookup uint64) {
// fhMap here would couple two unrelated refcounts and could tear down a
// still-live handle if Forget ever raced ahead of Release.
wfs.inodeToPath.Forget(nodeid, nlookup, func(dir util.FullPath) {
wfs.metaCache.DeleteFolderChildren(context.Background(), dir)
// Runs after Forget releases its lock; a concurrent lookup+rebuild can
// re-cache the directory in that window, so purge through the apply loop
// rather than wiping the store directly.
wfs.purgeDirectoryCache(dir)
})
}
+1
View File
@@ -542,6 +542,7 @@ message DiskStatus {
float percent_free = 5;
float percent_used = 6;
string disk_type = 7;
string error = 8;
}
message MemStatus {
+11 -2
View File
@@ -4565,6 +4565,7 @@ type DiskStatus struct {
PercentFree float32 `protobuf:"fixed32,5,opt,name=percent_free,json=percentFree,proto3" json:"percent_free,omitempty"`
PercentUsed float32 `protobuf:"fixed32,6,opt,name=percent_used,json=percentUsed,proto3" json:"percent_used,omitempty"`
DiskType string `protobuf:"bytes,7,opt,name=disk_type,json=diskType,proto3" json:"disk_type,omitempty"`
Error string `protobuf:"bytes,8,opt,name=error,proto3" json:"error,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -4648,6 +4649,13 @@ func (x *DiskStatus) GetDiskType() string {
return ""
}
func (x *DiskStatus) GetError() string {
if x != nil {
return x.Error
}
return ""
}
type MemStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Goroutines int32 `protobuf:"varint,1,opt,name=goroutines,proto3" json:"goroutines,omitempty"`
@@ -7298,7 +7306,7 @@ const file_volume_server_proto_rawDesc = "" +
"\vvolume_info\x18\n" +
" \x01(\v2\x1c.volume_server_pb.VolumeInfoR\n" +
"volumeInfo\x12\x18\n" +
"\aversion\x18\v \x01(\rR\aversion\"\xbb\x01\n" +
"\aversion\x18\v \x01(\rR\aversion\"\xd1\x01\n" +
"\n" +
"DiskStatus\x12\x10\n" +
"\x03dir\x18\x01 \x01(\tR\x03dir\x12\x10\n" +
@@ -7307,7 +7315,8 @@ const file_volume_server_proto_rawDesc = "" +
"\x04free\x18\x04 \x01(\x04R\x04free\x12!\n" +
"\fpercent_free\x18\x05 \x01(\x02R\vpercentFree\x12!\n" +
"\fpercent_used\x18\x06 \x01(\x02R\vpercentUsed\x12\x1b\n" +
"\tdisk_type\x18\a \x01(\tR\bdiskType\"\xa3\x01\n" +
"\tdisk_type\x18\a \x01(\tR\bdiskType\x12\x14\n" +
"\x05error\x18\b \x01(\tR\x05error\"\xa3\x01\n" +
"\tMemStatus\x12\x1e\n" +
"\n" +
"goroutines\x18\x01 \x01(\x05R\n" +
+138 -19
View File
@@ -267,17 +267,6 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, filerClient
if err := iam.loadS3ApiConfigurationFromFile(startConfigFile); err != nil {
glog.Fatalf("fail to load config file %s: %v", startConfigFile, err)
}
// Track identity names from static config to protect them from dynamic updates
// Must be done under lock to avoid race conditions
iam.m.Lock()
iam.useStaticConfig = true
iam.staticIdentityNames = make(map[string]bool)
for _, identity := range iam.identities {
iam.staticIdentityNames[identity.Name] = true
identity.IsStatic = true
}
iam.m.Unlock()
}
// Always try to load/merge config from credential manager (filer/db)
@@ -332,6 +321,30 @@ func NewIdentityAccessManagementWithStore(option *S3ApiServerOption, filerClient
return iam
}
// markStaticIdentities marks the identities declared in a static config file
// (-config, or -iam.config when it carries inline identities) as immutable, so
// dynamic filer reloads can't overwrite them. It is additive and scoped to the
// file's identities: a reload protects newly added ones without un-protecting
// the existing set or freezing dynamic filer-managed identities. useStaticConfig
// stays gated on whether any static identity exists, so an advanced-IAM file
// with no inline identities (OIDC/STS only) keeps the dynamic store live.
func (iam *IdentityAccessManagement) markStaticIdentities(config *iam_pb.S3ApiConfiguration) {
iam.m.Lock()
defer iam.m.Unlock()
if iam.staticIdentityNames == nil {
iam.staticIdentityNames = make(map[string]bool)
}
for _, ident := range config.Identities {
iam.staticIdentityNames[ident.Name] = true
}
for _, identity := range iam.identities {
if iam.staticIdentityNames[identity.Name] {
identity.IsStatic = true
}
}
iam.useStaticConfig = len(iam.staticIdentityNames) > 0
}
func (iam *IdentityAccessManagement) pollIamConfigChanges(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
@@ -477,24 +490,40 @@ func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName str
glog.Warningf("KMS initialization failed: %v", err)
}
return iam.LoadS3ApiConfigurationFromBytes(content)
config, err := iam.loadS3ApiConfigurationFromBytes(content)
if err != nil {
return err
}
// Identities listed in a config file are static (immutable). Mark them on
// every load so a reload protects newly added identities too, not just the
// set present at startup, and push the updated set into the credential
// manager so reloaded identities still show up in listings and survive
// later dynamic merges.
iam.markStaticIdentities(config)
iam.updateCredentialManagerStaticIdentities()
return nil
}
func (iam *IdentityAccessManagement) LoadS3ApiConfigurationFromBytes(content []byte) error {
_, err := iam.loadS3ApiConfigurationFromBytes(content)
return err
}
func (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []byte) (*iam_pb.S3ApiConfiguration, error) {
s3ApiConfiguration := &iam_pb.S3ApiConfiguration{}
if err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {
glog.Warningf("unmarshal error: %v", err)
return fmt.Errorf("unmarshal error: %w", err)
return nil, fmt.Errorf("unmarshal error: %w", err)
}
if err := filer.CheckDuplicateAccessKey(s3ApiConfiguration); err != nil {
return err
return nil, err
}
if err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {
return err
return nil, err
}
return nil
return s3ApiConfiguration, nil
}
func (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {
@@ -1459,6 +1488,15 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
object = prefix
}
// Batch DeleteObjects keys arrive in the body, not the URL: a bucket-level check
// here can't match object-scoped policies. DeleteMultipleObjectsHandler authorizes
// each key via AuthorizeBatchDeleteKey.
if action == s3_constants.ACTION_WRITE && r.Method == http.MethodPost &&
object == "" && r.URL.Query().Has("delete") {
r.Header.Set(s3_constants.AmzAccountId, identity.Account.Id)
return identity, s3err.ErrNone, reqAuthType
}
// For ListBuckets, authorization is performed in the handler by iterating
// through buckets and checking permissions for each. Skip the global check here.
policyAllows := false
@@ -1487,7 +1525,14 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
if identity != nil {
claims = identity.Claims
}
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, object, string(action), principal, r, claims, nil)
// List is bucket-level; the prefix promoted into object (for the
// legacy CanDo path) must not scope the resource ARN. Prefix is
// matched via the s3:prefix Condition.
policyObject := object
if action == s3_constants.ACTION_LIST {
policyObject = ""
}
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, policyObject, string(action), principal, r, claims, nil)
if err != nil {
// SECURITY: Fail-close on policy evaluation errors
@@ -2165,9 +2210,16 @@ func (iam *IdentityAccessManagement) evaluateIAMPolicies(r *http.Request, identi
return false
}
resource := buildResourceARN(bucket, object)
// List is bucket-level; the prefix promoted into object (for the legacy
// CanDo path) must not scope the resource ARN or the resolved action
// (e.g. ListBucketVersions on ?versions). Prefix is matched via s3:prefix.
resourceObject := object
if action == s3_constants.ACTION_LIST {
resourceObject = ""
}
resource := buildResourceARN(bucket, resourceObject)
principal := buildPrincipalARN(identity, r)
s3Action := ResolveS3Action(r, string(action), bucket, object)
s3Action := ResolveS3Action(r, string(action), bucket, resourceObject)
explicitAllow := false
conditions := policy_engine.ExtractConditionValuesFromRequest(r)
for k, v := range policy_engine.ExtractPrincipalVariables(principal) {
@@ -2334,6 +2386,73 @@ func (iam *IdentityAccessManagement) AuthorizeCopySource(r *http.Request, identi
return iam.VerifyActionPermission(srcReq, identity, Action(action), srcBucket, srcObject)
}
// AuthorizeBatchDeleteKey authorizes one key from a DeleteObjects body. The route
// Auth middleware only authenticated the caller (keys arrive in the body, not the
// URL), so each key is checked here against a synthetic DELETE /<bucket>/<key> that
// makes ResolveS3Action and buildResourceARN target the object. Mirrors AuthorizeCopySource.
func (iam *IdentityAccessManagement) AuthorizeBatchDeleteKey(r *http.Request, identity *Identity, bucket, objectKey, versionId string) s3err.ErrorCode {
if !iam.isEnabled() {
return s3err.ErrNone
}
if bucket == "" || objectKey == "" {
return s3err.ErrNone
}
if identity == nil {
return s3err.ErrAccessDenied
}
if identity.isAdmin() {
return s3err.ErrNone
}
// Shallow copy: authorization only reads headers, and this runs once per key.
keyReq := new(http.Request)
*keyReq = *r
keyURL := &url.URL{
Scheme: r.URL.Scheme,
Host: r.URL.Host,
Path: "/" + bucket + "/" + objectKey,
}
// Build the query from scratch so the envelope's "delete" param can't steer
// ResolveS3Action; keep the STS token and per-key versionId for policy eval.
keyQuery := make(url.Values)
if versionId != "" {
keyQuery.Set("versionId", versionId)
}
if strings.Contains(r.URL.RawQuery, "X-Amz-Security-Token") {
if token := r.URL.Query().Get("X-Amz-Security-Token"); token != "" {
keyQuery.Set("X-Amz-Security-Token", token)
}
}
if len(keyQuery) > 0 {
keyURL.RawQuery = keyQuery.Encode()
}
keyReq.URL = keyURL
keyReq.Method = http.MethodDelete
keyReq.RequestURI = ""
keyReq.Body = nil
keyReq.GetBody = nil
keyReq.ContentLength = 0
action := s3_constants.ACTION_WRITE
if iam.policyEngine != nil {
principal := buildPrincipalARN(identity, keyReq)
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, objectKey, action, principal, keyReq, identity.Claims, nil)
if err != nil {
glog.Errorf("DeleteObjects key policy evaluation failed for %s/%s: %v - denying", bucket, objectKey, err)
return s3err.ErrAccessDenied
}
if evaluated {
if allowed {
return s3err.ErrNone
}
return s3err.ErrAccessDenied
}
}
return iam.VerifyActionPermission(keyReq, identity, Action(action), bucket, objectKey)
}
// authorizeWithIAM authorizes requests using the IAM integration policy engine
func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity *Identity, action Action, bucket string, object string) s3err.ErrorCode {
ctx := r.Context()
@@ -0,0 +1,125 @@
package s3api
import (
"context"
"os"
"path/filepath"
"testing"
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
)
// An advanced -iam.config file (STS/OIDC/roles) carries no inline identities, so the
// server must not enter static-config mode. Otherwise it freezes live reloads and
// filer-backed identities created at runtime (e.g. by the operator's IAM CRDs) never
// take effect.
func TestIamConfigWithoutIdentitiesIsNotStatic(t *testing.T) {
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"sts":{"signingKey":"dGVzdC1zaWduaW5nLWtleQ=="}}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load advanced iam config: %v", err)
}
if s3a.iam.IsStaticConfig() {
t.Fatalf("advanced iam config without identities must not be treated as static")
}
// A filer change (operator creating a user) must still reload at runtime.
if err := s3a.iam.credentialManager.CreateUser(context.Background(), &iam_pb.Identity{Name: "alice"}); err != nil {
t.Fatalf("failed to create alice: %v", err)
}
if err := s3a.onIamConfigChange(filer.IamConfigDirectory+"/identities", nil, &filer_pb.Entry{Name: "alice.json"}); err != nil {
t.Fatalf("onIamConfigChange returned error: %v", err)
}
if !hasIdentity(s3a.iam, "alice") {
t.Fatalf("expected alice to load after filer change with -iam.config-only setup")
}
}
// A -config identity file marks its identities static, protecting them and keeping the
// established behavior of not live-reloading those from the filer.
func TestConfigWithIdentitiesIsStatic(t *testing.T) {
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
path := writeTempIamConfig(t, `{"identities":[{"name":"static-admin","credentials":[{"accessKey":"AKIAITEST","secretKey":"c2VjcmV0"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(path); err != nil {
t.Fatalf("failed to load identity config: %v", err)
}
if !s3a.iam.IsStaticConfig() {
t.Fatalf("config file with inline identities must be treated as static")
}
s3a.iam.m.RLock()
id := s3a.iam.nameToIdentity["static-admin"]
s3a.iam.m.RUnlock()
if id == nil || !id.IsStatic {
t.Fatalf("expected static-admin to be marked static")
}
// A static identity file does not live-reload dynamic identities from the filer.
if err := s3a.iam.credentialManager.CreateUser(context.Background(), &iam_pb.Identity{Name: "alice"}); err != nil {
t.Fatalf("failed to create alice: %v", err)
}
if err := s3a.onIamConfigChange(filer.IamConfigDirectory+"/identities", nil, &filer_pb.Entry{Name: "alice.json"}); err != nil {
t.Fatalf("onIamConfigChange returned error: %v", err)
}
if hasIdentity(s3a.iam, "alice") {
t.Fatalf("did not expect alice to load while running off a static identity file")
}
}
// Reloading the static config file (grace.OnReload) must mark newly added
// identities as static so dynamic filer updates can't overwrite them, while
// leaving already-loaded dynamic (filer-managed) identities untouched.
func TestReloadStaticConfigMarksNewIdentitiesWithoutFreezingDynamic(t *testing.T) {
s3a := newTestS3ApiServerWithMemoryIAM(t, []*iam_pb.Identity{})
p1 := writeTempIamConfig(t, `{"identities":[{"name":"static-admin","credentials":[{"accessKey":"AKADMIN0","secretKey":"c2VjcmV0"}],"actions":["Admin"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(p1); err != nil {
t.Fatalf("failed to load initial config: %v", err)
}
// A dynamic identity arrives from the filer; merge mode keeps it dynamic.
if err := s3a.iam.credentialManager.CreateUser(context.Background(), &iam_pb.Identity{Name: "alice"}); err != nil {
t.Fatalf("failed to create alice: %v", err)
}
if err := s3a.iam.LoadS3ApiConfigurationFromCredentialManager(); err != nil {
t.Fatalf("failed to load from credential manager: %v", err)
}
if !hasIdentity(s3a.iam, "alice") {
t.Fatalf("expected alice to load dynamically")
}
// Reload the static file with a new identity bob.
p2 := writeTempIamConfig(t, `{"identities":[{"name":"static-admin","credentials":[{"accessKey":"AKADMIN0","secretKey":"c2VjcmV0"}],"actions":["Admin"]},{"name":"bob","credentials":[{"accessKey":"AKBOB000","secretKey":"c2VjcmV0"}],"actions":["Read"]}]}`)
if err := s3a.iam.loadS3ApiConfigurationFromFile(p2); err != nil {
t.Fatalf("failed to reload config: %v", err)
}
if !isStaticName(s3a.iam, "bob") {
t.Fatalf("expected reloaded identity bob to be marked static")
}
if isStaticName(s3a.iam, "alice") {
t.Fatalf("dynamic identity alice must not be frozen as static by a config reload")
}
}
func isStaticName(iam *IdentityAccessManagement, name string) bool {
iam.m.RLock()
defer iam.m.RUnlock()
return iam.staticIdentityNames[name]
}
func writeTempIamConfig(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "iam.json")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("failed to write temp config: %v", err)
}
return path
}
+93
View File
@@ -0,0 +1,93 @@
package s3api
import (
"encoding/json"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/stretchr/testify/require"
)
// TestAuthorizeBatchDeleteKey_AwsCanonicalPolicy: a policy granting s3:DeleteObject
// on <bucket>/* must allow per-key batch deletes. Pre-fix the bucket-level check
// built arn:aws:s3:::<bucket> and never matched the object-scoped policy.
func TestAuthorizeBatchDeleteKey_AwsCanonicalPolicy(t *testing.T) {
const bucket = "test-bucket"
const policyName = "delete-test-bucket-objects"
policyDoc, err := json.Marshal(map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{
{
"Effect": "Allow",
"Action": "s3:DeleteObject",
"Resource": "arn:aws:s3:::" + bucket + "/*",
},
},
})
require.NoError(t, err)
iam := &IdentityAccessManagement{
isAuthEnabled: true,
}
require.NoError(t, iam.PutPolicy(policyName, string(policyDoc)))
identity := &Identity{
Name: "alice",
Account: &AccountAdmin,
PolicyNames: []string{policyName},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
r := httptest.NewRequest("POST", "/"+bucket+"?delete", nil)
require.Equal(t, s3err.ErrNone,
iam.AuthorizeBatchDeleteKey(r, identity, bucket, "objects/a.txt", ""),
"s3:DeleteObject on arn:aws:s3:::%s/* must allow deleting %s/objects/a.txt", bucket, bucket)
require.Equal(t, s3err.ErrAccessDenied,
iam.AuthorizeBatchDeleteKey(r, identity, "other-bucket", "objects/a.txt", ""),
"keys outside the granted bucket must be denied")
}
// TestAuthorizeBatchDeleteKey_PrefixScopedPolicy: a prefix-scoped policy must allow
// batch deletes under the prefix and deny keys outside it, per-key.
func TestAuthorizeBatchDeleteKey_PrefixScopedPolicy(t *testing.T) {
const bucket = "test-bucket"
const policyName = "delete-prefix-only"
policyDoc, err := json.Marshal(map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{
{
"Effect": "Allow",
"Action": "s3:DeleteObject",
"Resource": "arn:aws:s3:::" + bucket + "/safe/*",
},
},
})
require.NoError(t, err)
iam := &IdentityAccessManagement{
isAuthEnabled: true,
}
require.NoError(t, iam.PutPolicy(policyName, string(policyDoc)))
identity := &Identity{
Name: "alice",
Account: &AccountAdmin,
PolicyNames: []string{policyName},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
r := httptest.NewRequest("POST", "/"+bucket+"?delete", nil)
require.Equal(t, s3err.ErrNone,
iam.AuthorizeBatchDeleteKey(r, identity, bucket, "safe/inside.txt", ""),
"key under granted prefix must be allowed")
require.Equal(t, s3err.ErrAccessDenied,
iam.AuthorizeBatchDeleteKey(r, identity, bucket, "danger/outside.txt", ""),
"key outside the granted prefix must be denied per-key, not at the batch level")
}
@@ -0,0 +1,114 @@
package s3api
import (
"encoding/json"
"net/http/httptest"
"testing"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/stretchr/testify/require"
)
// ListObjects requests carry their key scope in the ?prefix= query parameter,
// which authRequestWithAuthType promotes into object so the legacy CanDo path
// can honor prefix-scoped Action strings. That promoted object must not reach
// the policy resource ARN: s3:ListBucket is a bucket-level action, so the
// resource stays arn:aws:s3:::bucket and any prefix scoping is expressed via
// the s3:prefix Condition.
func TestEvaluateIAMPolicies_ListBucketWithPrefix(t *testing.T) {
const bucket = "test-bucket"
iam := &IdentityAccessManagement{}
require.NoError(t, iam.PutPolicy("list-bucket", mustPolicy(t, map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::" + bucket,
}},
})))
identity := &Identity{
Name: "alice",
Account: &AccountAdmin,
PolicyNames: []string{"list-bucket"},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
// authRequestWithAuthType promotes prefix into object before reaching the
// IAM evaluator; pass the post-promotion value to mirror that flow.
withPrefix := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=foo/", nil)
require.True(t, iam.evaluateIAMPolicies(withPrefix, identity, s3_constants.ACTION_LIST, bucket, "foo/"),
"s3:ListBucket on the bucket ARN must allow listing with a prefix")
noPrefix := httptest.NewRequest("GET", "/"+bucket+"?list-type=2", nil)
require.True(t, iam.evaluateIAMPolicies(noPrefix, identity, s3_constants.ACTION_LIST, bucket, ""),
"s3:ListBucket on the bucket ARN must allow listing without a prefix")
}
// Prefix scoping still works once it moves to the Condition: a policy that
// grants s3:ListBucket on the bucket only under an s3:prefix StringLike must
// allow a matching prefix and deny a non-matching one.
func TestEvaluateIAMPolicies_ListBucketPrefixCondition(t *testing.T) {
const bucket = "test-bucket"
iam := &IdentityAccessManagement{}
require.NoError(t, iam.PutPolicy("list-scoped", mustPolicy(t, map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::" + bucket,
"Condition": map[string]any{"StringLike": map[string]any{"s3:prefix": "warehouse/*"}},
}},
})))
identity := &Identity{
Name: "bob",
Account: &AccountAdmin,
PolicyNames: []string{"list-scoped"},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
matching := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=warehouse/data", nil)
require.True(t, iam.evaluateIAMPolicies(matching, identity, s3_constants.ACTION_LIST, bucket, "warehouse/data"),
"prefix matching the s3:prefix condition must be allowed")
nonMatching := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=secrets/", nil)
require.False(t, iam.evaluateIAMPolicies(nonMatching, identity, s3_constants.ACTION_LIST, bucket, "secrets/"),
"prefix outside the s3:prefix condition must be denied")
}
// Listing variants keep their specific action even when a prefix is promoted
// into object: ?versions resolves to s3:ListBucketVersions, not s3:ListBucket.
func TestEvaluateIAMPolicies_ListBucketVersionsWithPrefix(t *testing.T) {
const bucket = "test-bucket"
iam := &IdentityAccessManagement{}
require.NoError(t, iam.PutPolicy("list-versions", mustPolicy(t, map[string]any{
"Version": "2012-10-17",
"Statement": []map[string]any{{
"Effect": "Allow",
"Action": "s3:ListBucketVersions",
"Resource": "arn:aws:s3:::" + bucket,
}},
})))
identity := &Identity{
Name: "carol",
Account: &AccountAdmin,
PolicyNames: []string{"list-versions"},
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
}
r := httptest.NewRequest("GET", "/"+bucket+"?versions&prefix=foo/", nil)
require.True(t, iam.evaluateIAMPolicies(r, identity, s3_constants.ACTION_LIST, bucket, "foo/"),
"s3:ListBucketVersions must still resolve when listing with a prefix")
}
func mustPolicy(t *testing.T, doc map[string]any) string {
t.Helper()
b, err := json.Marshal(doc)
require.NoError(t, err)
return string(b)
}
+39
View File
@@ -308,6 +308,45 @@ func ValidateAndTransferGrants(accountManager AccountManager, grants []*s3.Grant
return result, s3err.ErrNone
}
// buildAccessControlList converts stored ACP grants into the XML response form.
// When no grants are stored it falls back to a single full-control grant for the
// owner, matching AWS's default private ACL.
func buildAccessControlList(accountManager AccountManager, grants []*s3.Grant, ownerId, ownerDisplayName string) AccessControlList {
if len(grants) == 0 {
return AccessControlList{Grant: []Grant{{
Grantee: Grantee{
ID: ownerId,
DisplayName: ownerDisplayName,
Type: "CanonicalUser",
XMLXSI: "CanonicalUser",
XMLNS: "http://www.w3.org/2001/XMLSchema-instance",
},
Permission: Permission(s3_constants.PermissionFullControl),
}}}
}
var acl AccessControlList
for _, grant := range grants {
localGrant := Grant{Permission: Permission(*grant.Permission)}
if grant.Grantee != nil {
localGrant.Grantee = Grantee{
Type: *grant.Grantee.Type,
XMLXSI: *grant.Grantee.Type,
XMLNS: "http://www.w3.org/2001/XMLSchema-instance",
}
if grant.Grantee.ID != nil {
localGrant.Grantee.ID = *grant.Grantee.ID
localGrant.Grantee.DisplayName = accountManager.GetAccountNameById(*grant.Grantee.ID)
}
if grant.Grantee.URI != nil {
localGrant.Grantee.URI = *grant.Grantee.URI
}
}
acl.Grant = append(acl.Grant, localGrant)
}
return acl
}
// GetAcpGrants return grants parsed from entry
func GetAcpGrants(entryExtended map[string][]byte) []*s3.Grant {
acpBytes, ok := entryExtended[s3_constants.ExtAmzAclKey]
+133 -65
View File
@@ -165,6 +165,29 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
// Get authenticated identity from context (secure, cannot be spoofed)
currentIdentityId := s3_constants.GetIdentityNameFromContext(r)
// Parse any requested bucket ACL (canned ACL or grant headers) up front so it
// can be validated, persisted on creation, and factored into the already-exists
// response. A "private" canned ACL is the default and counts as no explicit ACL.
requestHasACL := hasExplicitBucketACL(r)
var aclGrantsBytes []byte
if requestHasACL {
accountId := getAccountId(r)
_, grants, errCode := ParseAndValidateAclHeaders(r, s3a.iam, "", accountId, accountId, false)
if errCode != s3err.ErrNone {
s3err.WriteErrorResponse(w, r, errCode)
return
}
if len(grants) > 0 {
grantsBytes, err := json.Marshal(grants)
if err != nil {
glog.Errorf("PutBucketHandler: marshal ACL grants for %s: %v", bucket, err)
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
return
}
aclGrantsBytes = grantsBytes
}
}
// Check collection existence first
collectionExists := false
if s3a.isTableBucket(bucket) {
@@ -192,54 +215,11 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
return
}
// Check bucket directory existence and get metadata
// Bucket already exists: report whether the caller already owns it or the
// name is taken / the request conflicts.
if exist, err := s3a.exists(s3a.option.BucketsPath, bucket, true); err == nil && exist {
// Bucket exists, check ownership and settings
if entry, err := s3a.getEntry(s3a.option.BucketsPath, bucket); err == nil {
// Get existing bucket owner
var existingOwnerId string
if entry.Extended != nil {
if id, ok := entry.Extended[s3_constants.AmzIdentityId]; ok {
existingOwnerId = string(id)
}
}
// Check ownership
if existingOwnerId != "" && existingOwnerId != currentIdentityId {
// Different owner - always fail with BucketAlreadyExists
glog.V(3).Infof("PutBucketHandler: bucket %s owned by %s, requested by %s", bucket, existingOwnerId, currentIdentityId)
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
return
}
// Same owner or no owner set - check for conflicting settings
objectLockRequested := strings.EqualFold(r.Header.Get(s3_constants.AmzBucketObjectLockEnabled), "true")
// Get current bucket configuration
bucketConfig, errCode := s3a.getBucketConfig(bucket)
if errCode != s3err.ErrNone {
glog.Errorf("PutBucketHandler: failed to get bucket config for %s: %v", bucket, errCode)
// If we can't get config, assume no conflict and allow recreation
} else {
// Check for Object Lock conflict
currentObjectLockEnabled := bucketConfig.ObjectLockConfig != nil &&
bucketConfig.ObjectLockConfig.ObjectLockEnabled == s3_constants.ObjectLockEnabled
if objectLockRequested != currentObjectLockEnabled {
// Conflicting Object Lock settings - fail with BucketAlreadyExists
glog.V(3).Infof("PutBucketHandler: bucket %s has conflicting Object Lock settings (requested: %v, current: %v)",
bucket, objectLockRequested, currentObjectLockEnabled)
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
return
}
}
// Bucket already exists - always return BucketAlreadyExists per S3 specification
// The S3 tests expect BucketAlreadyExists in all cases, not BucketAlreadyOwnedByYou
glog.V(3).Infof("PutBucketHandler: bucket %s already exists", bucket)
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
return
}
s3err.WriteErrorResponse(w, r, s3a.existingBucketError(r, bucket, currentIdentityId, requestHasACL))
return
}
// If collection exists but bucket directory doesn't, this is an inconsistent state
@@ -265,6 +245,15 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
// Set bucket owner
setBucketOwner(r)(entry)
// Persist a requested non-default ACL so GetBucketAcl and idempotent
// recreation observe it (private is the default and is not stored).
if len(aclGrantsBytes) > 0 {
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
entry.Extended[s3_constants.ExtAmzAclKey] = aclGrantsBytes
}
// Set Object Lock configuration atomically during bucket creation
if objectLockEnabled {
glog.V(3).Infof("PutBucketHandler: enabling Object Lock and Versioning for bucket %s atomically", bucket)
@@ -290,10 +279,10 @@ func (s3a *S3ApiServer) PutBucketHandler(w http.ResponseWriter, r *http.Request)
}
}); err != nil {
// If mkdir failed because another request created the bucket concurrently,
// return BucketAlreadyExists instead of InternalError.
// return the appropriate already-exists error instead of InternalError.
if exist, checkErr := s3a.exists(s3a.option.BucketsPath, bucket, true); checkErr == nil && exist {
glog.V(3).Infof("PutBucketHandler: bucket %s was created concurrently", bucket)
s3err.WriteErrorResponse(w, r, s3err.ErrBucketAlreadyExists)
s3err.WriteErrorResponse(w, r, s3a.existingBucketError(r, bucket, currentIdentityId, requestHasACL))
return
}
glog.Errorf("PutBucketHandler mkdir: %v", err)
@@ -497,16 +486,93 @@ var ErrAutoCreatePermissionDenied = errors.New("permission denied - requires Adm
// ErrInvalidBucketName is returned when a bucket name doesn't meet S3 naming requirements
var ErrInvalidBucketName = errors.New("invalid bucket name")
// existingBucketError returns the error for a PutBucket whose target bucket
// already exists: BucketAlreadyOwnedByYou for an idempotent recreate by the
// owner, or BucketAlreadyExists when the name is owned by someone else or the
// request conflicts with the existing bucket (a different Object Lock setting,
// or an ACL on the request or the existing bucket).
func (s3a *S3ApiServer) existingBucketError(r *http.Request, bucket, currentIdentityId string, requestHasACL bool) s3err.ErrorCode {
entry, err := s3a.getEntry(s3a.option.BucketsPath, bucket)
if err != nil {
// We just observed the bucket exists but can't read it; report it as taken.
glog.Errorf("PutBucketHandler: failed to read existing bucket %s: %v", bucket, err)
return s3err.ErrBucketAlreadyExists
}
var existingOwnerId string
if entry.Extended != nil {
if id, ok := entry.Extended[s3_constants.AmzIdentityId]; ok {
existingOwnerId = string(id)
}
}
// Different owner: the name is taken in the shared namespace.
if existingOwnerId != "" && existingOwnerId != currentIdentityId {
glog.V(3).Infof("PutBucketHandler: bucket %s owned by %s, requested by %s", bucket, existingOwnerId, currentIdentityId)
return s3err.ErrBucketAlreadyExists
}
// Same owner (or an unowned bucket the caller can claim). Recreating your own
// bucket is idempotent and returns BucketAlreadyOwnedByYou, unless the request
// conflicts with the existing bucket: a different Object Lock setting, or an ACL
// on the request or the existing bucket.
// (s3-tests: test_bucket_create_exists vs test_bucket_recreate_*_acl.)
if requestHasACL {
return s3err.ErrBucketAlreadyExists
}
objectLockRequested := strings.EqualFold(r.Header.Get(s3_constants.AmzBucketObjectLockEnabled), "true")
bucketConfig, errCode := s3a.getBucketConfig(bucket)
if errCode != s3err.ErrNone {
// Can't read the existing bucket's settings, so we can't tell whether this
// recreate conflicts; surface the failure instead of assuming idempotency.
glog.Errorf("PutBucketHandler: failed to get bucket config for %s: %v", bucket, errCode)
return errCode
}
currentObjectLockEnabled := bucketConfig.ObjectLockConfig != nil &&
bucketConfig.ObjectLockConfig.ObjectLockEnabled == s3_constants.ObjectLockEnabled
if objectLockRequested != currentObjectLockEnabled || len(bucketConfig.ACL) > 0 {
glog.V(3).Infof("PutBucketHandler: bucket %s already exists", bucket)
return s3err.ErrBucketAlreadyExists
}
glog.V(3).Infof("PutBucketHandler: bucket %s already owned by requester", bucket)
return s3err.ErrBucketAlreadyOwnedByYou
}
// hasExplicitBucketACL reports whether the request carries an explicit, non-default
// bucket ACL via a canned ACL header (other than "private") or grant headers.
func hasExplicitBucketACL(r *http.Request) bool {
if canned := r.Header.Get(s3_constants.AmzCannedAcl); canned != "" && !strings.EqualFold(canned, s3_constants.CannedAclPrivate) {
return true
}
for _, h := range []string{s3_constants.AmzAclFullControl, s3_constants.AmzAclRead, s3_constants.AmzAclReadAcp, s3_constants.AmzAclWrite, s3_constants.AmzAclWriteAcp} {
if r.Header.Get(h) != "" {
return true
}
}
return false
}
// setBucketOwner creates a function that sets the bucket owner from the request context
func setBucketOwner(r *http.Request) func(entry *filer_pb.Entry) {
currentIdentityId := s3_constants.GetIdentityNameFromContext(r)
// Record the canonical account id too so GetBucketAcl can report the bucket
// owner instead of whoever is reading (e.g. an admin or another account).
accountId := r.Header.Get(s3_constants.AmzAccountId)
return func(entry *filer_pb.Entry) {
if currentIdentityId == "" && accountId == "" {
return
}
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
if currentIdentityId != "" {
if entry.Extended == nil {
entry.Extended = make(map[string][]byte)
}
entry.Extended[s3_constants.AmzIdentityId] = []byte(currentIdentityId)
}
if accountId != "" {
entry.Extended[s3_constants.ExtAmzOwnerKey] = []byte(accountId)
}
}
}
@@ -722,23 +788,25 @@ func (s3a *S3ApiServer) GetBucketAclHandler(w http.ResponseWriter, r *http.Reque
return
}
amzAccountId := r.Header.Get(s3_constants.AmzAccountId)
amzDisplayName := s3a.iam.GetAccountNameById(amzAccountId)
// Report the bucket's owner (recorded at creation or by PutBucketAcl), not the
// caller; fall back to the caller only when no owner was persisted. Likewise
// return any stored ACL, defaulting to the owner's full-control grant.
ownerId := r.Header.Get(s3_constants.AmzAccountId)
var storedGrants []*s3.Grant
if bucketConfig, errCode := s3a.getBucketConfig(bucket); errCode == s3err.ErrNone && bucketConfig.Entry != nil {
storedGrants = GetAcpGrants(bucketConfig.Entry.Extended)
if bucketConfig.Owner != "" {
ownerId = bucketConfig.Owner
}
}
ownerDisplayName := s3a.iam.GetAccountNameById(ownerId)
response := AccessControlPolicy{
Owner: CanonicalUser{
ID: amzAccountId,
DisplayName: amzDisplayName,
ID: ownerId,
DisplayName: ownerDisplayName,
},
AccessControlList: buildAccessControlList(s3a.iam, storedGrants, ownerId, ownerDisplayName),
}
response.AccessControlList.Grant = append(response.AccessControlList.Grant, Grant{
Grantee: Grantee{
ID: amzAccountId,
DisplayName: amzDisplayName,
Type: "CanonicalUser",
XMLXSI: "CanonicalUser",
XMLNS: "http://www.w3.org/2001/XMLSchema-instance"},
Permission: s3.PermissionFullControl,
})
writeSuccessResponseXML(w, r, response)
}
@@ -35,6 +35,32 @@ func newBucketRequest(method, bucket, query, body string) *http.Request {
return req
}
func TestHasExplicitBucketACL(t *testing.T) {
cases := []struct {
name string
headers map[string]string
want bool
}{
{name: "none", headers: nil, want: false},
{name: "private is default", headers: map[string]string{s3_constants.AmzCannedAcl: "private"}, want: false},
{name: "canned public-read", headers: map[string]string{s3_constants.AmzCannedAcl: "public-read"}, want: true},
{name: "canned case-insensitive private", headers: map[string]string{s3_constants.AmzCannedAcl: "PRIVATE"}, want: false},
{name: "grant read", headers: map[string]string{s3_constants.AmzAclRead: `id="x"`}, want: true},
{name: "grant full control", headers: map[string]string{s3_constants.AmzAclFullControl: `id="x"`}, want: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
req := newBucketRequest(http.MethodPut, "b", "", "")
for k, v := range tc.headers {
req.Header.Set(k, v)
}
if got := hasExplicitBucketACL(req); got != tc.want {
t.Fatalf("hasExplicitBucketACL = %v, want %v", got, tc.want)
}
})
}
}
func TestGetBucketPolicyStatusIsPublic(t *testing.T) {
cases := []struct {
name string
+105 -6
View File
@@ -96,6 +96,8 @@ type (
iamGetPolicyResponse = iamlib.GetPolicyResponse
iamListPolicyVersionsResponse = iamlib.ListPolicyVersionsResponse
iamGetPolicyVersionResponse = iamlib.GetPolicyVersionResponse
iamCreatePolicyVersionResponse = iamlib.CreatePolicyVersionResponse
iamDeletePolicyVersionResponse = iamlib.DeletePolicyVersionResponse
iamCreateUserResponse = iamlib.CreateUserResponse
iamDeleteUserResponse = iamlib.DeleteUserResponse
iamGetUserResponse = iamlib.GetUserResponse
@@ -265,7 +267,8 @@ func (e *EmbeddedIamApi) ReloadConfiguration() error {
func (e *EmbeddedIamApi) ListUsers(s3cfg *iam_pb.S3ApiConfiguration, values url.Values) *iamListUsersResponse {
resp := &iamListUsersResponse{}
for _, ident := range s3cfg.Identities {
resp.ListUsersResult.Users = append(resp.ListUsersResult.Users, &iam.User{UserName: &ident.Name})
user := iamlib.NewUser(ident.Name)
resp.ListUsersResult.Users = append(resp.ListUsersResult.Users, &user)
}
return resp
}
@@ -313,7 +316,7 @@ func (e *EmbeddedIamApi) CreateUser(s3cfg *iam_pb.S3ApiConfiguration, values url
}
}
resp.CreateUserResult.User.UserName = &userName
resp.CreateUserResult.User = iamlib.NewUser(userName)
s3cfg.Identities = append(s3cfg.Identities, &iam_pb.Identity{Name: userName}) // Disabled defaults to false (enabled)
return resp, nil
}
@@ -353,7 +356,7 @@ func (e *EmbeddedIamApi) GetUser(s3cfg *iam_pb.S3ApiConfiguration, userName stri
resp := &iamGetUserResponse{}
for _, ident := range s3cfg.Identities {
if userName == ident.Name {
resp.GetUserResult.User = iam.User{UserName: &ident.Name}
resp.GetUserResult.User = iamlib.NewUser(ident.Name)
return resp, nil
}
}
@@ -829,6 +832,87 @@ func (e *EmbeddedIamApi) GetPolicyVersion(ctx context.Context, values url.Values
return resp, nil
}
// CreatePolicyVersion replaces a managed policy's document with a new version.
// SeaweedFS keeps a single current document per managed policy (no version
// history), so the new document always becomes version "v1" / the default. This
// is what the AWS Terraform provider calls to update an aws_iam_policy in place.
func (e *EmbeddedIamApi) CreatePolicyVersion(ctx context.Context, values url.Values) (*iamCreatePolicyVersionResponse, *iamError) {
resp := &iamCreatePolicyVersionResponse{}
policyName, err := iamPolicyNameFromArn(values.Get("PolicyArn"))
if err != nil {
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
}
policyDocumentString := values.Get("PolicyDocument")
if policyDocumentString == "" {
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("PolicyDocument is required")}
}
// SeaweedFS stores a single, always-default managed policy version. On AWS,
// SetAsDefault=false stages a non-default version without activating it; we
// can't honor that, so reject it rather than silently changing permissions.
if !strings.EqualFold(values.Get("SetAsDefault"), "true") {
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("SetAsDefault must be true: SeaweedFS stores a single managed policy version")}
}
if e.credentialManager == nil {
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
}
policyDocument, err := e.GetPolicyDocument(&policyDocumentString)
if err != nil {
return resp, &iamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
}
if _, err := e.getActions(&policyDocument); err != nil {
return resp, &iamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
}
existing, err := e.credentialManager.GetPolicy(ctx, policyName)
if err != nil {
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
if existing == nil {
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
if err := e.credentialManager.UpdatePolicy(ctx, policyName, policyDocument); err != nil {
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
versionID := "v1"
isDefaultVersion := true
document := policyDocumentString
resp.CreatePolicyVersionResult.PolicyVersion = iam.PolicyVersion{
VersionId: &versionID,
IsDefaultVersion: &isDefaultVersion,
Document: &document,
}
return resp, nil
}
// DeletePolicyVersion is accepted for API completeness. With a single stored
// version that is always the default, the only valid responses are NoSuchEntity
// (unknown version) and the AWS "cannot delete the default version" conflict.
func (e *EmbeddedIamApi) DeletePolicyVersion(ctx context.Context, values url.Values) (*iamDeletePolicyVersionResponse, *iamError) {
resp := &iamDeletePolicyVersionResponse{}
policyName, err := iamPolicyNameFromArn(values.Get("PolicyArn"))
if err != nil {
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
}
versionID := values.Get("VersionId")
if versionID == "" {
return resp, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("VersionId is required")}
}
if e.credentialManager == nil {
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("credential manager not configured")}
}
policy, err := e.credentialManager.GetPolicy(ctx, policyName)
if err != nil {
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
}
if policy == nil {
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", policyName)}
}
if versionID == "v1" {
return resp, &iamError{Code: iam.ErrCodeDeleteConflictException, Error: fmt.Errorf("cannot delete the default version of policy %s", policyName)}
}
return resp, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy version %s not found", versionID)}
}
func iamPolicyNameFromArn(policyArn string) (string, error) {
const policyPathDelimiter = ":policy/"
idx := strings.Index(policyArn, policyPathDelimiter)
@@ -2013,8 +2097,8 @@ func (e *EmbeddedIamApi) GetGroup(s3cfg *iam_pb.S3ApiConfiguration, values url.V
if g.Name == groupName {
resp.GetGroupResult.Group.GroupName = &g.Name
for _, member := range g.Members {
memberName := member
resp.GetGroupResult.Users = append(resp.GetGroupResult.Users, &iam.User{UserName: &memberName})
user := iamlib.NewUser(member)
resp.GetGroupResult.Users = append(resp.GetGroupResult.Users, &user)
}
return resp, nil
}
@@ -2680,6 +2764,21 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
return nil, iamErr
}
changed = false
case "CreatePolicyVersion":
var iamErr *iamError
response, iamErr = e.CreatePolicyVersion(ctx, values)
if iamErr != nil {
glog.Errorf("CreatePolicyVersion: %+v", iamErr.Error)
return nil, iamErr
}
changed = false
case "DeletePolicyVersion":
var iamErr *iamError
response, iamErr = e.DeletePolicyVersion(ctx, values)
if iamErr != nil {
return nil, iamErr
}
changed = false
case "SetUserStatus":
var iamErr *iamError
response, iamErr = e.SetUserStatus(s3cfg, values)
@@ -2832,7 +2931,7 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
glog.Errorf("Failed to reload IAM configuration after mutation: %v", err)
// Don't fail the request since the persistent save succeeded
}
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "DeletePolicy" || action == "CreateUser" || action == "PutGroupPolicy" || action == "DeleteGroupPolicy" {
} else if action == "AttachUserPolicy" || action == "DetachUserPolicy" || action == "CreatePolicy" || action == "CreatePolicyVersion" || action == "DeletePolicy" || action == "CreateUser" || action == "PutGroupPolicy" || action == "DeleteGroupPolicy" {
// Even if changed=false (persisted via credentialManager), we should still reload
// if we are utilizing the local in-memory cache for speed
if err := e.ReloadConfiguration(); err != nil {
+102
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/gorilla/mux"
@@ -189,6 +190,10 @@ func TestEmbeddedIamCreateUser(t *testing.T) {
assert.NotNil(t, out.CreateUserResult.User.UserName)
assert.Equal(t, "TestUser", *out.CreateUserResult.User.UserName)
// Issue #9786: terraform aws provider >= 6.41 blocks on a valid ARN.
assert.True(t, arn.IsARN(aws.StringValue(out.CreateUserResult.User.Arn)),
"CreateUser must return a valid ARN, got %q", aws.StringValue(out.CreateUserResult.User.Arn))
// Verify user was persisted in config
assert.Len(t, api.mockConfig.Identities, 1)
assert.Equal(t, "TestUser", api.mockConfig.Identities[0].Name)
@@ -337,6 +342,11 @@ func TestEmbeddedIamGetUser(t *testing.T) {
// Verify response contains correct username
assert.NotNil(t, out.GetUserResult.User.UserName)
assert.Equal(t, "TestUser", *out.GetUserResult.User.UserName)
// Issue #9786: the terraform aws provider reads the user back after creating
// it and waits until GetUser returns a value that passes arn.IsARN.
assert.True(t, arn.IsARN(aws.StringValue(out.GetUserResult.User.Arn)),
"GetUser must return a valid ARN, got %q", aws.StringValue(out.GetUserResult.User.Arn))
}
// TestEmbeddedIamGetUserImplicitUsername verifies GetUser without a UserName defaults
@@ -416,6 +426,98 @@ func TestEmbeddedIamCreatePolicy(t *testing.T) {
assert.NotNil(t, out.CreatePolicyResult.Policy.PolicyId)
}
// TestEmbeddedIamCreatePolicyVersion covers the embedded IAM path for issue
// #9785: updating a managed policy in place via CreatePolicyVersion (used by the
// AWS Terraform provider) instead of returning 501 NotImplemented.
func TestEmbeddedIamCreatePolicyVersion(t *testing.T) {
api := NewEmbeddedIamApiForTest()
svc := iam.New(session.New())
policyArn := aws.String("arn:aws:iam:::policy/tf-managed")
// Create the managed policy.
createReq, _ := svc.CreatePolicyRequest(&iam.CreatePolicyInput{
PolicyName: aws.String("tf-managed"),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*","s3:List*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = createReq.Build()
resp, err := executeEmbeddedIamRequest(api, createReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
// Update it in place. This used to return 501 NotImplemented.
cpvReq, _ := svc.CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: policyArn,
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
SetAsDefault: aws.Bool(true),
})
_ = cpvReq.Build()
out := iamCreatePolicyVersionResponse{}
resp, err = executeEmbeddedIamRequest(api, cpvReq.HTTPRequest, &out)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
require.NotNil(t, out.CreatePolicyVersionResult.PolicyVersion.VersionId)
assert.Equal(t, "v1", *out.CreatePolicyVersionResult.PolicyVersion.VersionId)
require.NotNil(t, out.CreatePolicyVersionResult.PolicyVersion.IsDefaultVersion)
assert.True(t, *out.CreatePolicyVersionResult.PolicyVersion.IsDefaultVersion)
// The stored document must reflect the update.
gpvReq, _ := svc.GetPolicyVersionRequest(&iam.GetPolicyVersionInput{PolicyArn: policyArn, VersionId: aws.String("v1")})
_ = gpvReq.Build()
gpvOut := iamGetPolicyVersionResponse{}
resp, err = executeEmbeddedIamRequest(api, gpvReq.HTTPRequest, &gpvOut)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
require.NotNil(t, gpvOut.GetPolicyVersionResult.PolicyVersion.Document)
assert.Contains(t, *gpvOut.GetPolicyVersionResult.PolicyVersion.Document, "s3:Get*")
assert.NotContains(t, *gpvOut.GetPolicyVersionResult.PolicyVersion.Document, "s3:List*")
}
// TestEmbeddedIamCreatePolicyVersionMissingPolicy verifies NoSuchEntity when the
// target policy does not exist.
func TestEmbeddedIamCreatePolicyVersionMissingPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
req, _ := iam.New(session.New()).CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: aws.String("arn:aws:iam:::policy/does-not-exist"),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
SetAsDefault: aws.Bool(true),
})
_ = req.Build()
resp, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusNotFound, resp.Code)
code, _ := extractEmbeddedIamErrorCodeAndMessage(resp)
assert.Equal(t, "NoSuchEntity", code)
}
// TestEmbeddedIamCreatePolicyVersionRequiresSetAsDefault verifies the embedded
// path also rejects a non-default version request given the single-version model.
func TestEmbeddedIamCreatePolicyVersionRequiresSetAsDefault(t *testing.T) {
api := NewEmbeddedIamApiForTest()
svc := iam.New(session.New())
policyArn := aws.String("arn:aws:iam:::policy/tf-managed")
createReq, _ := svc.CreatePolicyRequest(&iam.CreatePolicyInput{
PolicyName: aws.String("tf-managed"),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Get*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = createReq.Build()
resp, err := executeEmbeddedIamRequest(api, createReq.HTTPRequest, nil)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.Code)
// SetAsDefault omitted must be rejected.
cpvReq, _ := svc.CreatePolicyVersionRequest(&iam.CreatePolicyVersionInput{
PolicyArn: policyArn,
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:Put*"],"Resource":["arn:aws:s3:::EXAMPLE-BUCKET"]}]}`),
})
_ = cpvReq.Build()
resp, err = executeEmbeddedIamRequest(api, cpvReq.HTTPRequest, nil)
require.NoError(t, err)
assert.Equal(t, http.StatusBadRequest, resp.Code)
code, _ := extractEmbeddedIamErrorCodeAndMessage(resp)
assert.Equal(t, "InvalidInput", code)
}
// TestEmbeddedIamPutUserPolicy tests attaching a policy to a user
func TestEmbeddedIamPutUserPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
+59 -43
View File
@@ -20,7 +20,7 @@ var _ = filer_pb.FilerClient(&S3ApiServer{})
func (s3a *S3ApiServer) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
// Use filerClient for proper connection management and failover
if s3a.filerClient != nil {
return s3a.withFilerClientFailover(streamingMode, fn)
return s3a.withFilerClientFailover("", streamingMode, fn)
}
// Fallback to direct connection if filerClient not initialized
@@ -32,69 +32,85 @@ func (s3a *S3ApiServer) WithFilerClient(streamingMode bool, fn func(filer_pb.Sea
}
// withFilerClientFailover attempts to execute fn with automatic failover to other filers
func (s3a *S3ApiServer) withFilerClientFailover(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
// Get current filer as starting point
// withFilerClientFailover runs fn against preferred (if set) first, then the
// remaining filers (current, then the rest) with healthy ones before unhealthy.
// Failover is for transport errors only: a reached filer's ErrNotFound is
// authoritative (no
// fan-out, no resurrecting a peer's not-yet-replicated tombstone). preferred lets a
// caller route to a key's ring owner for read-after-write; it may be a filer outside
// the static list (the bookkeeping no-ops for untracked addresses). A failover
// updates the current filer; a preferred read does not, as its owner is per-key.
func (s3a *S3ApiServer) withFilerClientFailover(preferred pb.ServerAddress, streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
currentFiler := s3a.filerClient.GetCurrentFiler()
// Try current filer first (fast path)
err := pb.WithGrpcClient(context.Background(), streamingMode, s3a.randomClientId, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
return fn(client)
}, currentFiler.ToGrpcAddress(), false, s3a.option.GrpcDialOption)
if err == nil {
s3a.filerClient.RecordFilerSuccess(currentFiler)
return nil
}
// A reachable filer answering ErrNotFound is authoritative; failover is for
// unreachable/unhealthy filers, not for re-asking about an absent entry.
if errors.Is(err, filer_pb.ErrNotFound) {
return err
}
s3a.filerClient.RecordFilerFailure(currentFiler)
// Current filer failed - try all other filers with health-aware selection
filers := s3a.filerClient.GetAllFilers()
var lastErr error = err
for _, filer := range filers {
if filer == currentFiler {
continue // Already tried this one
candidates := make([]pb.ServerAddress, 0, 2+len(s3a.option.Filers))
seen := make(map[pb.ServerAddress]bool)
addCandidate := func(filer pb.ServerAddress) {
if filer == "" || seen[filer] {
return
}
seen[filer] = true
candidates = append(candidates, filer)
}
addCandidate(preferred)
addCandidate(currentFiler)
for _, filer := range s3a.filerClient.GetAllFilers() {
addCandidate(filer)
}
// Skip filers known to be unhealthy (circuit breaker pattern)
if s3a.filerClient.ShouldSkipUnhealthyFiler(filer) {
glog.V(2).Infof("WithFilerClient: skipping unhealthy filer %s", filer)
// preferred (the routed owner) is tried first even when health-flagged, so a
// replica's authoritative NotFound can't mask a write that only reached the owner.
// A recently-unreachable filer counts as unhealthy, deferring a dead owner that is
// also the current filer to the tail rather than dialing it before healthy replicas.
var healthy, unhealthy []pb.ServerAddress
for _, filer := range candidates {
if filer == preferred {
continue
}
if s3a.filerClient.ShouldSkipUnhealthyFiler(filer) || s3a.ownerRecentlyUnreachable(filer) {
unhealthy = append(unhealthy, filer)
} else {
healthy = append(healthy, filer)
}
}
ordered := make([]pb.ServerAddress, 0, len(candidates))
if preferred != "" {
ordered = append(ordered, preferred)
}
ordered = append(ordered, healthy...)
ordered = append(ordered, unhealthy...)
err = pb.WithGrpcClient(context.Background(), streamingMode, s3a.randomClientId, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
return fn(client)
var lastErr error
for _, filer := range ordered {
err := pb.WithGrpcClient(context.Background(), streamingMode, s3a.randomClientId, func(grpcConnection *grpc.ClientConn) error {
return fn(filer_pb.NewSeaweedFilerClient(grpcConnection))
}, filer.ToGrpcAddress(), false, s3a.option.GrpcDialOption)
if err == nil {
// Success! Record success and update current filer for future requests
s3a.filerClient.RecordFilerSuccess(filer)
s3a.filerClient.SetCurrentFiler(filer)
glog.V(1).Infof("WithFilerClient: failover from %s to %s succeeded", currentFiler, filer)
if filer != currentFiler && filer != preferred {
s3a.filerClient.SetCurrentFiler(filer)
glog.V(1).Infof("WithFilerClient: failover from %s to %s succeeded", currentFiler, filer)
}
return nil
}
// Authoritative not-found - stop failing over.
if errors.Is(err, filer_pb.ErrNotFound) {
return err
}
s3a.filerClient.RecordFilerFailure(filer)
glog.V(2).Infof("WithFilerClient: failover to %s failed: %v", filer, err)
// A preferred owner is often outside the static filer list, where the health
// tracking above no-ops; flag it so route-by-key reads skip it briefly.
if filer == preferred {
s3a.markOwnerUnreachable(filer)
}
glog.V(2).Infof("WithFilerClient: filer %s failed: %v", filer, err)
lastErr = err
}
// All filers failed
if lastErr == nil {
lastErr = fmt.Errorf("no filer available")
}
return fmt.Errorf("all filers failed, last error: %w", lastErr)
}
+2 -4
View File
@@ -2408,8 +2408,7 @@ func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request
// fetchObjectEntry fetches the filer entry for an object
// Returns nil if not found (not an error), or propagates other errors
func (s3a *S3ApiServer) fetchObjectEntry(bucket, object string) (*filer_pb.Entry, error) {
objectPath := fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object)
fetchedEntry, fetchErr := s3a.getEntry("", objectPath)
fetchedEntry, fetchErr := s3a.getObjectEntryRoutedByKey(bucket, object)
if fetchErr != nil {
if errors.Is(fetchErr, filer_pb.ErrNotFound) {
return nil, nil // Not found is not an error for SSE check
@@ -2422,8 +2421,7 @@ func (s3a *S3ApiServer) fetchObjectEntry(bucket, object string) (*filer_pb.Entry
// fetchObjectEntryRequired fetches the filer entry for an object
// Returns an error if the object is not found or any other error occurs
func (s3a *S3ApiServer) fetchObjectEntryRequired(bucket, object string) (*filer_pb.Entry, error) {
objectPath := fmt.Sprintf("%s/%s", s3a.bucketDir(bucket), object)
fetchedEntry, fetchErr := s3a.getEntry("", objectPath)
fetchedEntry, fetchErr := s3a.getObjectEntryRoutedByKey(bucket, object)
if fetchErr != nil {
return nil, fetchErr // Return error for both not-found and other errors
}
+2 -42
View File
@@ -107,53 +107,13 @@ func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Reque
objectOwnerDisplayName = s3a.iam.GetAccountNameById(objectOwner)
// Build ACL response
// Build ACL response from stored ACL metadata (or the owner's default grant).
response := AccessControlPolicy{
Owner: CanonicalUser{
ID: objectOwner,
DisplayName: objectOwnerDisplayName,
},
}
// Get grants from stored ACL metadata
grants := GetAcpGrants(entry.Extended)
if len(grants) > 0 {
// Convert AWS SDK grants to local Grant format
for _, grant := range grants {
localGrant := Grant{
Permission: Permission(*grant.Permission),
}
if grant.Grantee != nil {
localGrant.Grantee = Grantee{
Type: *grant.Grantee.Type,
XMLXSI: "CanonicalUser",
XMLNS: "http://www.w3.org/2001/XMLSchema-instance",
}
if grant.Grantee.ID != nil {
localGrant.Grantee.ID = *grant.Grantee.ID
localGrant.Grantee.DisplayName = s3a.iam.GetAccountNameById(*grant.Grantee.ID)
}
if grant.Grantee.URI != nil {
localGrant.Grantee.URI = *grant.Grantee.URI
}
}
response.AccessControlList.Grant = append(response.AccessControlList.Grant, localGrant)
}
} else {
// Fallback to default full control for object owner
response.AccessControlList.Grant = append(response.AccessControlList.Grant, Grant{
Grantee: Grantee{
ID: objectOwner,
DisplayName: objectOwnerDisplayName,
Type: "CanonicalUser",
XMLXSI: "CanonicalUser",
XMLNS: "http://www.w3.org/2001/XMLSchema-instance"},
Permission: Permission(s3_constants.PermissionFullControl),
})
AccessControlList: buildAccessControlList(s3a.iam, GetAcpGrants(entry.Extended), objectOwner, objectOwnerDisplayName),
}
writeSuccessResponseXML(w, r, response)
@@ -409,6 +409,13 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
versioningConfigured := (versioningState != "")
deletedCount := 0
// Per-key authorization: keys arrive in the body, so the route Auth middleware
// only authenticated. Authorize each key via AuthorizeBatchDeleteKey below.
var identity *Identity
if id := s3_constants.GetIdentityFromContext(r); id != nil {
identity, _ = id.(*Identity)
}
err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
// delete file entries
for _, object := range deleteObjects.Objects {
@@ -419,6 +426,10 @@ func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *h
deleteErrors = append(deleteErrors, deleteErrorFromCode(s3err.ErrAccessDenied, object.Key, object.VersionId))
continue
}
if authErr := s3a.iam.AuthorizeBatchDeleteKey(r, identity, bucket, object.Key, object.VersionId); authErr != s3err.ErrNone {
deleteErrors = append(deleteErrors, deleteErrorFromCode(authErr, object.Key, object.VersionId))
continue
}
var deleteResult deleteMutationResult
deleteCode := s3a.withObjectWriteLock(bucket, object.Key, func() s3err.ErrorCode {
+97
View File
@@ -0,0 +1,97 @@
package s3api
import (
"context"
"errors"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// unreachableOwnerTTL is how long a route-by-key owner that just failed a read is
// skipped before being retried — long enough to spare a dead owner per-request
// dials, short enough to resume owner-first reads soon after it (or the ring) recovers.
const unreachableOwnerTTL = 2 * time.Second
// getObjectEntryRoutedByKey resolves an object's entry preferring the key's write
// owner (the same route key the write path hashes), so a read sees a just-written
// object without waiting for cross-filer replication. On the owner's ErrNotFound it
// probes the key's prior owner once during a rebalance window; falls back to
// getEntry when no owner is resolvable.
func (s3a *S3ApiServer) getObjectEntryRoutedByKey(bucket, object string) (*filer_pb.Entry, error) {
fullPath := util.NewFullPath(s3a.bucketDir(bucket), object)
owner := s3a.routableWriteOwner(bucket, object)
if owner == "" || s3a.filerClient == nil {
return filer_pb.GetEntry(context.Background(), s3a, fullPath)
}
// Skip an owner whose recent read hit a transport error; read local-first until
// it (or the ring) recovers, rather than re-dialing a dead owner every request.
preferred := owner
if s3a.ownerRecentlyUnreachable(owner) {
preferred = ""
}
dir, name := fullPath.DirAndName()
var entry *filer_pb.Entry
err := s3a.withFilerClientFailover(preferred, false, func(client filer_pb.SeaweedFilerClient) error {
resp, lookupErr := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
Directory: dir,
Name: name,
})
if lookupErr != nil {
return lookupErr
}
entry = resp.Entry
return nil
})
// A just-moved key may not have replicated to the new owner yet; consult its
// prior owner once while the ring change is within the cooling-off window.
if errors.Is(err, filer_pb.ErrNotFound) {
if prior := s3a.priorWriteOwner(bucket, object); prior != "" && prior != owner {
if priorEntry, priorErr := s3a.lookupEntryOnFiler(prior, dir, name); priorErr == nil {
return priorEntry, nil
}
}
}
return entry, err
}
func (s3a *S3ApiServer) priorWriteOwner(bucket, object string) pb.ServerAddress {
if object == "" || s3a.objectWriteLockClient == nil {
return ""
}
return s3a.objectWriteLockClient.PriorOwnerForKey(s3a.objectRouteKey(bucket, object))
}
func (s3a *S3ApiServer) markOwnerUnreachable(owner pb.ServerAddress) {
s3a.unreachableOwners.Store(owner, time.Now().Add(unreachableOwnerTTL))
}
func (s3a *S3ApiServer) ownerRecentlyUnreachable(owner pb.ServerAddress) bool {
if v, ok := s3a.unreachableOwners.Load(owner); ok {
return time.Now().Before(v.(time.Time))
}
return false
}
// lookupEntryOnFiler resolves dir/name against a single filer, without failover.
func (s3a *S3ApiServer) lookupEntryOnFiler(filer pb.ServerAddress, dir, name string) (*filer_pb.Entry, error) {
var entry *filer_pb.Entry
err := pb.WithFilerClient(false, 0, filer, s3a.option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
resp, lookupErr := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{
Directory: dir,
Name: name,
})
if lookupErr != nil {
return lookupErr
}
entry = resp.Entry
return nil
})
return entry, err
}
@@ -0,0 +1,24 @@
package s3api
import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb"
)
// A flagged owner reads back as recently unreachable; an unflagged one does not.
func TestOwnerRecentlyUnreachable(t *testing.T) {
s3a := &S3ApiServer{}
owner := pb.ServerAddress("127.0.0.1:8888.18888")
if s3a.ownerRecentlyUnreachable(owner) {
t.Fatal("unmarked owner should not be flagged")
}
s3a.markOwnerUnreachable(owner)
if !s3a.ownerRecentlyUnreachable(owner) {
t.Fatal("marked owner should be flagged within the TTL")
}
if s3a.ownerRecentlyUnreachable(pb.ServerAddress("127.0.0.1:9999.19999")) {
t.Fatal("a different owner should not be flagged")
}
}
+21 -1
View File
@@ -98,6 +98,12 @@ type S3ApiServer struct {
newObjectWriteLock func(bucket, object string) objectWriteLock
// objectWriteLockClient resolves a key's owner filer for route-by-key.
objectWriteLockClient *cluster.LockClient
// unreachableOwners holds owners (pb.ServerAddress -> expiry time.Time) whose
// last owner-first read hit a transport error, so route-by-key reads briefly
// skip them instead of re-dialing a dead owner every request until the ring
// drops it. Bypasses the gateway's filer health tracking, which no-ops for an
// owner outside the static -filer list.
unreachableOwners sync.Map
// Shared ReaderCache used by the S3 GET streaming path. It lives for the
// lifetime of the server so that concurrent and repeat reads share a
// single in-flight download per chunk, and so that no per-request
@@ -386,10 +392,24 @@ func NewS3ApiServerWithStore(router *mux.Router, option *S3ApiServerOption, expl
glog.Errorf("fail to load config file %s: %v", option.Config, err)
} else {
glog.V(1).Infof("Loaded %d identities from config file %s", len(s3ApiServer.iam.identities), option.Config)
s3ApiServer.iam.updateCredentialManagerStaticIdentities()
}
})
}
// Refresh the JWT signing keys on SIGHUP so an operator can rotate them
// without restarting; otherwise filer/volume auth stays stuck on the stale
// key after a rotation.
grace.OnReload(func() {
util.LoadConfiguration("security", false)
v := util.GetViper()
s3ApiServer.filerGuard.UpdateSigningKeys(
v.GetString("jwt.filer_signing.key"),
v.GetInt("jwt.filer_signing.expires_after_seconds"),
v.GetString("jwt.filer_signing.read.key"),
v.GetInt("jwt.filer_signing.read.expires_after_seconds"),
)
util_http.ReloadJwtSigningReadConfig()
})
s3ApiServer.bucketRegistry = NewBucketRegistry(s3ApiServer)
// Update IAM with the final filer client (already handled by SetFilerClient above,
+64 -22
View File
@@ -6,6 +6,8 @@ import (
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
@@ -39,31 +41,50 @@ Generating JWT:
Referenced:
https://github.com/pkieltyka/jwtauth/blob/master/jwtauth.go
*/
type Guard struct {
whiteListIp map[string]struct{}
whiteListCIDR map[string]*net.IPNet
SigningKey SigningKey
ExpiresAfterSec int
ReadSigningKey SigningKey
ReadExpiresAfterSec int
// guardState is the immutable snapshot of all hot-reloadable Guard state. The
// Update* methods build a new snapshot from the current one and swap it in
// atomically, so request-path readers (WhiteList, IsWhiteListed, the SigningKey
// accessors) always observe a consistent set of keys and whitelist — never a
// torn slice header or a mix of old and new state across a SIGHUP.
type guardState struct {
signingKey SigningKey
expiresAfterSec int
readSigningKey SigningKey
readExpiresAfterSec int
whiteListIp map[string]struct{}
whiteListCIDR map[string]*net.IPNet
isWriteActive bool
isEmptyWhiteList bool
}
type Guard struct {
// state is swapped atomically by the Update* methods. Read it via Load.
state atomic.Pointer[guardState]
// updateMu serializes the read-modify-write inside the Update* methods so
// concurrent reloads don't clobber each other; readers stay lock-free.
updateMu sync.Mutex
}
func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int) *Guard {
g := &Guard{
SigningKey: SigningKey(signingKey),
ExpiresAfterSec: expiresAfterSec,
ReadSigningKey: SigningKey(readSigningKey),
ReadExpiresAfterSec: readExpiresAfterSec,
}
g := &Guard{}
g.state.Store(&guardState{
signingKey: SigningKey(signingKey),
expiresAfterSec: expiresAfterSec,
readSigningKey: SigningKey(readSigningKey),
readExpiresAfterSec: readExpiresAfterSec,
})
g.UpdateWhiteList(whiteList)
return g
}
func (g *Guard) SigningKey() SigningKey { return g.state.Load().signingKey }
func (g *Guard) ExpiresAfterSec() int { return g.state.Load().expiresAfterSec }
func (g *Guard) ReadSigningKey() SigningKey { return g.state.Load().readSigningKey }
func (g *Guard) ReadExpiresAfterSec() int { return g.state.Load().readExpiresAfterSec }
func (g *Guard) WhiteList(f http.HandlerFunc) http.HandlerFunc {
if !g.isWriteActive {
if !g.state.Load().isWriteActive {
//if no security needed, just skip all checking
return f
}
@@ -109,18 +130,19 @@ func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
// IsWhiteListed returns true if the given host IP is allowed by the guard.
// When no whitelist is configured (security inactive), all hosts are allowed.
func (g *Guard) IsWhiteListed(host string) bool {
if !g.isWriteActive {
st := g.state.Load()
if !st.isWriteActive {
return true
}
if g.isEmptyWhiteList {
if st.isEmptyWhiteList {
return true
}
if _, ok := g.whiteListIp[host]; ok {
if _, ok := st.whiteListIp[host]; ok {
return true
}
remote := net.ParseIP(host)
if remote != nil {
for _, cidrnet := range g.whiteListCIDR {
for _, cidrnet := range st.whiteListCIDR {
if cidrnet.Contains(remote) {
return true
}
@@ -129,6 +151,22 @@ func (g *Guard) IsWhiteListed(host string) bool {
return false
}
// UpdateSigningKeys refreshes the JWT signing keys and their expirations so
// operators can rotate keys (e.g. via SIGHUP) without restarting the process.
// It swaps in a new snapshot carrying the existing whitelist, so a concurrent
// reader sees either the old keys or the new ones, never a torn slice header.
func (g *Guard) UpdateSigningKeys(signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int) {
g.updateMu.Lock()
defer g.updateMu.Unlock()
next := *g.state.Load()
next.signingKey = SigningKey(signingKey)
next.expiresAfterSec = expiresAfterSec
next.readSigningKey = SigningKey(readSigningKey)
next.readExpiresAfterSec = readExpiresAfterSec
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
g.state.Store(&next)
}
func (g *Guard) UpdateWhiteList(whiteList []string) {
whiteListIp := make(map[string]struct{})
whiteListCIDR := make(map[string]*net.IPNet)
@@ -144,8 +182,12 @@ func (g *Guard) UpdateWhiteList(whiteList []string) {
whiteListIp[ip] = struct{}{}
}
}
g.isEmptyWhiteList = len(whiteListIp) == 0 && len(whiteListCIDR) == 0
g.isWriteActive = !g.isEmptyWhiteList || len(g.SigningKey) != 0
g.whiteListIp = whiteListIp
g.whiteListCIDR = whiteListCIDR
g.updateMu.Lock()
defer g.updateMu.Unlock()
next := *g.state.Load()
next.isEmptyWhiteList = len(whiteListIp) == 0 && len(whiteListCIDR) == 0
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
next.whiteListIp = whiteListIp
next.whiteListCIDR = whiteListCIDR
g.state.Store(&next)
}
+81
View File
@@ -0,0 +1,81 @@
package security
import (
"sync"
"testing"
)
// TestUpdateSigningKeysRotates pins the hot-reload contract: after a key
// rotation the guard validates tokens minted with the new key and rejects the
// old one, so a SIGHUP recovers from a key mismatch without a process restart.
func TestUpdateSigningKeysRotates(t *testing.T) {
g := NewGuard(nil, "old-write", 10, "old-read", 60)
g.UpdateSigningKeys("new-write", 11, "new-read", 61)
if string(g.SigningKey()) != "new-write" || g.ExpiresAfterSec() != 11 {
t.Fatalf("write key not refreshed: key=%q exp=%d", g.SigningKey(), g.ExpiresAfterSec())
}
if string(g.ReadSigningKey()) != "new-read" || g.ReadExpiresAfterSec() != 61 {
t.Fatalf("read key not refreshed: key=%q exp=%d", g.ReadSigningKey(), g.ReadExpiresAfterSec())
}
tok := GenJwtForVolumeServer(g.SigningKey(), g.ExpiresAfterSec(), "3,01637037d6")
if _, err := DecodeJwt(g.SigningKey(), tok, &SeaweedFileIdClaims{}); err != nil {
t.Fatalf("token minted with rotated key should verify: %v", err)
}
if _, err := DecodeJwt(SigningKey("old-write"), tok, &SeaweedFileIdClaims{}); err == nil {
t.Fatalf("token minted with rotated key must not verify against the old key")
}
}
// TestUpdateSigningKeysConcurrent rotates keys and whitelist while readers mint
// and verify tokens and check whitelist membership, so `go test -race` would
// flag any torn read of the signing-key slice header or the whitelist maps.
// Each key rotation uses matching keys so every reader's token validates.
func TestUpdateSigningKeysConcurrent(t *testing.T) {
g := NewGuard([]string{"10.0.0.1"}, "k0", 60, "k0", 60)
var wg sync.WaitGroup
for w := 0; w < 8; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 1000; i++ {
key := g.SigningKey()
tok := GenJwtForVolumeServer(key, g.ExpiresAfterSec(), "3,01637037d6")
if _, err := DecodeJwt(key, tok, &SeaweedFileIdClaims{}); err != nil {
t.Errorf("token should verify against the snapshot it was minted from: %v", err)
return
}
g.IsWhiteListed("10.0.0.1")
}
}()
}
for i := 0; i < 1000; i++ {
g.UpdateSigningKeys("kw", 60, "kr", 60)
g.UpdateSigningKeys("kw2", 60, "kr2", 60)
g.UpdateWhiteList([]string{"10.0.0.1", "192.168.0.0/16"})
}
wg.Wait()
}
// TestUpdateSigningKeysTogglesWriteActive guards the isWriteActive recompute:
// adding a signing key to an otherwise-open guard must activate auth, and
// clearing it again must deactivate.
func TestUpdateSigningKeysTogglesWriteActive(t *testing.T) {
g := NewGuard(nil, "", 0, "", 0)
if g.state.Load().isWriteActive {
t.Fatalf("no whitelist and no key should be inactive")
}
g.UpdateSigningKeys("write", 10, "", 0)
if !g.state.Load().isWriteActive {
t.Fatalf("setting a signing key should activate auth")
}
g.UpdateSigningKeys("", 0, "", 0)
if g.state.Load().isWriteActive {
t.Fatalf("clearing the signing key should deactivate auth")
}
}
+51 -22
View File
@@ -22,34 +22,63 @@ func (fs *FilerServer) TraverseBfsMetadata(req *filer_pb.TraverseBfsMetadataRequ
ctx := stream.Context()
queue := util.NewQueue[*filer.Entry]()
isExcluded := func(path util.FullPath) bool {
excluded := false
excludedTrie.MatchPrefix([]byte(path), func(key []byte, value bool) bool {
// Only exclude when the prefix ends on a path-component boundary,
// so /a/b does not also exclude a sibling like /a/bc.
if len(path) == len(key) || path[len(key)] == '/' {
excluded = true
return false
}
return true
})
return excluded
}
// Send each entry as it is visited and queue only directory paths to
// descend into. Queuing the entries themselves would hold the whole
// subtree in memory, including every file's chunk list, and can exhaust
// the filer on large trees (e.g. during a peer's first-time bootstrap).
sendEntry := func(entry *filer.Entry) error {
parent, _ := entry.FullPath.DirAndName()
if err := stream.Send(&filer_pb.TraverseBfsMetadataResponse{
Directory: parent,
Entry: entry.ToProtoEntry(),
}); err != nil {
return fmt.Errorf("send traverse bfs metadata response: %w", err)
}
return nil
}
dirEntry, err := fs.filer.FindEntry(ctx, util.FullPath(req.Directory))
if err != nil {
return fmt.Errorf("find dir %s: %v", req.Directory, err)
}
queue.Enqueue(dirEntry)
if isExcluded(dirEntry.FullPath) {
return nil
}
if err := sendEntry(dirEntry); err != nil {
return err
}
for item := queue.Dequeue(); item != nil; item = queue.Dequeue() {
if excludedTrie.MatchPrefix([]byte(item.FullPath), func(key []byte, value bool) bool {
return true
}) {
// println("excluded", item.FullPath)
continue
}
parent, _ := item.FullPath.DirAndName()
if err := stream.Send(&filer_pb.TraverseBfsMetadataResponse{
Directory: parent,
Entry: item.ToProtoEntry(),
}); err != nil {
return fmt.Errorf("send traverse bfs metadata response: %w", err)
}
queue := util.NewQueue[util.FullPath]()
if dirEntry.IsDirectory() {
queue.Enqueue(dirEntry.FullPath)
}
if !item.IsDirectory() {
continue
}
if err := fs.iterateDirectory(ctx, item.FullPath, func(entry *filer.Entry) error {
queue.Enqueue(entry)
for queue.Len() > 0 {
dirPath := queue.Dequeue()
if err := fs.iterateDirectory(ctx, dirPath, func(entry *filer.Entry) error {
if isExcluded(entry.FullPath) {
return nil
}
if err := sendEntry(entry); err != nil {
return err
}
if entry.IsDirectory() {
queue.Enqueue(entry.FullPath)
}
return nil
}); err != nil {
return err
@@ -1,10 +1,14 @@
package weed_server
import (
"context"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/stretchr/testify/assert"
"github.com/viant/ptrie"
"google.golang.org/grpc"
)
func TestPtrie(t *testing.T) {
@@ -30,3 +34,61 @@ func TestPtrie(t *testing.T) {
assert.False(t, excludedTrie.Has(b))
}
type captureTraverseStream struct {
grpc.ServerStream
ctx context.Context
visited []string
}
func (s *captureTraverseStream) Context() context.Context { return s.ctx }
func (s *captureTraverseStream) Send(resp *filer_pb.TraverseBfsMetadataResponse) error {
dir := resp.Directory
if dir != "/" {
dir += "/"
}
s.visited = append(s.visited, dir+resp.Entry.Name)
return nil
}
func TestTraverseBfsMetadata(t *testing.T) {
store := newRenameTestStore()
// "/.system-data" shares the "/.system" byte prefix but is a different
// path component, so it must not be excluded.
for _, dir := range []string{"/", "/a", "/a/sub", "/b", "/.system", "/.system-data"} {
store.entries[dir] = newDirectoryEntry(dir, 1)
}
for _, file := range []string{"/a/f1", "/a/sub/f2", "/b/f3", "/.system/secret", "/.system-data/keep"} {
store.entries[file] = newFileEntry(file, 2)
}
server := &FilerServer{filer: newRenameTestFiler(store)}
stream := &captureTraverseStream{ctx: context.Background()}
err := server.TraverseBfsMetadata(&filer_pb.TraverseBfsMetadataRequest{
Directory: "/",
ExcludedPrefixes: []string{"/.system"},
}, stream)
assert.NoError(t, err)
// The excluded subtree is skipped; everything else (including the
// /.system-data sibling) is visited exactly once.
assert.ElementsMatch(t, []string{
"/", "/a", "/a/f1", "/a/sub", "/a/sub/f2", "/b", "/b/f3",
"/.system-data", "/.system-data/keep",
}, stream.visited)
// Each entry's parent must be streamed before the entry itself, so a
// consumer can apply the tree top-down.
seen := make(map[string]bool)
for _, path := range stream.visited {
if path != "/" {
parent, _ := util.FullPath(path).DirAndName()
assert.Truef(t, seen[parent], "parent %s of %s not streamed first", parent, path)
}
seen[path] = true
}
}
var _ filer_pb.SeaweedFiler_TraverseBfsMetadataServer = (*captureTraverseStream)(nil)
+15
View File
@@ -23,6 +23,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"github.com/seaweedfs/seaweedfs/weed/filer"
_ "github.com/seaweedfs/seaweedfs/weed/filer/arangodb"
@@ -343,4 +344,18 @@ func (fs *FilerServer) Reload() {
glog.V(0).Infoln("Reload filer server...")
util.LoadConfiguration("security", false)
v := util.GetViper()
fs.filerGuard.UpdateSigningKeys(
v.GetString("jwt.filer_signing.key"),
v.GetInt("jwt.filer_signing.expires_after_seconds"),
v.GetString("jwt.filer_signing.read.key"),
v.GetInt("jwt.filer_signing.read.expires_after_seconds"),
)
fs.volumeGuard.UpdateSigningKeys(
v.GetString("jwt.signing.key"),
v.GetInt("jwt.signing.expires_after_seconds"),
v.GetString("jwt.signing.read.key"),
v.GetInt("jwt.signing.read.expires_after_seconds"),
)
util_http.ReloadJwtSigningReadConfig()
}
+4 -6
View File
@@ -219,16 +219,14 @@ func (fs *FilerServer) maybeCheckJwtAuthorization(r *http.Request, isWrite bool)
var signingKey security.SigningKey
if isWrite {
if len(fs.filerGuard.SigningKey) == 0 {
signingKey = fs.filerGuard.SigningKey()
if len(signingKey) == 0 {
return true
} else {
signingKey = fs.filerGuard.SigningKey
}
} else {
if len(fs.filerGuard.ReadSigningKey) == 0 {
signingKey = fs.filerGuard.ReadSigningKey()
if len(signingKey) == 0 {
return true
} else {
signingKey = fs.filerGuard.ReadSigningKey
}
}
+1 -1
View File
@@ -254,5 +254,5 @@ func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
}
func (fs *FilerServer) maybeGetVolumeReadJwtAuthorizationToken(fileId string) string {
return string(security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey, fs.volumeGuard.ReadExpiresAfterSec, fileId))
return string(security.GenJwtForVolumeServer(fs.volumeGuard.ReadSigningKey(), fs.volumeGuard.ReadExpiresAfterSec(), fileId))
}
+1 -1
View File
@@ -155,7 +155,7 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest
DataCenter: dn.GetDataCenterId(),
},
Count: count,
Auth: string(security.GenJwtForVolumeServer(ms.guard.SigningKey, ms.guard.ExpiresAfterSec, fid)),
Auth: string(security.GenJwtForVolumeServer(ms.guard.SigningKey(), ms.guard.ExpiresAfterSec(), fid)),
Replicas: replicas,
}, nil
}
+1 -1
View File
@@ -183,7 +183,7 @@ func (ms *MasterServer) LookupVolume(ctx context.Context, req *master_pb.LookupV
}
var auth string
if commaSep > 0 { // this is a file id
auth = string(security.GenJwtForVolumeServer(ms.guard.SigningKey, ms.guard.ExpiresAfterSec, result.VolumeOrFileId))
auth = string(security.GenJwtForVolumeServer(ms.guard.SigningKey(), ms.guard.ExpiresAfterSec(), result.VolumeOrFileId))
}
if result.NotFound {
notFoundCount++
+6
View File
@@ -567,4 +567,10 @@ func (ms *MasterServer) Reload() {
ms.guard.UpdateWhiteList(append(ms.option.WhiteList,
util.StringSplit(v.GetString("guard.white_list"), ",")...),
)
ms.guard.UpdateSigningKeys(
v.GetString("jwt.signing.key"),
v.GetInt("jwt.signing.expires_after_seconds"),
v.GetString("jwt.signing.read.key"),
v.GetInt("jwt.signing.read.expires_after_seconds"),
)
}
+2 -2
View File
@@ -213,9 +213,9 @@ func (ms *MasterServer) maybeAddJwtAuthorization(w http.ResponseWriter, fileId s
}
var encodedJwt security.EncodedJwt
if isWrite {
encodedJwt = security.GenJwtForVolumeServer(ms.guard.SigningKey, ms.guard.ExpiresAfterSec, fileId)
encodedJwt = security.GenJwtForVolumeServer(ms.guard.SigningKey(), ms.guard.ExpiresAfterSec(), fileId)
} else {
encodedJwt = security.GenJwtForVolumeServer(ms.guard.ReadSigningKey, ms.guard.ReadExpiresAfterSec, fileId)
encodedJwt = security.GenJwtForVolumeServer(ms.guard.ReadSigningKey(), ms.guard.ReadExpiresAfterSec(), fileId)
}
if encodedJwt == "" {
return
+55
View File
@@ -24,6 +24,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/topology"
"github.com/seaweedfs/seaweedfs/weed/util/version"
"google.golang.org/grpc"
)
@@ -31,8 +32,57 @@ const (
ldbFile = "logs.dat"
sdbFile = "stable.dat"
updatePeersTimeout = 15 * time.Minute
// legacyMigrationKey marks, in the hashicorp stable store, that this
// master's hashicorp raft state has already absorbed any pre-existing
// legacy seaweedfs/raft state. Its presence makes the import one-time so
// later restarts never re-read stale legacy state.
legacyMigrationKey = "seaweedfs.legacy.raft.migrated"
)
// migrateLegacyRaftStateIfNeeded performs the one-time legacy -> hashicorp raft
// migration. It first checks the migration marker in the hashicorp stable
// store; if already migrated it does nothing. Otherwise, when a legacy
// seaweedfs/raft state is present, it imports the cluster identity
// (TopologyId) and MaxVolumeId from it, then marks the migration done. With no
// legacy state it just records the marker. Either way the master ends up
// marked migrated, so the import runs at most once per cluster.
func migrateLegacyRaftStateIfNeeded(sdb *boltdb.BoltStore, dataDir string, topo *topology.Topology) {
if _, err := sdb.Get([]byte(legacyMigrationKey)); err == nil {
return // marker present: already migrated
}
if legacyRaftStateExists(dataDir) {
glog.V(0).Infof("first hashicorp-raft start with legacy raft state in %s; migrating", dataDir)
importLegacyRaftState(dataDir, topo)
}
if err := sdb.Set([]byte(legacyMigrationKey), []byte(version.Version())); err != nil {
glog.Warningf("failed to record legacy raft migration marker: %v", err)
}
}
// importLegacyRaftState seeds TopologyId and MaxVolumeId from the latest legacy
// snapshot. TopologyId is the cluster identity and must survive the engine
// switch; MaxVolumeId is otherwise rebuilt from volume heartbeats, but carrying
// it avoids reusing an id whose volume was deleted before the migration.
func importLegacyRaftState(dataDir string, topo *topology.Topology) {
state, ok := readLegacyRaftSnapshotState(dataDir)
if !ok {
glog.V(0).Infof("legacy raft state present but no readable snapshot; " +
"TopologyId/MaxVolumeId will be rebuilt from volume heartbeats")
return
}
var cmd topology.MaxVolumeIdCommand
if err := json.Unmarshal(state, &cmd); err != nil {
glog.Warningf("failed to parse legacy raft snapshot state: %v", err)
return
}
topo.UpAdjustMaxVolumeId(cmd.MaxVolumeId)
if cmd.TopologyId != "" {
topo.SetTopologyId(cmd.TopologyId)
}
glog.V(0).Infof("migrated legacy raft state: MaxVolumeId=%d TopologyId=%s", cmd.MaxVolumeId, cmd.TopologyId)
}
func getPeerIdx(self pb.ServerAddress, mapPeers map[string]pb.ServerAddress) int {
peerIDs := make([]string, 0, len(mapPeers))
seen := make(map[string]struct{}, len(mapPeers))
@@ -212,6 +262,11 @@ func NewHashicorpRaftServer(option *RaftServerOption) (*RaftServer, error) {
return nil, fmt.Errorf("boltdb.NewBoltStore(%q): %v", filepath.Join(baseDir, "stable.dat"), err)
}
// Carry cluster identity forward when upgrading from legacy seaweedfs/raft.
// Runs once, before raft starts, so the seeded TopologyId is in place
// before ensureTopologyId would otherwise generate a fresh one.
migrateLegacyRaftStateIfNeeded(sdb, baseDir, option.Topo)
fss, err := raft.NewFileSnapshotStore(baseDir, 3, os.Stderr)
if err != nil {
return nil, fmt.Errorf("raft.NewFileSnapshotStore(%q, ...): %v", baseDir, err)
+116
View File
@@ -0,0 +1,116 @@
package weed_server
import (
"encoding/json"
"fmt"
"hash/crc32"
"os"
"path"
"path/filepath"
"testing"
boltdb "github.com/hashicorp/raft-boltdb/v2"
"github.com/seaweedfs/seaweedfs/weed/sequence"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/topology"
)
// writeLegacySnapshot writes a seaweedfs/raft (legacy) snapshot carrying the
// given FSM state, in the on-disk format readLegacyRaftSnapshotState expects.
func writeLegacySnapshot(t *testing.T, dataDir string, maxVolumeId needle.VolumeId, topologyId string) {
t.Helper()
snapshotDir := path.Join(dataDir, "snapshot")
if err := os.MkdirAll(snapshotDir, 0755); err != nil {
t.Fatal(err)
}
state, err := json.Marshal(topology.MaxVolumeIdCommand{MaxVolumeId: maxVolumeId, TopologyId: topologyId})
if err != nil {
t.Fatal(err)
}
body, err := json.Marshal(struct {
State json.RawMessage `json:"state"`
}{State: state})
if err != nil {
t.Fatal(err)
}
f, err := os.Create(path.Join(snapshotDir, "0_1.ss"))
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := fmt.Fprintf(f, "%08x\n", crc32.ChecksumIEEE(body)); err != nil {
t.Fatal(err)
}
if _, err := f.Write(body); err != nil {
t.Fatal(err)
}
}
func openStableStore(t *testing.T, dataDir string) *boltdb.BoltStore {
t.Helper()
sdb, err := boltdb.NewBoltStore(filepath.Join(dataDir, sdbFile))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { sdb.Close() })
return sdb
}
func newTestTopology() *topology.Topology {
return topology.NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5, false)
}
func TestMigrateLegacyRaftState_ImportsIdentityOnce(t *testing.T) {
dir := t.TempDir()
writeLegacySnapshot(t, dir, 4242, "cluster-abc")
sdb := openStableStore(t, dir)
topo := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo)
if got := topo.GetTopologyId(); got != "cluster-abc" {
t.Fatalf("TopologyId = %q, want cluster-abc", got)
}
if got := topo.GetMaxVolumeId(); got != needle.VolumeId(4242) {
t.Fatalf("MaxVolumeId = %d, want 4242", got)
}
if v, err := sdb.Get([]byte(legacyMigrationKey)); err != nil || len(v) == 0 {
t.Fatalf("migration marker not set: v=%q err=%v", v, err)
}
// Second run on a fresh topology must NOT re-import: the marker gates it.
topo2 := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo2)
if got := topo2.GetTopologyId(); got != "" {
t.Fatalf("re-import after marker set: TopologyId = %q, want empty", got)
}
}
func TestMigrateLegacyRaftState_NoLegacyJustMarks(t *testing.T) {
dir := t.TempDir()
sdb := openStableStore(t, dir)
topo := newTestTopology()
migrateLegacyRaftStateIfNeeded(sdb, dir, topo)
if got := topo.GetTopologyId(); got != "" {
t.Fatalf("TopologyId = %q, want empty (nothing to import)", got)
}
if v, err := sdb.Get([]byte(legacyMigrationKey)); err != nil || len(v) == 0 {
t.Fatalf("migration marker not set on fresh install: v=%q err=%v", v, err)
}
}
func TestLegacyRaftStateExists(t *testing.T) {
dir := t.TempDir()
if legacyRaftStateExists(dir) {
t.Fatal("empty dir reported as having legacy state")
}
if err := os.WriteFile(path.Join(dir, "log"), []byte("x"), 0644); err != nil {
t.Fatal(err)
}
if !legacyRaftStateExists(dir) {
t.Fatal("legacy log file not detected")
}
}
+30 -10
View File
@@ -249,35 +249,47 @@ func (s *RaftServer) Peers() (members []string) {
return
}
// recoverTopologyIdFromSnapshot reads the TopologyId from the latest
// seaweedfs/raft snapshot before state cleanup.
func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
// legacyRaftStateExists reports whether a seaweedfs/raft (legacy) state is
// present in dataDir. The legacy engine writes these names; hashicorp raft
// uses logs.dat/stable.dat/snapshots, so there is no overlap.
func legacyRaftStateExists(dataDir string) bool {
for _, name := range []string{"snapshot", "log", "conf", "state"} {
if _, err := os.Stat(path.Join(dataDir, name)); err == nil {
return true
}
}
return false
}
// readLegacyRaftSnapshotState returns the raw FSM state JSON from the latest
// seaweedfs/raft (legacy) snapshot, if a valid one exists.
func readLegacyRaftSnapshotState(dataDir string) (json.RawMessage, bool) {
snapshotDir := path.Join(dataDir, "snapshot")
dir, err := os.Open(snapshotDir)
if err != nil {
return
return nil, false
}
defer dir.Close()
filenames, err := dir.Readdirnames(-1)
if err != nil || len(filenames) == 0 {
return
return nil, false
}
sort.Strings(filenames)
file, err := os.Open(path.Join(snapshotDir, filenames[len(filenames)-1]))
if err != nil {
return
return nil, false
}
defer file.Close()
// Snapshot format: 8-hex-digit CRC32 checksum, newline, JSON body.
var checksum uint32
if _, err := fmt.Fscanf(file, "%08x\n", &checksum); err != nil {
return
return nil, false
}
b, err := io.ReadAll(file)
if err != nil || crc32.ChecksumIEEE(b) != checksum {
return
return nil, false
}
// The snapshot JSON wraps the FSM state in a "state" field.
@@ -285,9 +297,17 @@ func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
State json.RawMessage `json:"state"`
}
if err := json.Unmarshal(b, &snap); err != nil || len(snap.State) == 0 {
return
return nil, false
}
return snap.State, true
}
// recoverTopologyIdFromSnapshot reads the TopologyId from the latest
// seaweedfs/raft snapshot before state cleanup.
func recoverTopologyIdFromSnapshot(dataDir string, topo *topology.Topology) {
if state, ok := readLegacyRaftSnapshotState(dataDir); ok {
recoverTopologyIdFromState(state, topo)
}
recoverTopologyIdFromState(snap.State, topo)
}
// HasExistingState returns true when the raft log already contains entries,
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
@@ -91,6 +92,7 @@ func TestVolumeEcShardsInfo_AggregatesAcrossDisks(t *testing.T) {
// cross-disk fallback in NewEcVolume.
shardsOnDisk0 := []erasure_coding.ShardId{0, 5}
shardsOnDisk1 := []erasure_coding.ShardId{7, 12}
diskIOProbeConfig := stats.DefaultDiskIOProbeConfig()
store := storage.NewStore(nil, "localhost", 8080, 18080, "http://localhost:8080", "store-id",
[]string{dir0, dir1},
@@ -101,6 +103,7 @@ func TestVolumeEcShardsInfo_AggregatesAcrossDisks(t *testing.T) {
[]types.DiskType{types.HardDriveType, types.HardDriveType},
nil,
3,
diskIOProbeConfig,
)
done := make(chan struct{})
go func() {
+8 -1
View File
@@ -83,6 +83,7 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
readBufferSizeMB int,
ldbTimeout int64,
allowUntrustedRemoteEndpoints bool,
diskProbeConfig stats.DiskIOProbeConfig,
) *VolumeServer {
v := util.GetViper()
@@ -134,7 +135,7 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
vs.checkWithMaster()
vs.store = storage.NewStore(vs.grpcDialOption, ip, port, grpcPort, publicUrl, id, folders, maxCounts, minFreeSpaces, idxFolder, vs.needleMapKind, diskTypes, diskTags, ldbTimeout)
vs.store = storage.NewStore(vs.grpcDialOption, ip, port, grpcPort, publicUrl, id, folders, maxCounts, minFreeSpaces, idxFolder, vs.needleMapKind, diskTypes, diskTags, ldbTimeout, diskProbeConfig)
vs.guard = security.NewGuard(whiteList, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec)
handleStaticResources(adminMux)
@@ -189,6 +190,12 @@ func (vs *VolumeServer) Reload() {
util.LoadConfiguration("security", false)
v := util.GetViper()
vs.guard.UpdateWhiteList(append(vs.whiteList, util.StringSplit(v.GetString("guard.white_list"), ",")...))
vs.guard.UpdateSigningKeys(
v.GetString("jwt.signing.key"),
v.GetInt("jwt.signing.expires_after_seconds"),
v.GetString("jwt.signing.read.key"),
v.GetInt("jwt.signing.read.expires_after_seconds"),
)
}
// Returns whether a volume server is in maintenance (i.e. read-only) mode.
+4 -6
View File
@@ -330,16 +330,14 @@ func (vs *VolumeServer) maybeCheckJwtAuthorization(r *http.Request, vid, fid str
var signingKey security.SigningKey
if isWrite {
if len(vs.guard.SigningKey) == 0 {
signingKey = vs.guard.SigningKey()
if len(signingKey) == 0 {
return true
} else {
signingKey = vs.guard.SigningKey
}
} else {
if len(vs.guard.ReadSigningKey) == 0 {
signingKey = vs.guard.ReadSigningKey()
if len(signingKey) == 0 {
return true
} else {
signingKey = vs.guard.ReadSigningKey
}
}
+26 -5
View File
@@ -2,6 +2,8 @@
package auth
import (
"fmt"
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
"golang.org/x/crypto/ssh"
)
@@ -17,11 +19,16 @@ type Manager struct {
userStore user.Store
passwordAuth *PasswordAuthenticator
publicKeyAuth *PublicKeyAuthenticator
certificateAuth *CertificateAuthenticator
enabledAuthMethods []string
}
// NewManager creates a new authentication manager
func NewManager(userStore user.Store, enabledAuthMethods []string) *Manager {
// NewManager creates a new authentication manager.
//
// trustedUserCAKeysFile is the path to a file containing trusted CA public
// keys (OpenSSH authorized_keys format). It is required when "certificate"
// is listed in enabledAuthMethods and ignored otherwise.
func NewManager(userStore user.Store, enabledAuthMethods []string, trustedUserCAKeysFile string) (*Manager, error) {
manager := &Manager{
userStore: userStore,
enabledAuthMethods: enabledAuthMethods,
@@ -30,6 +37,7 @@ func NewManager(userStore user.Store, enabledAuthMethods []string) *Manager {
// Initialize authenticators based on enabled methods
passwordEnabled := false
publicKeyEnabled := false
certificateEnabled := false
for _, method := range enabledAuthMethods {
switch method {
@@ -37,13 +45,21 @@ func NewManager(userStore user.Store, enabledAuthMethods []string) *Manager {
passwordEnabled = true
case "publickey":
publicKeyEnabled = true
case "certificate":
certificateEnabled = true
}
}
manager.passwordAuth = NewPasswordAuthenticator(userStore, passwordEnabled)
manager.publicKeyAuth = NewPublicKeyAuthenticator(userStore, publicKeyEnabled)
return manager
certAuth, err := NewCertificateAuthenticator(userStore, certificateEnabled, trustedUserCAKeysFile)
if err != nil {
return nil, fmt.Errorf("init certificate auth: %w", err)
}
manager.certificateAuth = certAuth
return manager, nil
}
// GetSSHServerConfig returns an SSH server config with the appropriate authentication methods
@@ -55,8 +71,13 @@ func (m *Manager) GetSSHServerConfig() *ssh.ServerConfig {
config.PasswordCallback = m.passwordAuth.Authenticate
}
// Add public key authentication if enabled
if m.publicKeyAuth.Enabled() {
// Wire the public-key channel. Certificate auth, when enabled, takes
// over the channel entirely (MinIO/OpenSSH-style): plain public keys
// are rejected even if "publickey" is also listed in enabledAuthMethods.
switch {
case m.certificateAuth.Enabled():
config.PublicKeyCallback = m.certificateAuth.Authenticate
case m.publicKeyAuth.Enabled():
config.PublicKeyCallback = m.publicKeyAuth.Authenticate
}
+79
View File
@@ -0,0 +1,79 @@
package auth
import (
"strings"
"testing"
"time"
"golang.org/x/crypto/ssh"
)
// When both "publickey" and "certificate" are enabled, certificate auth takes
// over the public-key channel: plain keys are rejected, certs are accepted, and
// password auth stays independently wired.
func TestManager_CertificateTakesOverPublicKeyChannel(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
mgr, err := NewManager(store, []string{"password", "publickey", "certificate"}, env.caKeyFile)
if err != nil {
t.Fatalf("NewManager: %v", err)
}
cfg := mgr.GetSSHServerConfig()
if cfg.PasswordCallback == nil {
t.Fatal("expected password callback to stay wired")
}
if cfg.PublicKeyCallback == nil {
t.Fatal("expected public-key callback")
}
// Plain public key is rejected by the certificate authenticator.
if _, err := cfg.PublicKeyCallback(&fakeConnMetadata{user: "alice"}, env.userSigner.PublicKey()); err == nil {
t.Fatal("expected plain public key to be rejected")
} else if !strings.Contains(err.Error(), "public key without certificate") {
t.Fatalf("expected certificate-channel rejection, got %v", err)
}
// A valid cert is accepted.
cert := env.signCert(t, ssh.UserCert, []string{"alice"},
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
perms, err := cfg.PublicKeyCallback(&fakeConnMetadata{user: "alice"}, cert)
if err != nil {
t.Fatalf("expected cert to be accepted: %v", err)
}
if perms.Extensions["username"] != "alice" {
t.Fatalf("expected username extension alice, got %q", perms.Extensions["username"])
}
}
// Without "certificate", the public-key channel keeps plain public-key auth.
func TestManager_PublicKeyOnlyChannel(t *testing.T) {
mgr, err := NewManager(newStubStore("alice"), []string{"publickey"}, "")
if err != nil {
t.Fatalf("NewManager: %v", err)
}
cfg := mgr.GetSSHServerConfig()
if cfg.PublicKeyCallback == nil {
t.Fatal("expected public-key callback")
}
env := newTestEnv(t)
// Routes to plain public-key auth (stub store has no registered key), which
// fails with a different error than the certificate channel would.
_, err = cfg.PublicKeyCallback(&fakeConnMetadata{user: "alice"}, env.userSigner.PublicKey())
if err == nil {
t.Fatal("expected authentication failure")
}
if strings.Contains(err.Error(), "without certificate") {
t.Fatalf("certificate auth should not be wired, got %v", err)
}
}
// Enabling certificate auth without a CA keys file is a hard configuration error.
func TestManager_CertificateRequiresCAFile(t *testing.T) {
if _, err := NewManager(newStubStore(), []string{"certificate"}, ""); err == nil {
t.Fatal("expected error when certificate auth enabled without CA keys file")
}
}
+150
View File
@@ -0,0 +1,150 @@
package auth
import (
"bytes"
"crypto/subtle"
"errors"
"fmt"
"os"
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
"golang.org/x/crypto/ssh"
)
// CertificateAuthenticator authenticates clients that present an OpenSSH
// user certificate signed by one of the configured trusted CA public keys.
//
// Behaviour mirrors MinIO's --sftp=trusted-user-ca-key option and OpenSSH's
// TrustedUserCAKeys directive: when enabled, only key blobs of type
// *ssh.Certificate are accepted on the public-key channel. Plain public
// keys are rejected. The SSH login username must appear in the cert's
// ValidPrincipals list and must resolve to an existing user in the store.
type CertificateAuthenticator struct {
userStore user.Store
enabled bool
trustedCAs []ssh.PublicKey
checker *ssh.CertChecker
}
// NewCertificateAuthenticator constructs a CertificateAuthenticator.
// When enabled is true, caKeysFile must point to a file containing one or
// more CA public keys in OpenSSH authorized_keys format (one per line).
func NewCertificateAuthenticator(userStore user.Store, enabled bool, caKeysFile string) (*CertificateAuthenticator, error) {
a := &CertificateAuthenticator{
userStore: userStore,
enabled: enabled,
}
if !enabled {
return a, nil
}
if caKeysFile == "" {
return nil, fmt.Errorf("certificate auth enabled but no trustedUserCAKeysFile provided")
}
cas, err := loadAuthorizedKeysFile(caKeysFile)
if err != nil {
return nil, fmt.Errorf("load trusted user CA keys from %s: %w", caKeysFile, err)
}
if len(cas) == 0 {
return nil, fmt.Errorf("no trusted user CA keys found in %s", caKeysFile)
}
a.trustedCAs = cas
// Pre-marshal trusted CA keys once. IsUserAuthority runs on every
// authentication attempt, so caching the marshaled form avoids
// repeated allocations on the hot path.
trustedCAsMarshaled := make([][]byte, len(cas))
for i, ca := range cas {
trustedCAsMarshaled[i] = ca.Marshal()
}
a.checker = &ssh.CertChecker{
IsUserAuthority: func(auth ssh.PublicKey) bool {
marshaled := auth.Marshal()
for _, caBytes := range trustedCAsMarshaled {
if subtle.ConstantTimeCompare(marshaled, caBytes) == 1 {
return true
}
}
return false
},
}
return a, nil
}
// Enabled reports whether certificate authentication is active.
func (a *CertificateAuthenticator) Enabled() bool {
return a.enabled
}
// Authenticate implements ssh.ServerConfig.PublicKeyCallback.
func (a *CertificateAuthenticator) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if !a.enabled {
return nil, fmt.Errorf("certificate authentication disabled")
}
cert, ok := key.(*ssh.Certificate)
if !ok {
return nil, fmt.Errorf("public key without certificate not allowed")
}
if cert.CertType != ssh.UserCert {
return nil, fmt.Errorf("certificate is not a user certificate")
}
if len(cert.ValidPrincipals) == 0 {
return nil, fmt.Errorf("certificate has no valid principals")
}
username := conn.User()
// CertChecker.Authenticate verifies the CA signature (via IsUserAuthority),
// the ValidAfter/ValidBefore window, and that username is in ValidPrincipals.
perms, err := a.checker.Authenticate(conn, key)
if err != nil {
return nil, fmt.Errorf("certificate validation failed: %w", err)
}
// The SSH login user must exist in the SeaweedFS user store.
if _, err := a.userStore.GetUser(username); err != nil {
var notFound *user.UserNotFoundError
if errors.As(err, &notFound) {
return nil, fmt.Errorf("user %q not found", username)
}
return nil, fmt.Errorf("lookup user %q: %w", username, err)
}
if perms == nil {
perms = &ssh.Permissions{}
}
if perms.Extensions == nil {
perms.Extensions = map[string]string{}
}
perms.Extensions["username"] = username
return perms, nil
}
// loadAuthorizedKeysFile parses an authorized_keys-style file and returns
// all public keys found in it. Blank lines and comment lines starting with
// '#' are skipped.
func loadAuthorizedKeysFile(path string) ([]ssh.PublicKey, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var keys []ssh.PublicKey
for _, line := range bytes.Split(data, []byte("\n")) {
line = bytes.TrimSpace(line)
if len(line) == 0 || line[0] == '#' {
continue
}
pub, _, _, _, err := ssh.ParseAuthorizedKey(line)
if err != nil {
return nil, err
}
keys = append(keys, pub)
}
return keys, nil
}
+312
View File
@@ -0,0 +1,312 @@
package auth
import (
"crypto/ed25519"
"crypto/rand"
"errors"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/sftpd/user"
"golang.org/x/crypto/ssh"
)
// stubStore is a minimal user.Store for auth tests.
type stubStore struct {
users map[string]*user.User
}
func newStubStore(usernames ...string) *stubStore {
s := &stubStore{users: map[string]*user.User{}}
for _, name := range usernames {
s.users[name] = &user.User{Username: name}
}
return s
}
func (s *stubStore) GetUser(username string) (*user.User, error) {
if u, ok := s.users[username]; ok {
return u, nil
}
return nil, &user.UserNotFoundError{Username: username}
}
func (s *stubStore) ValidatePassword(string, []byte) bool { return false }
func (s *stubStore) ValidatePublicKey(string, string) bool { return false }
func (s *stubStore) GetUserPermissions(string, string) []string { return nil }
func (s *stubStore) SaveUser(*user.User) error { return nil }
func (s *stubStore) DeleteUser(string) error { return nil }
func (s *stubStore) ListUsers() ([]string, error) { return nil, nil }
// fakeConnMetadata satisfies ssh.ConnMetadata for the parts CertChecker uses.
type fakeConnMetadata struct {
user string
}
func (c *fakeConnMetadata) User() string { return c.user }
func (c *fakeConnMetadata) SessionID() []byte { return []byte("session") }
func (c *fakeConnMetadata) ClientVersion() []byte { return []byte("SSH-2.0-test") }
func (c *fakeConnMetadata) ServerVersion() []byte { return []byte("SSH-2.0-test") }
func (c *fakeConnMetadata) RemoteAddr() net.Addr { return &fakeAddr{} }
func (c *fakeConnMetadata) LocalAddr() net.Addr { return &fakeAddr{} }
type fakeAddr struct{}
func (fakeAddr) Network() string { return "tcp" }
func (fakeAddr) String() string { return "127.0.0.1:0" }
// testEnv bundles a CA, a user signer, and a temp dir for a single test.
type testEnv struct {
caSigner ssh.Signer
userSigner ssh.Signer
caKeyFile string
}
func newTestEnv(t *testing.T) *testEnv {
t.Helper()
_, caPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("ed25519 CA: %v", err)
}
caSigner, err := ssh.NewSignerFromKey(caPriv)
if err != nil {
t.Fatalf("ca signer: %v", err)
}
_, userPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("ed25519 user: %v", err)
}
userSigner, err := ssh.NewSignerFromKey(userPriv)
if err != nil {
t.Fatalf("user signer: %v", err)
}
dir := t.TempDir()
caFile := filepath.Join(dir, "ca_user.pub")
if err := os.WriteFile(caFile, ssh.MarshalAuthorizedKey(caSigner.PublicKey()), 0o600); err != nil {
t.Fatalf("write ca file: %v", err)
}
return &testEnv{caSigner: caSigner, userSigner: userSigner, caKeyFile: caFile}
}
// signCert produces a user cert signed by the test CA.
func (e *testEnv) signCert(t *testing.T, certType uint32, principals []string, validAfter, validBefore time.Time) *ssh.Certificate {
t.Helper()
cert := &ssh.Certificate{
Key: e.userSigner.PublicKey(),
CertType: certType,
ValidPrincipals: principals,
ValidAfter: uint64(validAfter.Unix()),
ValidBefore: uint64(validBefore.Unix()),
}
if err := cert.SignCert(rand.Reader, e.caSigner); err != nil {
t.Fatalf("sign cert: %v", err)
}
return cert
}
func TestCertificateAuthenticator_GoldenPath(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, err := NewCertificateAuthenticator(store, true, env.caKeyFile)
if err != nil {
t.Fatalf("new: %v", err)
}
cert := env.signCert(t, ssh.UserCert, []string{"alice"},
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
perms, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert)
if err != nil {
t.Fatalf("Authenticate: %v", err)
}
if perms.Extensions["username"] != "alice" {
t.Fatalf("expected username extension alice, got %q", perms.Extensions["username"])
}
}
func TestCertificateAuthenticator_RejectsPlainPublicKey(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, err := NewCertificateAuthenticator(store, true, env.caKeyFile)
if err != nil {
t.Fatalf("new: %v", err)
}
_, err = a.Authenticate(&fakeConnMetadata{user: "alice"}, env.userSigner.PublicKey())
if err == nil {
t.Fatal("expected rejection of plain public key, got nil")
}
if !strings.Contains(err.Error(), "public key without certificate") {
t.Fatalf("unexpected error: %v", err)
}
}
func TestCertificateAuthenticator_RejectsHostCert(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
cert := env.signCert(t, ssh.HostCert, []string{"alice"},
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
if _, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert); err == nil {
t.Fatal("expected rejection of host cert, got nil")
}
}
func TestCertificateAuthenticator_RejectsEmptyPrincipals(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
cert := env.signCert(t, ssh.UserCert, nil,
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
_, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert)
if err == nil || !strings.Contains(err.Error(), "no valid principals") {
t.Fatalf("expected empty-principals rejection, got %v", err)
}
}
func TestCertificateAuthenticator_RejectsWrongPrincipal(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice", "bob")
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
cert := env.signCert(t, ssh.UserCert, []string{"bob"},
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
if _, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert); err == nil {
t.Fatal("expected wrong-principal rejection, got nil")
}
}
func TestCertificateAuthenticator_RejectsExpiredCert(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
cert := env.signCert(t, ssh.UserCert, []string{"alice"},
time.Now().Add(-2*time.Hour), time.Now().Add(-time.Hour))
if _, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert); err == nil {
t.Fatal("expected expired-cert rejection, got nil")
}
}
func TestCertificateAuthenticator_RejectsUnknownCA(t *testing.T) {
env := newTestEnv(t)
store := newStubStore("alice")
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
// Sign with a different CA.
_, otherCAPriv, _ := ed25519.GenerateKey(rand.Reader)
otherCASigner, _ := ssh.NewSignerFromKey(otherCAPriv)
cert := &ssh.Certificate{
Key: env.userSigner.PublicKey(),
CertType: ssh.UserCert,
ValidPrincipals: []string{"alice"},
ValidAfter: uint64(time.Now().Add(-time.Minute).Unix()),
ValidBefore: uint64(time.Now().Add(time.Hour).Unix()),
}
if err := cert.SignCert(rand.Reader, otherCASigner); err != nil {
t.Fatalf("sign: %v", err)
}
if _, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert); err == nil {
t.Fatal("expected unknown-CA rejection, got nil")
}
}
func TestCertificateAuthenticator_RejectsUnknownUser(t *testing.T) {
env := newTestEnv(t)
store := newStubStore() // no users
a, _ := NewCertificateAuthenticator(store, true, env.caKeyFile)
cert := env.signCert(t, ssh.UserCert, []string{"alice"},
time.Now().Add(-time.Minute), time.Now().Add(time.Hour))
_, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert)
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Fatalf("expected user-not-found, got %v", err)
}
}
func TestCertificateAuthenticator_LoadsMultipleCAKeys(t *testing.T) {
env := newTestEnv(t)
// Append a second CA pubkey to the file.
_, ca2Priv, _ := ed25519.GenerateKey(rand.Reader)
ca2Signer, _ := ssh.NewSignerFromKey(ca2Priv)
f, err := os.OpenFile(env.caKeyFile, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatalf("open: %v", err)
}
if _, err := f.Write(ssh.MarshalAuthorizedKey(ca2Signer.PublicKey())); err != nil {
t.Fatalf("write: %v", err)
}
f.Close()
store := newStubStore("alice")
a, err := NewCertificateAuthenticator(store, true, env.caKeyFile)
if err != nil {
t.Fatalf("new: %v", err)
}
if len(a.trustedCAs) != 2 {
t.Fatalf("expected 2 CAs, got %d", len(a.trustedCAs))
}
// A cert signed by the second CA should be accepted.
cert := &ssh.Certificate{
Key: env.userSigner.PublicKey(),
CertType: ssh.UserCert,
ValidPrincipals: []string{"alice"},
ValidAfter: uint64(time.Now().Add(-time.Minute).Unix()),
ValidBefore: uint64(time.Now().Add(time.Hour).Unix()),
}
if err := cert.SignCert(rand.Reader, ca2Signer); err != nil {
t.Fatalf("sign: %v", err)
}
if _, err := a.Authenticate(&fakeConnMetadata{user: "alice"}, cert); err != nil {
t.Fatalf("Authenticate with second CA: %v", err)
}
}
func TestNewCertificateAuthenticator_DisabledIgnoresFile(t *testing.T) {
a, err := NewCertificateAuthenticator(newStubStore(), false, "")
if err != nil {
t.Fatalf("new: %v", err)
}
if a.Enabled() {
t.Fatal("expected disabled")
}
}
func TestNewCertificateAuthenticator_EnabledRequiresFile(t *testing.T) {
_, err := NewCertificateAuthenticator(newStubStore(), true, "")
if err == nil {
t.Fatal("expected error when enabled without file")
}
}
func TestNewCertificateAuthenticator_MissingFile(t *testing.T) {
_, err := NewCertificateAuthenticator(newStubStore(), true, filepath.Join(t.TempDir(), "nope.pub"))
if err == nil {
t.Fatal("expected error for missing file")
}
// Sanity: not a not-found-user-style error.
var notFound *user.UserNotFoundError
if errors.As(err, &notFound) {
t.Fatalf("unexpected error type: %v", err)
}
}
+9 -2
View File
@@ -36,7 +36,7 @@ type SFTPServiceOptions struct {
// SSH Configuration
SshPrivateKey string // Legacy single host key
HostKeysFolder string // Multiple host keys for different algorithms
AuthMethods []string // Enabled auth methods: "password", "publickey", "keyboard-interactive"
AuthMethods []string // Enabled auth methods: "password", "publickey", "certificate"
MaxAuthTries int // Limit authentication attempts
BannerMessage string // Pre-auth banner message
LoginGraceTime time.Duration // Timeout for authentication
@@ -48,6 +48,9 @@ type SFTPServiceOptions struct {
// User Management
UserStoreFile string // Path to user store file
// Certificate Authentication
TrustedUserCAKeysFile string // Path to file with trusted user CA public keys (OpenSSH authorized_keys format)
// JWT Configuration for Filer
FilerSigningKey []byte // JWT signing key for filer uploads
FilerSigningExpiresAfter int // JWT token expiration time in seconds
@@ -65,7 +68,11 @@ func NewSFTPService(options *SFTPServiceOptions) *SFTPService {
service.userStore = userStore
// Initialize auth manager
service.authManager = auth.NewManager(userStore, options.AuthMethods)
authManager, err := auth.NewManager(userStore, options.AuthMethods, options.TrustedUserCAKeysFile)
if err != nil {
glog.Fatalf("Failed to initialize auth manager: %v", err)
}
service.authManager = authManager
return &service
}
+487
View File
@@ -1,10 +1,105 @@
package stats
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
)
type DiskIOProbeConfig struct {
// enable/disable disk io probing
Enabled bool
// timeout for a single io probe
Timeout time.Duration
// probe interval
Interval time.Duration
// latency above this threshold is considered slow
SlowLatency time.Duration
// rolling observation window
Window time.Duration
// minimum number of samples required before evaluating health
MinSamples int
// percentage of slow operations required to mark disk degraded
SlowPercent float64
// percentage of failed operations required to mark disk degraded
ErrorPercent float64
// recovery coef defines the hysteresis threshold for recovering from degraded state.
RecoveryCoef float64
// statfs failures before alerting
MaxStatFailures int
}
func DefaultDiskIOProbeConfig() DiskIOProbeConfig {
return DiskIOProbeConfig{
Enabled: false,
Timeout: 2 * time.Second,
Interval: 30 * time.Second,
SlowLatency: 100 * time.Millisecond,
Window: time.Minute,
MinSamples: 10,
SlowPercent: 20,
ErrorPercent: 10,
RecoveryCoef: 0.5,
MaxStatFailures: 3,
}
}
type ioSample struct {
ts time.Time
latency time.Duration
failed bool
slow bool
}
type diskState struct {
mu sync.Mutex
// statfs probe
isChecking bool
statFailureCount int
statSuccessCount int
lastStatErr error
lastGoodStatus volume_server_pb.DiskStatus
hasLastGood bool
samples []ioSample
// IO probe
isIOChecking bool
ioCheckID uint64
lastIOCheck time.Time
ioFailureCount int
lastIOErr error
ioDegraded bool
}
var diskRegistry sync.Map
const (
// statfs timeout
diskTimeout = 500 * time.Millisecond
)
func NewDiskStatus(path string) (disk *volume_server_pb.DiskStatus) {
disk = &volume_server_pb.DiskStatus{Dir: path}
fillInDiskStatus(disk)
@@ -13,3 +108,395 @@ func NewDiskStatus(path string) (disk *volume_server_pb.DiskStatus) {
}
return
}
func NewDiskStatusOnStart(path string, config DiskIOProbeConfig) (disk *volume_server_pb.DiskStatus) {
disk = &volume_server_pb.DiskStatus{Dir: path}
diskProbe(disk, config)
if disk.PercentUsed > 95 {
glog.V(0).Infof("disk status: %v", disk)
}
return
}
func diskProbe(disk *volume_server_pb.DiskStatus, config DiskIOProbeConfig) {
actual, _ := diskRegistry.LoadOrStore(disk.Dir, &diskState{})
state := actual.(*diskState)
state.mu.Lock()
if state.isChecking {
state.statFailureCount++
state.statSuccessCount = 0
state.lastStatErr = errors.New("statfs still in progress")
state.updateErrorLocked(disk, config)
state.applyLastGoodStatusLocked(disk)
state.mu.Unlock()
return
}
state.isChecking = true
state.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), diskTimeout)
defer cancel()
probe := &volume_server_pb.DiskStatus{Dir: disk.Dir}
ch := make(chan error, 1)
go func() {
err := fillInDiskStatus(probe)
// Clear the flag only once statfs has actually returned, so a stuck disk
// keeps a single outstanding probe instead of spawning a new one each tick.
state.mu.Lock()
state.isChecking = false
state.mu.Unlock()
ch <- err
}()
var probeErr error
select {
case probeErr = <-ch:
case <-ctx.Done():
// Leave isChecking set; the probe goroutine clears it when statfs returns.
state.mu.Lock()
state.statFailureCount++
state.statSuccessCount = 0
state.lastStatErr = errors.New("statfs timeout")
state.updateErrorLocked(disk, config)
state.applyLastGoodStatusLocked(disk)
state.mu.Unlock()
return
}
state.mu.Lock()
if probeErr != nil {
state.statFailureCount++
state.statSuccessCount = 0
state.lastStatErr = probeErr
state.updateErrorLocked(disk, config)
state.applyLastGoodStatusLocked(disk)
state.mu.Unlock()
return
}
state.observeStatSuccessLocked(config)
disk.All = probe.All
disk.Free = probe.Free
disk.Used = probe.Used
disk.PercentFree = probe.PercentFree
disk.PercentUsed = probe.PercentUsed
state.rememberGoodStatusLocked(disk)
if !config.Enabled {
state.ioFailureCount = 0
state.lastIOErr = nil
state.ioDegraded = false
state.updateErrorLocked(disk, config)
state.mu.Unlock()
return
}
shouldCheckIO := false
ioCheckID := uint64(0)
if time.Since(state.lastIOCheck) >= config.Interval {
if state.isIOChecking {
degraded := state.observeLatencyLocked(
config.Timeout,
true,
config,
)
state.ioDegraded = degraded
state.lastIOCheck = time.Now()
if degraded {
state.ioFailureCount++
state.lastIOErr = errors.New("disk io still in progress")
} else {
state.ioFailureCount = 0
state.lastIOErr = nil
}
} else {
state.isIOChecking = true
state.ioCheckID++
ioCheckID = state.ioCheckID
state.lastIOCheck = time.Now()
shouldCheckIO = true
}
}
state.updateErrorLocked(disk, config)
state.mu.Unlock()
if shouldCheckIO {
checkDiskIOLatency(state, disk, ioCheckID, config)
}
}
type ioProbeResult struct {
err error
latency time.Duration
}
func checkDiskIOLatency(state *diskState, disk *volume_server_pb.DiskStatus, checkID uint64, config DiskIOProbeConfig) {
ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
defer cancel()
ch := make(chan ioProbeResult, 1)
go func() {
start := time.Now()
err := runIOProbe(disk.Dir)
ch <- ioProbeResult{
err: err,
latency: time.Since(start),
}
state.mu.Lock()
if state.ioCheckID == checkID {
state.isIOChecking = false
state.lastIOCheck = time.Now()
}
state.mu.Unlock()
}()
select {
case result := <-ch:
state.mu.Lock()
defer state.mu.Unlock()
if state.ioCheckID != checkID {
return
}
state.isIOChecking = false
state.lastIOCheck = time.Now()
if result.err != nil {
degraded := state.observeLatencyLocked(
config.Timeout,
true,
config,
)
state.ioDegraded = degraded
if degraded {
state.ioFailureCount++
state.lastIOErr = result.err
} else {
state.ioFailureCount = 0
state.lastIOErr = nil
}
state.updateErrorLocked(disk, config)
return
}
degraded := state.observeLatencyLocked(
result.latency,
false,
config,
)
state.ioDegraded = degraded
if degraded {
state.ioFailureCount++
state.lastIOErr = fmt.Errorf(
"disk io degradation detected latency=%v",
result.latency,
)
} else {
state.ioFailureCount = 0
state.lastIOErr = nil
}
state.updateErrorLocked(disk, config)
glog.V(1).Infof(
"disk io latency dir=%s latency=%v ioFailureCount=%d degraded=%v samples=%d error=%v",
disk.Dir,
result.latency,
state.ioFailureCount,
degraded,
len(state.samples),
state.lastIOErr,
)
case <-ctx.Done():
state.mu.Lock()
if state.ioCheckID == checkID {
degraded := state.observeLatencyLocked(
config.Timeout,
true,
config,
)
state.ioDegraded = degraded
if degraded {
state.ioFailureCount++
state.lastIOErr = errors.New("disk io timeout")
} else {
state.ioFailureCount = 0
state.lastIOErr = nil
}
state.lastIOCheck = time.Now()
state.updateErrorLocked(disk, config)
}
state.mu.Unlock()
}
}
func runIOProbe(dir string) error {
path := filepath.Join(dir, ".disk-health-check")
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
return err
}
defer f.Close()
if _, err := f.WriteAt(make([]byte, 4096), 0); err != nil {
return err
}
return f.Sync()
}
func (s *diskState) observeLatencyLocked(latency time.Duration, failed bool, config DiskIOProbeConfig) bool {
now := time.Now()
sample := ioSample{
ts: now,
latency: latency,
failed: failed,
slow: latency >= config.SlowLatency,
}
s.samples = append(s.samples, sample)
cutoff := now.Add(-config.Window)
idx := 0
for _, sample := range s.samples {
if sample.ts.After(cutoff) {
s.samples[idx] = sample
idx++
}
}
s.samples = s.samples[:idx]
total := len(s.samples)
if total < config.MinSamples {
return s.ioDegraded
}
var slowCount int
var failedCount int
for _, sample := range s.samples {
if sample.slow {
slowCount++
}
if sample.failed {
failedCount++
}
}
slowPercent := float64(slowCount) / float64(total) * 100
errorPercent := float64(failedCount) / float64(total) * 100
if !s.ioDegraded {
return slowPercent >= config.SlowPercent ||
errorPercent >= config.ErrorPercent
}
recoverSlowPercent := config.SlowPercent * config.RecoveryCoef
recoverErrorPercent := config.ErrorPercent * config.RecoveryCoef
return slowPercent > recoverSlowPercent ||
errorPercent > recoverErrorPercent
}
func (s *diskState) observeStatSuccessLocked(config DiskIOProbeConfig) {
if s.statFailureCount < config.MaxStatFailures {
s.statFailureCount = 0
s.statSuccessCount = 0
s.lastStatErr = nil
return
}
s.statSuccessCount++
if s.statSuccessCount >= statRecoverySuccesses(config) {
s.statFailureCount = 0
s.statSuccessCount = 0
s.lastStatErr = nil
}
}
func statRecoverySuccesses(config DiskIOProbeConfig) int {
if config.MaxStatFailures <= 1 {
return 1
}
if config.RecoveryCoef <= 0 {
return config.MaxStatFailures * 2
}
successes := int(float64(config.MaxStatFailures) * (1/config.RecoveryCoef - 1))
if successes < 1 {
return 1
}
return successes
}
func (s *diskState) updateErrorLocked(disk *volume_server_pb.DiskStatus, config DiskIOProbeConfig) {
var problems []string
if s.statFailureCount >= config.MaxStatFailures &&
s.lastStatErr != nil {
problems = append(
problems,
fmt.Sprintf("statfs: %v", s.lastStatErr),
)
}
if config.Enabled && s.ioDegraded && s.lastIOErr != nil {
problems = append(
problems,
fmt.Sprintf("io: %v", s.lastIOErr),
)
}
if len(problems) == 0 {
disk.Error = ""
return
}
disk.Error =
"disk health check failed: " +
strings.Join(problems, "; ")
}
func (s *diskState) rememberGoodStatusLocked(disk *volume_server_pb.DiskStatus) {
s.lastGoodStatus = *disk
s.hasLastGood = true
}
func (s *diskState) applyLastGoodStatusLocked(disk *volume_server_pb.DiskStatus) {
if !s.hasLastGood || disk.Error != "" {
return
}
dir := disk.Dir
errorMessage := disk.Error
*disk = s.lastGoodStatus
disk.Dir = dir
disk.Error = errorMessage
}
+2 -2
View File
@@ -4,6 +4,6 @@ package stats
import "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
func fillInDiskStatus(status *volume_server_pb.DiskStatus) {
return
func fillInDiskStatus(status *volume_server_pb.DiskStatus) error {
return nil
}
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more