Files
seaweedFS/weed/s3api/s3api_put_object_helper_test.go
Chris Lu 0d8588e3ae S3: Implement IAM defaults and STS signing key fallback (#8348)
* S3: Implement IAM defaults and STS signing key fallback logic

* S3: Refactor startup order to init SSE-S3 key manager before IAM

* S3: Derive STS signing key from KEK using HKDF for security isolation

* S3: Document STS signing key fallback in security.toml

* fix(s3api): refine anonymous access logic and secure-by-default behavior

- Initialize anonymous identity by default in `NewIdentityAccessManagement` to prevent nil pointer exceptions.
- Ensure `ReplaceS3ApiConfiguration` preserves the anonymous identity if not present in the new configuration.
- Update `NewIdentityAccessManagement` signature to accept `filerClient`.
- In legacy mode (no policy engine), anonymous defaults to Deny (no actions), preserving secure-by-default behavior.
- Use specific `LookupAnonymous` method instead of generic map lookup.
- Update tests to accommodate signature changes and verify improved anonymous handling.

* feat(s3api): make IAM configuration optional

- Start S3 API server without a configuration file if `EnableIam` option is set.
- Default to `Allow` effect for policy engine when no configuration is provided (Zero-Config mode).
- Handle empty configuration path gracefully in `loadIAMManagerFromConfig`.
- Add integration test `iam_optional_test.go` to verify empty config behavior.

* fix(iamapi): fix signature mismatch in NewIdentityAccessManagementWithStore

* fix(iamapi): properly initialize FilerClient instead of passing nil

* fix(iamapi): properly initialize filer client for IAM management

- Instead of passing `nil`, construct a `wdclient.FilerClient` using the provided `Filers` addresses.
- Ensure `NewIdentityAccessManagementWithStore` receives a valid `filerClient` to avoid potential nil pointer dereferences or limited functionality.

* clean: remove dead code in s3api_server.go

* refactor(s3api): improve IAM initialization, safety and anonymous access security

* fix(s3api): ensure IAM config loads from filer after client init

* fix(s3): resolve test failures in integration, CORS, and tagging tests

- Fix CORS tests by providing explicit anonymous permissions config
- Fix S3 integration tests by setting admin credentials in init
- Align tagging test credentials in CI with IAM defaults
- Added goroutine to retry IAM config load in iamapi server

* fix(s3): allow anonymous access to health targets and S3 Tables when identities are present

* fix(ci): use /healthz for Caddy health check in awscli tests

* iam, s3api: expose DefaultAllow from IAM and Policy Engine

This allows checking the global "Open by Default" configuration from
other components like S3 Tables.

* s3api/s3tables: support DefaultAllow in permission logic and handler

Updated CheckPermissionWithContext to respect the DefaultAllow flag
in PolicyContext. This enables "Open by Default" behavior for
unauthenticated access in zero-config environments. Added a targeted
unit test to verify the logic.

* s3api/s3tables: propagate DefaultAllow through handlers

Propagated the DefaultAllow flag to individual handlers for
namespaces, buckets, tables, policies, and tagging. This ensures
consistent "Open by Default" behavior across all S3 Tables API
endpoints.

* s3api: wire up DefaultAllow for S3 Tables API initialization

Updated registerS3TablesRoutes to query the global IAM configuration
and set the DefaultAllow flag on the S3 Tables API server. This
completes the end-to-end propagation required for anonymous access in
zero-config environments. Added a SetDefaultAllow method to
S3TablesApiServer to facilitate this.

* s3api: fix tests by adding DefaultAllow to mock IAM integrations

The IAMIntegration interface was updated to include DefaultAllow(),
breaking several mock implementations in tests. This commit fixes
the build errors by adding the missing method to the mocks.

* env

* ensure ports

* env

* env

* fix default allow

* add one more test using non-anonymous user

* debug

* add more debug

* less logs
2026-02-16 13:59:13 -08:00

186 lines
5.7 KiB
Go

package s3api
import (
"net/http"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/credential"
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
)
func TestGetRequestDataReader_ChunkedEncodingWithoutIAM(t *testing.T) {
// Create an S3ApiServer with IAM disabled
s3a := &S3ApiServer{
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
}
// Ensure IAM is disabled for this test
s3a.iam.isAuthEnabled = false
tests := []struct {
name string
contentSha256 string
expectedError s3err.ErrorCode
shouldProcess bool
description string
}{
{
name: "RegularRequest",
contentSha256: "",
expectedError: s3err.ErrNone,
shouldProcess: false,
description: "Regular requests without chunked encoding should pass through unchanged",
},
{
name: "StreamingSignedWithoutIAM",
contentSha256: "STREAMING-AWS4-HMAC-SHA256-PAYLOAD",
expectedError: s3err.ErrAuthNotSetup,
shouldProcess: false,
description: "Streaming signed requests should fail when IAM is disabled",
},
{
name: "StreamingUnsignedWithoutIAM",
contentSha256: "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
expectedError: s3err.ErrNone,
shouldProcess: true,
description: "Streaming unsigned requests should be processed even when IAM is disabled",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
body := strings.NewReader("test data")
req, _ := http.NewRequest("PUT", "/bucket/key", body)
if tt.contentSha256 != "" {
req.Header.Set("x-amz-content-sha256", tt.contentSha256)
}
dataReader, errCode := getRequestDataReader(s3a, req)
// Check error code
if errCode != tt.expectedError {
t.Errorf("Expected error code %v, got %v", tt.expectedError, errCode)
}
// For successful cases, check if processing occurred
if errCode == s3err.ErrNone {
if tt.shouldProcess {
// For chunked requests, the reader should be different from the original body
if dataReader == req.Body {
t.Error("Expected dataReader to be processed by newChunkedReader, but got raw request body")
}
} else {
// For regular requests, the reader should be the same as the original body
if dataReader != req.Body {
t.Error("Expected dataReader to be the same as request body for regular requests")
}
}
}
t.Logf("Test case: %s - %s", tt.name, tt.description)
})
}
}
func TestGetRequestDataReader_AuthTypeDetection(t *testing.T) {
// Create an S3ApiServer with IAM disabled
s3a := &S3ApiServer{
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
}
s3a.iam.isAuthEnabled = false
// Test the specific case mentioned in the issue where chunked data
// with checksum headers would be stored incorrectly
t.Run("ChunkedDataWithChecksum", func(t *testing.T) {
// Simulate a request with chunked data and checksum trailer
body := strings.NewReader("test content")
req, _ := http.NewRequest("PUT", "/bucket/key", body)
req.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
req.Header.Set("x-amz-trailer", "x-amz-checksum-crc32")
// Verify the auth type is detected correctly
authType := getRequestAuthType(req)
if authType != authTypeStreamingUnsigned {
t.Errorf("Expected authTypeStreamingUnsigned, got %v", authType)
}
// Verify the request is processed correctly
dataReader, errCode := getRequestDataReader(s3a, req)
if errCode != s3err.ErrNone {
t.Errorf("Expected no error, got %v", errCode)
}
// The dataReader should be processed by newChunkedReader
if dataReader == req.Body {
t.Error("Expected dataReader to be processed by newChunkedReader to handle chunked encoding")
}
})
}
func TestGetRequestDataReader_IAMEnabled(t *testing.T) {
// Create an S3ApiServer with IAM enabled
s3a := &S3ApiServer{
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
}
s3a.iam.isAuthEnabled = true
t.Run("StreamingUnsignedWithIAMEnabled", func(t *testing.T) {
body := strings.NewReader("test data")
req, _ := http.NewRequest("PUT", "/bucket/key", body)
req.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
dataReader, errCode := getRequestDataReader(s3a, req)
// Should succeed and be processed
if errCode != s3err.ErrNone {
t.Errorf("Expected no error, got %v", errCode)
}
// Should be processed by newChunkedReader
if dataReader == req.Body {
t.Error("Expected dataReader to be processed by newChunkedReader")
}
})
}
// Test helper to verify auth type detection works correctly
func TestAuthTypeDetection(t *testing.T) {
tests := []struct {
name string
headers map[string]string
expectedType authType
}{
{
name: "StreamingUnsigned",
headers: map[string]string{"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER"},
expectedType: authTypeStreamingUnsigned,
},
{
name: "StreamingSigned",
headers: map[string]string{"x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"},
expectedType: authTypeStreamingSigned,
},
{
name: "Regular",
headers: map[string]string{},
expectedType: authTypeAnonymous,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("PUT", "/bucket/key", strings.NewReader("test"))
for key, value := range tt.headers {
req.Header.Set(key, value)
}
authType := getRequestAuthType(req)
if authType != tt.expectedType {
t.Errorf("Expected auth type %v, got %v", tt.expectedType, authType)
}
})
}
}