Files
seaweedfs/weed/images/gateway
1815f140b6 fips140=only: refuse JWT signing keys and S3 secrets too short for HMAC (#12912)
* fips140=only: refuse HMAC keys too short for FIPS mode where they are configured

Under GODEBUG=fips140=only, hmac.New panics on keys shorter than 112 bits
(14 bytes). A short JWT signing key starts fine and then kills weed server
on the first write (the master's Assign mints a volume JWT in an
unrecovered gRPC handler), and an S3 secret of 8 or 9 characters (the
SigV4 signing key is HMAC keyed with "AWS4"+secret) makes every request
from that identity panic in its handler.

Only under crypto/fips140.Enforced():

- security.toml: LoadSecurityConfiguration exits with an error naming the
  setting when a jwt.signing / jwt.filer_signing key, read key or
  previous key is under 14 bytes. LoadFilerJwtFromFile (filer.sync
  -a.security/-b.security) returns the same error, and
  Guard.UpdateSigningKeys keeps the keys in effect on a reload that
  brings in a short key.
- S3: SigV4 (header, presigned, streaming seed and POST policy) answers
  InvalidAccessKeyId, as for an inactive key, when the credential's
  secret is under 10 characters, and logs the access key. Loading such a
  credential logs a warning; it stays loaded and stored.
- IAM CreateAccessKey (IAM API, embedded IAM, admin UI) requires a
  caller-supplied SecretAccessKey of at least 10 characters.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: check jwt.filer_signing.subscribe.key and the imgproxy key too

The filer verifies metadata subscription tokens with
jwt.filer_signing.subscribe.key and `weed shell fs.meta.token` signs them
with it, so under GODEBUG=fips140=only a short value panics on first use;
LoadSecurityConfiguration now refuses it with the other JWT keys. `weed
image` signs imgproxy URLs with HMAC keyed with IMGPROXY_KEY;
gateway.New refuses a key under 14 bytes in that mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: warn about JWT keys too short for fips140=only outside that mode

Outside GODEBUG=fips140=only a JWT signing key under 14 bytes works, so
LoadSecurityConfiguration (every weed command but fuse) and
LoadFilerJwtFromFile now log a warning naming the setting instead of saying
nothing: such a key is refused under fips140=only, and a future release may
refuse it in every mode, so the warning asks for a rotation to a longer key
with previous_key while it still works. A short previous_key holds the old
key during that rotation, so its warning only asks to clear it afterwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: refuse a short secret under fips140=only with AccessDenied, not InvalidAccessKeyId

InvalidAccessKeyId says the access key does not exist, so a client refused
for a secret too short for fips140=only went looking for a missing key. The
new ErrFips140SecretTooShort answers AccessDenied (403) with "This access
key cannot be used while the server runs in FIPS 140 mode. Ask the
administrator for a new secret." The message leaves out the length rule:
the refusal comes before the request's signature is checked, so any caller
that knows the access key ID would learn the secret is short. The embedded
IAM API maps it to AccessDenied as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: log an S3 secret too short for fips140=only at error level

Under GODEBUG=fips140=only every request signed with such a key is refused,
so the identity is unusable; the load-time message is an error, not a
warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util, security: name every JWT key too short for fips140=only in one error

CheckFips140SigningKeys stopped at the first short key, so a cluster with
two short keys failed at startup, was fixed, and failed again on the next
one. CheckFips140HmacKeys checks every setting and names each short key
("jwt.signing.key is 10 bytes, jwt.filer_signing.key is 8 bytes; ..."); with
one short key the message is unchanged. Guard reloads use it as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fips140=only: say what happened, to what and what to do in the short-key messages

The messages about S3 secrets and JWT keys too short for FIPS 140 now start
from the process's mode, name the key, its owner or file, the limit, and the
fix:

- loading S3 identities: "this process runs with GODEBUG=fips140=only, and
  refuses all S3 requests signed with access key ... (identity ...) because
  its secret is shorter than the 10 characters FIPS 140 needs for SigV4
  secrets; give that access key a new secret of at least 10 characters";
- a refused request logs its request ID, which the client gets back, its
  client IP (as the audit log records it, s3err.RemoteIP) and the identity;
- the startup refusal names security.toml's path and every short key, and
  links the wiki section on replacing them with or without downtime;
- the startup warning outside fips140=only says the server would not start
  in that mode, and links the same section.

A short previous_key no longer gets a warning outside fips140=only: it holds
the old key while switching to a longer one, and under fips140=only the
startup refusal names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: a reload under fips140=only drops short previous keys, not the new keys

UpdateSigningKeys refused the whole key set when a previous key was too short,
so a volume server kept its old keys while the filer's volume signer, which
gets no previous keys, took the new ones; proxied chunk reads then failed with
401. Short current keys still keep the keys in effect. A short previous key is
dropped with an error log instead: nothing under fips140=only can sign with it,
so no token is lost, and every server ends up with the same current keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security: check only the filer keys filer.sync uses in its security files

LoadFilerJwtFromFile checked every JWT setting in a -a.security/-b.security
file, so under fips140=only filer.sync refused to start over a short volume or
previous key it never uses. It now checks jwt.filer_signing.key and its read
key, after the fallback to the process-wide configuration, which startup
checks already.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: answer a short secret under fips140=only with SignatureDoesNotMatch

A distinct answer before the signature is checked told anyone who knows an
access key ID that its secret is short. The refusal now runs where the
signature would be checked, after the permission, expiry and signed-header
checks, and answers the SignatureDoesNotMatch a wrong signature gets. The
server log keeps the cause, the request ID and the client. This drops
ErrFips140SecretTooShort and its IAM mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* security, filer: keep Basic Auth on a reload whose JWT keys are refused

When a reload under fips140=only refused the new filer JWT keys, the filer
still removed Basic Auth, so a configuration that switches from Basic Auth to
short JWT keys left the filer with neither. UpdateSigningKeys and
ReloadSigningKeys now report whether the new keys are in effect, and the
filer drops Basic Auth only when they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: do not install a volume read key too short for fips140=only

A reload installed jwt.signing.read.key into the read-signing cache without a
length check, so under fips140=only a short key made later chunk reads panic
signing with it. loadJwtConfig now leaves the key in effect when the new one
is too short.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util/http: keep the volume read key when the volume guard would refuse the reload

Under GODEBUG=fips140=only a volume server's reload keeps its keys when
jwt.signing.key or jwt.signing.read.key is too short. The read-key cache
checked only the read key, so it could sign reads with a key the volume
servers had not taken. It now checks the same two keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: build the short-key list in one append in CheckFips140HmacKeys

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: keep the blank line before the permission check in verifyV4Signature

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: skip TestFIPS140OnlyShortSecret under real fips140=only enforcement

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-25 13:07:15 -08:00
..

On-demand image gateway

weed image is an optional public image endpoint. Original images remain in SeaweedFS. On a cache miss, a separate imgproxy service resizes and encodes the image; results enter a bounded in-process cache. Subsequent requests recheck anonymous source access before reusing results. Cache eviction and process restarts do not affect stored objects. No S3 objects, Filer entries, or application file records are created for processed images.

flowchart LR
  Browser --> CDN
  CDN --> Gateway[weed image]
  Gateway -->|Check source access and revision on every request| S3[SeaweedFS S3]
  Gateway -->|Cache miss| imgproxy
  imgproxy -->|Anonymous source read| S3
  Gateway --> Cache[Bounded memory cache]

Request interface

/image.png?x-oss-process=image/resize,w_640/quality,Q_85/format,webp
/image.png?x-oss-process=image/resize,w_240,h_240,m_lfit,limit_1/format,webp
/image.png?x-oss-process=image/format,jpg/quality,Q_85
  • resize accepts w, h, m_lfit, and limit_1. It preserves aspect ratio and never enlarges the source. One dimension determines the other; two dimensions specify a bounding box. Any unspecified axis uses maxDimension as its bound, including format-only requests; neither output axis can exceed it.
  • quality,Q_1 through quality,Q_100 specify absolute quality, defaulting to 85. Aliyun's relative quality q has no equivalent here and returns 400.
  • format accepts jpg, jpeg, png, and webp, defaulting to WebP.
  • The default maximum output dimension is 4096. Repeated parameters, unknown operations, cropping, watermarks, animation processing, automatic format negotiation, and other OSS operations are unsupported. PNG output is lossless; quality mainly affects JPEG/WebP. Animated sources use imgproxy's default first-frame behavior.
  • A single versionId may select a specific source version. Other query parameters are rejected.
  • GET, HEAD, Range, and conditional requests apply to the returned representation. Processed images have independent SHA-256 ETags and byte lengths. Derived responses use ETag validators rather than the source modification date, which cannot distinguish overwrites within the same second. Without a processing parameter the gateway reads the original image, including single byte ranges.
  • Original GET and HEAD responses reject unsupported or malformed media types, including HTML and all image/*+xml subtypes. Non-XML image types and octet-stream objects retain their original Content-Type, including parameters. This prevents uploaded executable documents from being served under the gateway's origin. A 304 may omit Content-Type; an explicit unsupported type is still rejected so conditional responses cannot reclassify previously cached bytes.

This implements a limited subset of OSS image processing parameters, rather than full Aliyun OSS compatibility. It runs on a separate port and does not change existing weed s3, Filer, or Volume services.

Running the gateway

Start a separate imgproxy service, then run:

weed image \
  -source=http://s3:8333/public-bucket \
  -imgproxy=http://imgproxy:8080 \
  -ip.bind=0.0.0.0 -port=8334 \
  -cacheCapacityMB=64 -concurrency=8 \
  -maxSourceMB=25 -maxResultMB=10 -maxDimension=4096 -timeout=15s

source fixes the source HTTP(S) URL, optionally including a bucket path or a bucket domain pointing to S3. With http://s3:8333/public-bucket, a client request for /a/b.png reads http://s3:8333/public-bucket/a/b.png. Both backend URLs must omit credentials, queries, and fragments. The imgproxy URL must be a root URL without a path prefix; prefixed URLs are rejected at startup. Dot segments and backslashes, including repeatedly escaped forms, are rejected to prevent backend path normalization from escaping a fixed bucket prefix. The gateway and imgproxy must reach the same source.

Configure imgproxy limits and isolate the encoder with container or process resource limits. Suggested imgproxy settings:

IMGPROXY_WORKERS=2
IMGPROXY_REQUESTS_QUEUE_SIZE=8
IMGPROXY_MAX_SRC_FILE_SIZE=26214400
IMGPROXY_MAX_SRC_RESOLUTION=25
IMGPROXY_MAX_RESULT_DIMENSION=4096
IMGPROXY_MAX_ANIMATION_FRAMES=1
IMGPROXY_MAX_REDIRECTS=0
IMGPROXY_ALLOWED_PROCESSING_OPTIONS=rs,q,f
IMGPROXY_ALLOWED_SOURCES=http://s3:8333/public-bucket/

These variables apply to imgproxy 3.x. In imgproxy 4.x, some source security limits move to separate source configuration; configure equivalent restrictions according to that version's documentation. File size limits do not replace pixel and memory limits. The gateway does not decode images and cannot enforce encoder-side limits.

Set hexadecimal IMGPROXY_KEY and IMGPROXY_SALT in both services to sign backend requests. The gateway supports one key/salt pair with full SHA-256 signatures; imgproxy must use the default 32-byte signature length. Unsigned requests are only appropriate on an isolated trusted network. Keep signing material out of command lines, public configuration, and logs.

Access and caching

The endpoint only accepts anonymous public reads. It rejects client Authorization, S3 signature parameters, and x-amz-* request headers. Browser cookies are ignored and never forwarded to backends. The gateway does not create administrative credentials or signed source URLs for private objects. Use the existing S3 endpoint for private images.

Every derived request performs an anonymous source HEAD, including cache hits, HEAD, and 304 requests. The encoder uses anonymous GET, so the source must apply the same public-read policy to HEAD and GET; SeaweedFS S3 authorizes both as object reads. A source 403 or 404 rejects derived requests even if cached bytes remain. Source URL, ETag, modification time, length, version ID, and canonical processing options form the cache key. Sources without ETags are not cached. A revision change detected during encoding returns 409, allowing a client retry. Use immutable object names for unversioned sources to avoid races between metadata checks and frequent source overwrites.

Concurrent misses for the same result share one encoding job. A cancelled waiter does not cancel work needed by other waiters. If all waiters leave, the job may run until its independent processing timeout; separate work tokens still bound such background jobs. Source metadata checks, shared encoding (including its final source recheck), and client writes each receive a full timeout budget. A slow initial HEAD does not shorten the caller's wait for shared encoding. The HTTP server also bounds request body reads to 10 seconds. Requests, result sizes, duration, and concurrency are bounded. Original single-range responses are limited by the complete object's size, not just the selected range. Excess concurrency returns 429; errors are never cached. The cache is limited by bytes and 1024 entries, defaults to 64 MiB, and can be disabled with -cacheCapacityMB=0. Each instance has its own cache, empty after restart.

Responses default to Cache-Control: no-cache, allowing downstream storage with mandatory revalidation so source access is checked on every request. A CDN must preserve x-oss-process and versionId and include the complete query in its cache key. If you explicitly set a CDN TTL for permanently public immutable objects, CDN hits bypass the gateway. Revocation or deletion then requires a CDN purge, otherwise access changes only take effect after TTL expiry. Errors use no-store.

Configure HTTPS, CORS, and external rate limits in the existing reverse proxy or CDN. Route only public image GET/HEAD requests to this gateway. Uploads, listings, signed reads, and other S3 operations continue using the existing S3 endpoint.

Validation

go test -race ./weed/images/gateway
go vet ./weed/images/gateway
CGO_ENABLED=0 go build ./weed

Tests cover revocation and deletion, overwrite invalidation, explicit versions, shared work and cancellation, resource limits, backend failures, signatures and path escaping, and HEAD/ETag/Range semantics. Before deployment, also test real SeaweedFS and imgproxy for dimensions, media types, transparency, and regeneration after clearing the cache.