Add AssumeRole and AssumeRoleWithLDAPIdentity STS actions (#8003)

* test: add integration tests for AssumeRole and AssumeRoleWithLDAPIdentity STS actions

- Add s3_sts_assume_role_test.go with comprehensive tests for AssumeRole:
  * Parameter validation (missing RoleArn, RoleSessionName, invalid duration)
  * AWS SigV4 authentication with valid/invalid credentials
  * Temporary credential generation and usage

- Add s3_sts_ldap_test.go with tests for AssumeRoleWithLDAPIdentity:
  * Parameter validation (missing LDAP credentials, RoleArn)
  * LDAP authentication scenarios (valid/invalid credentials)
  * Integration with LDAP server (when configured)

- Update Makefile with new test targets:
  * test-sts: run all STS tests
  * test-sts-assume-role: run AssumeRole tests only
  * test-sts-ldap: run LDAP STS tests only
  * test-sts-suite: run tests with full service lifecycle

- Enhance setup_all_tests.sh:
  * Add OpenLDAP container setup for LDAP testing
  * Create test LDAP users (testuser, ldapadmin)
  * Set LDAP environment variables for tests
  * Update cleanup to remove LDAP container

- Fix setup_keycloak.sh:
  * Enable verbose error logging for realm creation
  * Improve error diagnostics

Tests use fail-fast approach (t.Fatal) when server not configured,
ensuring clear feedback when infrastructure is missing.

* feat: implement AssumeRole and AssumeRoleWithLDAPIdentity STS actions

Implement two new STS actions to match MinIO's STS feature set:

**AssumeRole Implementation:**
- Add handleAssumeRole with full AWS SigV4 authentication
- Integrate with existing IAM infrastructure via verifyV4Signature
- Validate required parameters (RoleArn, RoleSessionName)
- Validate DurationSeconds (900-43200 seconds range)
- Generate temporary credentials with expiration
- Return AWS-compatible XML response

**AssumeRoleWithLDAPIdentity Implementation:**
- Add handleAssumeRoleWithLDAPIdentity handler (stub)
- Validate LDAP-specific parameters (LDAPUsername, LDAPPassword)
- Validate common STS parameters (RoleArn, RoleSessionName, DurationSeconds)
- Return proper error messages for missing LDAP provider
- Ready for LDAP provider integration

**Routing Fixes:**
- Add explicit routes for AssumeRole and AssumeRoleWithLDAPIdentity
- Prevent IAM handler from intercepting authenticated STS requests
- Ensure proper request routing priority

**Handler Infrastructure:**
- Add IAM field to STSHandlers for SigV4 verification
- Update NewSTSHandlers to accept IAM reference
- Add STS-specific error codes and response types
- Implement writeSTSErrorResponse for AWS-compatible errors

The AssumeRole action is fully functional and tested.
AssumeRoleWithLDAPIdentity requires LDAP provider implementation.

* fix: update IAM matcher to exclude STS actions from interception

Update the IAM handler matcher to check for STS actions (AssumeRole,
AssumeRoleWithWebIdentity, AssumeRoleWithLDAPIdentity) and exclude them
from IAM handler processing. This allows STS requests to be handled by
the STS fallback handler even when they include AWS SigV4 authentication.

The matcher now parses the form data to check the Action parameter and
returns false for STS actions, ensuring they are routed to the correct
handler.

Note: This is a work-in-progress fix. Tests are still showing some
routing issues that need further investigation.

* fix: address PR review security issues for STS handlers

This commit addresses all critical security issues from PR review:

Security Fixes:
- Use crypto/rand for cryptographically secure credential generation
  instead of time.Now().UnixNano() (fixes predictable credentials)
- Add sts:AssumeRole permission check via VerifyActionPermission to
  prevent unauthorized role assumption
- Generate proper session tokens using crypto/rand instead of
  placeholder strings

Code Quality Improvements:
- Refactor DurationSeconds parsing into reusable parseDurationSeconds()
  helper function used by all three STS handlers
- Create generateSecureCredentials() helper for consistent and secure
  temporary credential generation
- Fix iamMatcher to check query string as fallback when Action not
  found in form data

LDAP Provider Implementation:
- Add go-ldap/ldap/v3 dependency
- Create LDAPProvider implementing IdentityProvider interface with
  full LDAP authentication support (connect, bind, search, groups)
- Update ProviderFactory to create real LDAP providers
- Wire LDAP provider into AssumeRoleWithLDAPIdentity handler

Test Infrastructure:
- Add LDAP user creation verification step in setup_all_tests.sh

* fix: address PR feedback (Round 2) - config validation & provider improvements

- Implement `validateLDAPConfig` in `ProviderFactory`
- Improve `LDAPProvider.Initialize`:
  - Support `connectionTimeout` parsing (string/int/float) from config map
  - Warn if `BindDN` is present but `BindPassword` is empty
- Improve `LDAPProvider.GetUserInfo`:
  - Add fallback to `searchUserGroups` if `memberOf` returns no groups (consistent with Authenticate)

* fix: address PR feedback (Round 3) - LDAP connection improvements & build fix

- Improve `LDAPProvider` connection handling:
  - Use `net.Dialer` with configured timeout for connection establishment
  - Enforce TLS 1.2+ (`MinVersion: tls.VersionTLS12`) for both LDAPS and StartTLS
- Fix build error in `s3api_sts.go` (format verb for ErrorCode)

* fix: address PR feedback (Round 4) - LDAP hardening, Authz check & Routing fix

- LDAP Provider Hardening:
  - Prevent re-initialization
  - Enforce single user match in `GetUserInfo` (was explicit only in Authenticate)
  - Ensure connection closure if StartTLS fails
- STS Handlers:
  - Add robust provider detection using type assertion
  - **Security**: Implement authorization check (`VerifyActionPermission`) after LDAP authentication
- Routing:
  - Update tests to reflect that STS actions are handled by STS handler, not generic IAM

* fix: address PR feedback (Round 5) - JWT tokens, ARN formatting, PrincipalArn

CRITICAL FIXES:
- Replace standalone credential generation with STS service JWT tokens
  - handleAssumeRole now generates proper JWT session tokens
  - handleAssumeRoleWithLDAPIdentity now generates proper JWT session tokens
  - Session tokens can be validated across distributed instances

- Fix ARN formatting in responses
  - Extract role name from ARN using utils.ExtractRoleNameFromArn()
  - Prevents malformed ARNs like "arn:aws:sts::assumed-role/arn:aws:iam::..."

- Add configurable AccountId for federated users
  - Add AccountId field to STSConfig (defaults to "111122223333")
  - PrincipalArn now uses configured account ID instead of hardcoded "aws"
  - Enables proper trust policy validation

IMPROVEMENTS:
- Sanitize LDAP authentication error messages (don't leak internal details)
- Remove duplicate comment in provider detection
- Add utils import for ARN parsing utilities

* feat: implement LDAP connection pooling to prevent resource exhaustion

PERFORMANCE IMPROVEMENT:
- Add connection pool to LDAPProvider (default size: 10 connections)
- Reuse LDAP connections across authentication requests
- Prevent file descriptor exhaustion under high load

IMPLEMENTATION:
- connectionPool struct with channel-based connection management
- getConnection(): retrieves from pool or creates new connection
- returnConnection(): returns healthy connections to pool
- createConnection(): establishes new LDAP connection with TLS support
- Close(): cleanup method to close all pooled connections
- Connection health checking (IsClosing()) before reuse

BENEFITS:
- Reduced connection overhead (no TCP handshake per request)
- Better resource utilization under load
- Prevents "too many open files" errors
- Non-blocking pool operations (creates new conn if pool empty)

* fix: correct TokenGenerator access in STS handlers

CRITICAL FIX:
- Make TokenGenerator public in STSService (was private tokenGenerator)
- Update all references from Config.TokenGenerator to TokenGenerator
- Remove TokenGenerator from STSConfig (it belongs in STSService)

This fixes the "NotImplemented" errors in distributed and Keycloak tests.
The issue was that Round 5 changes tried to access Config.TokenGenerator
which didn't exist - TokenGenerator is a field in STSService, not STSConfig.

The TokenGenerator is properly initialized in STSService.Initialize() and
is now accessible for JWT token generation in AssumeRole handlers.

* fix: update tests to use public TokenGenerator field

Following the change to make TokenGenerator public in STSService,
this commit updates the test files to reference the correct public field name.
This resolves compilation errors in the IAM STS test suite.

* fix: update distributed tests to use valid Keycloak users

Updated s3_iam_distributed_test.go to use 'admin-user' and 'read-user'
which exist in the standard Keycloak setup provided by setup_keycloak.sh.
This resolves 'unknown test user' errors in distributed integration tests.

* fix: ensure iam_config.json exists in setup target for CI

The GitHub Actions workflow calls 'make setup' which was not creating
iam_config.json, causing the server to start without IAM integration
enabled (iamIntegration = nil), resulting in NotImplemented errors.

Now 'make setup' copies iam_config.local.json to iam_config.json if
it doesn't exist, ensuring IAM is properly configured in CI.

* fix(iam/ldap): fix connection pool race and rebind corruption

- Add atomic 'closed' flag to connection pool to prevent racing on Close()
- Rebind authenticated user connections back to service account before returning to pool
- Close connections on error instead of returning potentially corrupted state to pool

* fix(iam/ldap): populate standard TokenClaims fields in ValidateToken

- Set Subject, Issuer, Audience, IssuedAt, and ExpiresAt to satisfy the interface
- Use time.Time for timestamps as required by TokenClaims struct
- Default to 1 hour TTL for LDAP tokens

* fix(s3api): include account ID in STS AssumedRoleUser ARN

- Consistent with AWS, include the account ID in the assumed-role ARN
- Use the configured account ID from STS service if available, otherwise default to '111122223333'
- Apply to both AssumeRole and AssumeRoleWithLDAPIdentity handlers
- Also update .gitignore to ignore IAM test environment files

* refactor(s3api): extract shared STS credential generation logic

- Move common logic for session claims and credential generation to prepareSTSCredentials
- Update handleAssumeRole and handleAssumeRoleWithLDAPIdentity to use the helper
- Remove stale comments referencing outdated line numbers

* feat(iam/ldap): make pool size configurable and add audience support

- Add PoolSize to LDAPConfig (default 10)
- Add Audience to LDAPConfig to align with OIDC validation
- Update initialization and ValidateToken to use new fields

* update tests

* debug

* chore(iam): cleanup debug prints and fix test config port

* refactor(iam): use mapstructure for LDAP config parsing

* feat(sts): implement strict trust policy validation for AssumeRole

* test(iam): refactor STS tests to use AWS SDK signer

* test(s3api): implement ValidateTrustPolicyForPrincipal in MockIAMIntegration

* fix(s3api): ensure IAM matcher checks query string on ParseForm error

* fix(sts): use crypto/rand for secure credentials and extract constants

* fix(iam): fix ldap connection leaks and add insecure warning

* chore(iam): improved error wrapping and test parameterization

* feat(sts): add support for LDAPProviderName parameter

* Update weed/iam/ldap/ldap_provider.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update weed/s3api/s3api_sts.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix(sts): use STSErrSTSNotReady when LDAP provider is missing

* fix(sts): encapsulate TokenGenerator in STSService and add getter

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Chris Lu
2026-01-12 10:45:24 -08:00
committed by GitHub
parent d7c30fdb2b
commit 06391701ed
30 changed files with 2027 additions and 123 deletions

View File

@@ -57,6 +57,10 @@ setup: ## Setup test environment
@echo "Setting up test environment..."
@mkdir -p test-volume-data/filerldb2
@mkdir -p test-volume-data/m9333
@if [ ! -f iam_config.json ]; then \
echo "Creating iam_config.json from iam_config.local.json..."; \
cp iam_config.local.json iam_config.json; \
fi
start-services: ## Start SeaweedFS services for testing
@echo "Starting SeaweedFS services using weed mini..."
@@ -125,6 +129,10 @@ clean: stop-services ## Clean up test environment
@rm -rf test-volume-data
@rm -f weed-*.log
@rm -f *.test
@rm -f iam_config.json
@rm -f .test_env
@docker rm -f keycloak-iam-test >/dev/null 2>&1 || true
@docker rm -f openldap-iam-test >/dev/null 2>&1 || true
@echo "Cleanup complete"
logs: ## Show service logs
@@ -176,6 +184,20 @@ test-context: ## Test only contextual policy enforcement
test-presigned: ## Test only presigned URL integration
go test -v -run TestS3IAMPresignedURLIntegration ./...
test-sts: ## Run all STS tests
go test -v -run "TestSTS" ./...
test-sts-assume-role: ## Run AssumeRole STS tests
go test -v -run "TestSTSAssumeRole" ./...
test-sts-ldap: ## Run LDAP STS tests
go test -v -run "TestSTSLDAP" ./...
test-sts-suite: start-services ## Run all STS tests with full environment setup/teardown
@echo "Running STS test suite..."
-go test -v -run "TestSTS" ./...
@$(MAKE) stop-services
# Performance testing
benchmark: setup start-services wait-for-services ## Run performance benchmarks
@echo "🏁 Running IAM performance benchmarks..."
@@ -240,7 +262,7 @@ docker-build: ## Build custom SeaweedFS image for Docker tests
# All PHONY targets
.PHONY: test test-quick run-tests setup start-services stop-services wait-for-services clean logs status debug
.PHONY: test-auth test-policy test-expiration test-multipart test-bucket-policy test-context test-presigned
.PHONY: test-auth test-policy test-expiration test-multipart test-bucket-policy test-context test-presigned test-sts test-sts-assume-role test-sts-ldap
.PHONY: benchmark ci watch install-deps docker-test docker-up docker-down docker-logs docker-build
.PHONY: test-distributed test-performance test-stress test-versioning-stress test-keycloak-full test-all-previously-skipped setup-all-tests help-advanced
@@ -275,6 +297,9 @@ test-all-previously-skipped: ## Run all previously skipped tests
@echo "🎯 Running all previously skipped tests..."
@./run_all_tests.sh
.PHONY: cleanup
cleanup: clean
setup-all-tests: ## Setup environment for all tests (including Keycloak)
@echo "🚀 Setting up complete test environment..."
@./setup_all_tests.sh

View File

@@ -1,7 +1,7 @@
{
"sts": {
"tokenDuration": "1h",
"maxSessionLength": "12h",
"maxSessionLength": "12h",
"issuer": "seaweedfs-sts",
"signingKey": "dGVzdC1zaWduaW5nLWtleS0zMi1jaGFyYWN0ZXJzLWxvbmc="
},
@@ -24,7 +24,11 @@
"clientSecret": "seaweedfs-s3-secret",
"jwksUri": "http://localhost:8080/realms/seaweedfs-test/protocol/openid-connect/certs",
"userInfoUri": "http://localhost:8080/realms/seaweedfs-test/protocol/openid-connect/userinfo",
"scopes": ["openid", "profile", "email"],
"scopes": [
"openid",
"profile",
"email"
],
"claimsMapping": {
"username": "preferred_username",
"email": "email",
@@ -38,13 +42,13 @@
"role": "arn:aws:iam::role/KeycloakAdminRole"
},
{
"claim": "roles",
"claim": "roles",
"value": "s3-read-only",
"role": "arn:aws:iam::role/KeycloakReadOnlyRole"
},
{
"claim": "roles",
"value": "s3-write-only",
"value": "s3-write-only",
"role": "arn:aws:iam::role/KeycloakWriteOnlyRole"
},
{
@@ -73,15 +77,19 @@
"Principal": {
"Federated": "test-oidc"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3AdminPolicy"],
"attachedPolicies": [
"S3AdminPolicy"
],
"description": "Admin role for testing"
},
{
"roleName": "TestReadOnlyRole",
"roleName": "TestReadOnlyRole",
"roleArn": "arn:aws:iam::role/TestReadOnlyRole",
"trustPolicy": {
"Version": "2012-10-17",
@@ -91,15 +99,19 @@
"Principal": {
"Federated": "test-oidc"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3ReadOnlyPolicy"],
"attachedPolicies": [
"S3ReadOnlyPolicy"
],
"description": "Read-only role for testing"
},
{
"roleName": "TestWriteOnlyRole",
"roleName": "TestWriteOnlyRole",
"roleArn": "arn:aws:iam::role/TestWriteOnlyRole",
"trustPolicy": {
"Version": "2012-10-17",
@@ -109,11 +121,15 @@
"Principal": {
"Federated": "test-oidc"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3WriteOnlyPolicy"],
"attachedPolicies": [
"S3WriteOnlyPolicy"
],
"description": "Write-only role for testing"
},
{
@@ -127,11 +143,15 @@
"Principal": {
"Federated": "keycloak"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3AdminPolicy"],
"attachedPolicies": [
"S3AdminPolicy"
],
"description": "Admin role for Keycloak users"
},
{
@@ -145,11 +165,15 @@
"Principal": {
"Federated": "keycloak"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3ReadOnlyPolicy"],
"attachedPolicies": [
"S3ReadOnlyPolicy"
],
"description": "Read-only role for Keycloak users"
},
{
@@ -163,11 +187,15 @@
"Principal": {
"Federated": "keycloak"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3WriteOnlyPolicy"],
"attachedPolicies": [
"S3WriteOnlyPolicy"
],
"description": "Write-only role for Keycloak users"
},
{
@@ -181,11 +209,15 @@
"Principal": {
"Federated": "keycloak"
},
"Action": ["sts:AssumeRoleWithWebIdentity"]
"Action": [
"sts:AssumeRoleWithWebIdentity"
]
}
]
},
"attachedPolicies": ["S3ReadWritePolicy"],
"attachedPolicies": [
"S3ReadWritePolicy"
],
"description": "Read-write role for Keycloak users"
}
],
@@ -197,13 +229,21 @@
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:*"],
"Resource": ["*"]
"Action": [
"s3:*"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": ["sts:ValidateSession"],
"Resource": ["*"]
"Action": [
"sts:ValidateSession"
],
"Resource": [
"*"
]
}
]
}
@@ -211,7 +251,7 @@
{
"name": "S3ReadOnlyPolicy",
"document": {
"Version": "2012-10-17",
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
@@ -226,8 +266,12 @@
},
{
"Effect": "Allow",
"Action": ["sts:ValidateSession"],
"Resource": ["*"]
"Action": [
"sts:ValidateSession"
],
"Resource": [
"*"
]
}
]
}
@@ -260,8 +304,12 @@
},
{
"Effect": "Allow",
"Action": ["sts:ValidateSession"],
"Resource": ["*"]
"Action": [
"sts:ValidateSession"
],
"Resource": [
"*"
]
}
]
}
@@ -283,8 +331,12 @@
},
{
"Effect": "Allow",
"Action": ["sts:ValidateSession"],
"Resource": ["*"]
"Action": [
"sts:ValidateSession"
],
"Resource": [
"*"
]
}
]
}

View File

@@ -19,11 +19,11 @@
"type": "oidc",
"enabled": true,
"config": {
"issuer": "http://localhost:8090/realms/seaweedfs-test",
"issuer": "http://localhost:8080/realms/seaweedfs-test",
"clientId": "seaweedfs-s3",
"clientSecret": "seaweedfs-s3-secret",
"jwksUri": "http://localhost:8090/realms/seaweedfs-test/protocol/openid-connect/certs",
"userInfoUri": "http://localhost:8090/realms/seaweedfs-test/protocol/openid-connect/userinfo",
"jwksUri": "http://localhost:8080/realms/seaweedfs-test/protocol/openid-connect/certs",
"userInfoUri": "http://localhost:8080/realms/seaweedfs-test/protocol/openid-connect/userinfo",
"scopes": [
"openid",
"profile",

View File

@@ -30,10 +30,10 @@ func TestS3IAMDistributedTests(t *testing.T) {
// Create S3 clients that would connect to different gateway instances
// In a real distributed setup, these would point to different S3 gateway ports
client1, err := framework.CreateS3ClientWithJWT("test-user", "TestAdminRole")
client1, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
require.NoError(t, err)
client2, err := framework.CreateS3ClientWithJWT("test-user", "TestAdminRole")
client2, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
require.NoError(t, err)
// Both clients should be able to perform operations
@@ -70,7 +70,7 @@ func TestS3IAMDistributedTests(t *testing.T) {
adminClient, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
require.NoError(t, err)
readOnlyClient, err := framework.CreateS3ClientWithJWT("readonly-user", "TestReadOnlyRole")
readOnlyClient, err := framework.CreateS3ClientWithJWT("read-user", "TestReadOnlyRole")
require.NoError(t, err)
bucketName := "test-distributed-roles"
@@ -160,7 +160,7 @@ func TestS3IAMDistributedTests(t *testing.T) {
go func(goroutineID int) {
defer wg.Done()
client, err := framework.CreateS3ClientWithJWT(fmt.Sprintf("user-%d", goroutineID), "TestAdminRole")
client, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
if err != nil {
errors <- fmt.Errorf("failed to create S3 client for goroutine %d: %w", goroutineID, err)
return

View File

@@ -0,0 +1,357 @@
package iam
import (
"encoding/xml"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// AssumeRoleResponse represents the STS AssumeRole response
type AssumeRoleTestResponse struct {
XMLName xml.Name `xml:"AssumeRoleResponse"`
Result struct {
Credentials struct {
AccessKeyId string `xml:"AccessKeyId"`
SecretAccessKey string `xml:"SecretAccessKey"`
SessionToken string `xml:"SessionToken"`
Expiration string `xml:"Expiration"`
} `xml:"Credentials"`
AssumedRoleUser struct {
AssumedRoleId string `xml:"AssumedRoleId"`
Arn string `xml:"Arn"`
} `xml:"AssumedRoleUser"`
} `xml:"AssumeRoleResult"`
}
// TestSTSAssumeRoleValidation tests input validation for AssumeRole endpoint
func TestSTSAssumeRoleValidation(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Fatal("SeaweedFS STS endpoint is not running at", TestSTSEndpoint, "- please run 'make setup-all-tests' first")
}
// Check if AssumeRole is implemented by making a test call
if !isAssumeRoleImplemented(t) {
t.Fatal("AssumeRole action is not implemented in the running server - please rebuild weed binary with new code and restart the server")
}
t.Run("missing_role_arn", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleSessionName": {"test-session"},
// RoleArn is missing
}, "test-access-key", "test-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail without RoleArn")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Equal(t, "MissingParameter", errResp.Error.Code)
})
t.Run("missing_role_session_name", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
// RoleSessionName is missing
}, "test-access-key", "test-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail without RoleSessionName")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Equal(t, "MissingParameter", errResp.Error.Code)
})
t.Run("unsupported_action_for_anonymous", func(t *testing.T) {
// AssumeRole requires SigV4 authentication, anonymous requests should fail
resp, err := callSTSAPI(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
})
require.NoError(t, err)
defer resp.Body.Close()
// Should fail because AssumeRole requires AWS SigV4 authentication
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"AssumeRole should require authentication")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for anonymous AssumeRole: status=%d, body=%s", resp.StatusCode, string(body))
})
t.Run("invalid_duration_too_short", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
"DurationSeconds": {"100"}, // Less than 900 seconds minimum
}, "test-access-key", "test-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with DurationSeconds < 900")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Equal(t, "InvalidParameterValue", errResp.Error.Code)
})
t.Run("invalid_duration_too_long", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
"DurationSeconds": {"100000"}, // More than 43200 seconds maximum
}, "test-access-key", "test-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with DurationSeconds > 43200")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Equal(t, "InvalidParameterValue", errResp.Error.Code)
})
}
// isAssumeRoleImplemented checks if the running server supports AssumeRole
func isAssumeRoleImplemented(t *testing.T) bool {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test"},
"RoleSessionName": {"test"},
}, "test", "test")
if err != nil {
return false
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
// If we get "NotImplemented", the action isn't supported
var errResp STSErrorTestResponse
if xml.Unmarshal(body, &errResp) == nil && errResp.Error.Code == "NotImplemented" {
return false
}
// If we get InvalidAction, the action isn't routed
if errResp.Error.Code == "InvalidAction" {
return false
}
return true
}
// TestSTSAssumeRoleWithValidCredentials tests AssumeRole with valid IAM credentials
// This test requires a configured IAM user in SeaweedFS
func TestSTSAssumeRoleWithValidCredentials(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Skip("SeaweedFS STS endpoint is not running at", TestSTSEndpoint)
}
// Use test credentials from environment or fall back to defaults
accessKey := os.Getenv("STS_TEST_ACCESS_KEY")
if accessKey == "" {
accessKey = "admin"
}
secretKey := os.Getenv("STS_TEST_SECRET_KEY")
if secretKey == "" {
secretKey = "admin"
}
t.Run("successful_assume_role", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/admin"},
"RoleSessionName": {"integration-test-session"},
}, accessKey, secretKey)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response status: %d, body: %s", resp.StatusCode, string(body))
// If AssumeRole is not yet implemented, expect an error about unsupported action
if resp.StatusCode != http.StatusOK {
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
t.Logf("Error response: code=%s, message=%s", errResp.Error.Code, errResp.Error.Message)
// This test will initially fail until AssumeRole is implemented
// Once implemented, uncomment the assertions below
// assert.Fail(t, "AssumeRole not yet implemented")
} else {
var stsResp AssumeRoleTestResponse
err = xml.Unmarshal(body, &stsResp)
require.NoError(t, err, "Failed to parse response: %s", string(body))
creds := stsResp.Result.Credentials
assert.NotEmpty(t, creds.AccessKeyId, "AccessKeyId should not be empty")
assert.NotEmpty(t, creds.SecretAccessKey, "SecretAccessKey should not be empty")
assert.NotEmpty(t, creds.SessionToken, "SessionToken should not be empty")
assert.NotEmpty(t, creds.Expiration, "Expiration should not be empty")
t.Logf("Successfully obtained temporary credentials: AccessKeyId=%s", creds.AccessKeyId)
}
})
t.Run("with_custom_duration", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/admin"},
"RoleSessionName": {"duration-test-session"},
"DurationSeconds": {"3600"}, // 1 hour
}, accessKey, secretKey)
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response status: %d, body: %s", resp.StatusCode, string(body))
// Verify DurationSeconds is accepted
if resp.StatusCode != http.StatusOK {
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
// Should not fail due to DurationSeconds parameter
assert.NotContains(t, errResp.Error.Message, "DurationSeconds",
"DurationSeconds parameter should be accepted")
}
})
}
// TestSTSAssumeRoleWithInvalidCredentials tests AssumeRole rejection with bad credentials
func TestSTSAssumeRoleWithInvalidCredentials(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Skip("SeaweedFS STS endpoint is not running at", TestSTSEndpoint)
}
t.Run("invalid_access_key", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/admin"},
"RoleSessionName": {"test-session"},
}, "invalid-access-key", "some-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
// Should fail with access denied or signature mismatch
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with invalid access key")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for invalid credentials: status=%d, body=%s", resp.StatusCode, string(body))
})
t.Run("invalid_secret_key", func(t *testing.T) {
resp, err := callSTSAPIWithSigV4(t, url.Values{
"Action": {"AssumeRole"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/admin"},
"RoleSessionName": {"test-session"},
}, "admin", "wrong-secret-key")
require.NoError(t, err)
defer resp.Body.Close()
// Should fail with signature mismatch
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with invalid secret key")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for wrong secret: status=%d, body=%s", resp.StatusCode, string(body))
})
}
// callSTSAPIWithSigV4 makes an STS API call with AWS Signature V4 authentication
func callSTSAPIWithSigV4(t *testing.T, params url.Values, accessKey, secretKey string) (*http.Response, error) {
// Prepare request body
body := params.Encode()
// Create request
req, err := http.NewRequest(http.MethodPost, TestSTSEndpoint+"/",
strings.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Host", req.URL.Host)
// Sign request with AWS Signature V4 using official SDK
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
signer := v4.NewSigner(creds)
// Read body for signing
// Note: We need a ReadSeeker for the signer, or we can pass the body string/bytes to ComputeBodyHash if needed,
// but standard Sign method takes an io.ReadSeeker for the body.
bodyReader := strings.NewReader(body)
_, err = signer.Sign(req, bodyReader, "sts", "us-east-1", time.Now())
if err != nil {
return nil, fmt.Errorf("failed to sign request: %w", err)
}
client := &http.Client{Timeout: 30 * time.Second}
return client.Do(req)
}

View File

@@ -0,0 +1,291 @@
package iam
import (
"encoding/xml"
"io"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// AssumeRoleWithLDAPIdentityResponse represents the STS response for LDAP identity
type AssumeRoleWithLDAPIdentityTestResponse struct {
XMLName xml.Name `xml:"AssumeRoleWithLDAPIdentityResponse"`
Result struct {
Credentials struct {
AccessKeyId string `xml:"AccessKeyId"`
SecretAccessKey string `xml:"SecretAccessKey"`
SessionToken string `xml:"SessionToken"`
Expiration string `xml:"Expiration"`
} `xml:"Credentials"`
} `xml:"AssumeRoleWithLDAPIdentityResult"`
}
// TestSTSLDAPValidation tests input validation for AssumeRoleWithLDAPIdentity
func TestSTSLDAPValidation(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Fatal("SeaweedFS STS endpoint is not running at", TestSTSEndpoint, "- please run 'make setup-all-tests' first")
}
// Check if AssumeRoleWithLDAPIdentity is implemented
if !isLDAPIdentityActionImplemented(t) {
t.Fatal("AssumeRoleWithLDAPIdentity action is not implemented in the running server - please rebuild weed binary with new code and restart the server")
}
t.Run("missing_ldap_username", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
"LDAPPassword": {"testpass"},
// LDAPUsername is missing
})
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail without LDAPUsername")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
// Expect either MissingParameter or InvalidAction (if not implemented)
assert.Contains(t, []string{"MissingParameter", "InvalidAction"}, errResp.Error.Code)
})
t.Run("missing_ldap_password", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
"LDAPUsername": {"testuser"},
// LDAPPassword is missing
})
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail without LDAPPassword")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Contains(t, []string{"MissingParameter", "InvalidAction"}, errResp.Error.Code)
})
t.Run("missing_role_arn", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleSessionName": {"test-session"},
"LDAPUsername": {"testuser"},
"LDAPPassword": {"testpass"},
// RoleArn is missing
})
require.NoError(t, err)
defer resp.Body.Close()
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail without RoleArn")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errResp STSErrorTestResponse
err = xml.Unmarshal(body, &errResp)
require.NoError(t, err, "Failed to parse error response: %s", string(body))
assert.Contains(t, []string{"MissingParameter", "InvalidAction"}, errResp.Error.Code)
})
t.Run("invalid_duration_too_short", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test-role"},
"RoleSessionName": {"test-session"},
"LDAPUsername": {"testuser"},
"LDAPPassword": {"testpass"},
"DurationSeconds": {"100"}, // Less than 900 seconds minimum
})
require.NoError(t, err)
defer resp.Body.Close()
// If the action is implemented, it should reject invalid duration
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for invalid duration: status=%d, body=%s", resp.StatusCode, string(body))
})
}
// TestSTSLDAPWithValidCredentials tests LDAP authentication
// This test requires an LDAP server to be configured
func TestSTSLDAPWithValidCredentials(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Skip("SeaweedFS STS endpoint is not running at", TestSTSEndpoint)
}
// Check if LDAP is configured (skip if not)
if !isLDAPConfigured() {
t.Skip("LDAP is not configured - skipping LDAP integration tests")
}
t.Run("successful_ldap_auth", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/ldap-user"},
"RoleSessionName": {"ldap-test-session"},
"LDAPUsername": {"testuser"},
"LDAPPassword": {"testpass"},
})
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response status: %d, body: %s", resp.StatusCode, string(body))
if resp.StatusCode == http.StatusOK {
var stsResp AssumeRoleWithLDAPIdentityTestResponse
err = xml.Unmarshal(body, &stsResp)
require.NoError(t, err, "Failed to parse response: %s", string(body))
creds := stsResp.Result.Credentials
assert.NotEmpty(t, creds.AccessKeyId, "AccessKeyId should not be empty")
assert.NotEmpty(t, creds.SecretAccessKey, "SecretAccessKey should not be empty")
assert.NotEmpty(t, creds.SessionToken, "SessionToken should not be empty")
assert.NotEmpty(t, creds.Expiration, "Expiration should not be empty")
}
})
}
// TestSTSLDAPWithInvalidCredentials tests LDAP rejection with bad credentials
func TestSTSLDAPWithInvalidCredentials(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
if !isSTSEndpointRunning(t) {
t.Skip("SeaweedFS STS endpoint is not running at", TestSTSEndpoint)
}
t.Run("invalid_ldap_password", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/ldap-user"},
"RoleSessionName": {"ldap-test-session"},
"LDAPUsername": {"testuser"},
"LDAPPassword": {"wrong-password"},
})
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for invalid LDAP credentials: status=%d, body=%s", resp.StatusCode, string(body))
// Should fail (either AccessDenied or InvalidAction if not implemented)
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with invalid LDAP password")
})
t.Run("nonexistent_ldap_user", func(t *testing.T) {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/ldap-user"},
"RoleSessionName": {"ldap-test-session"},
"LDAPUsername": {"nonexistent-user-12345"},
"LDAPPassword": {"somepassword"},
})
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("Response for nonexistent user: status=%d, body=%s", resp.StatusCode, string(body))
// Should fail
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
"Should fail with nonexistent LDAP user")
})
}
// callSTSAPIForLDAP makes an STS API call for LDAP operation
func callSTSAPIForLDAP(t *testing.T, params url.Values) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPost, TestSTSEndpoint+"/",
strings.NewReader(params.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{Timeout: 30 * time.Second}
return client.Do(req)
}
// isLDAPConfigured checks if LDAP server is configured and available
func isLDAPConfigured() bool {
// Check environment variable for LDAP URL
ldapURL := os.Getenv("LDAP_URL")
return ldapURL != ""
}
// isLDAPIdentityActionImplemented checks if the running server supports AssumeRoleWithLDAPIdentity
func isLDAPIdentityActionImplemented(t *testing.T) bool {
resp, err := callSTSAPIForLDAP(t, url.Values{
"Action": {"AssumeRoleWithLDAPIdentity"},
"Version": {"2011-06-15"},
"RoleArn": {"arn:aws:iam::role/test"},
"RoleSessionName": {"test"},
"LDAPUsername": {"test"},
"LDAPPassword": {"test"},
})
if err != nil {
return false
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
// If we get "NotImplemented" or empty response, the action isn't supported
if len(body) == 0 {
return false
}
var errResp STSErrorTestResponse
if xml.Unmarshal(body, &errResp) == nil && errResp.Error.Code == "NotImplemented" {
return false
}
// If we get InvalidAction, the action isn't routed
if errResp.Error.Code == "InvalidAction" {
return false
}
return true
}

View File

@@ -50,6 +50,82 @@ setup_keycloak() {
echo -e "${GREEN}[OK] Keycloak setup completed${NC}"
}
# Set up OpenLDAP for LDAP-based STS testing
setup_ldap() {
echo -e "\n${BLUE}1a. Setting up OpenLDAP for STS LDAP testing...${NC}"
# Check if LDAP container is already running
if docker ps --format '{{.Names}}' | grep -q '^openldap-iam-test$'; then
echo -e "${YELLOW}OpenLDAP container already running${NC}"
echo -e "${GREEN}[OK] LDAP setup completed (using existing container)${NC}"
return 0
fi
# Remove any stopped container with the same name
docker rm -f openldap-iam-test 2>/dev/null || true
# Start OpenLDAP container
echo -e "${YELLOW}🔧 Starting OpenLDAP container...${NC}"
docker run -d \
--name openldap-iam-test \
-p 389:389 \
-p 636:636 \
-e LDAP_ADMIN_PASSWORD=adminpassword \
-e LDAP_ORGANISATION="SeaweedFS" \
-e LDAP_DOMAIN="seaweedfs.test" \
osixia/openldap:latest || {
echo -e "${YELLOW}⚠️ OpenLDAP setup failed (optional for basic STS tests)${NC}"
return 0 # Don't fail - LDAP is optional
}
# Wait for LDAP to be ready
echo -e "${YELLOW}⏳ Waiting for OpenLDAP to be ready...${NC}"
for i in $(seq 1 30); do
if docker exec openldap-iam-test ldapsearch -x -H ldap://localhost -b "dc=seaweedfs,dc=test" -D "cn=admin,dc=seaweedfs,dc=test" -w adminpassword "(objectClass=*)" >/dev/null 2>&1; then
break
fi
sleep 1
done
# Add test users for LDAP STS testing
echo -e "${YELLOW}📝 Adding test users for LDAP STS...${NC}"
docker exec -i openldap-iam-test ldapadd -x -D "cn=admin,dc=seaweedfs,dc=test" -w adminpassword <<EOF 2>/dev/null || true
dn: ou=users,dc=seaweedfs,dc=test
objectClass: organizationalUnit
ou: users
dn: cn=testuser,ou=users,dc=seaweedfs,dc=test
objectClass: inetOrgPerson
cn: testuser
sn: Test User
uid: testuser
userPassword: testpass
dn: cn=ldapadmin,ou=users,dc=seaweedfs,dc=test
objectClass: inetOrgPerson
cn: ldapadmin
sn: LDAP Admin
uid: ldapadmin
userPassword: ldapadminpass
EOF
# Verify test users were created successfully
echo -e "${YELLOW}🔍 Verifying LDAP test users...${NC}"
if docker exec openldap-iam-test ldapsearch -x -D "cn=admin,dc=seaweedfs,dc=test" -w adminpassword -b "ou=users,dc=seaweedfs,dc=test" "(cn=testuser)" cn 2>/dev/null | grep -q "cn: testuser"; then
echo -e "${GREEN}[OK] Test user 'testuser' verified${NC}"
else
echo -e "${RED}[WARN] Could not verify test user 'testuser' - LDAP tests may fail${NC}"
fi
# Set environment for LDAP tests
export LDAP_URL="ldap://localhost:389"
export LDAP_BASE_DN="dc=seaweedfs,dc=test"
export LDAP_BIND_DN="cn=admin,dc=seaweedfs,dc=test"
export LDAP_BIND_PASSWORD="adminpassword"
echo -e "${GREEN}[OK] LDAP setup completed${NC}"
}
# Set up SeaweedFS test cluster
setup_seaweedfs_cluster() {
echo -e "\n${BLUE}2. Setting up SeaweedFS test cluster...${NC}"
@@ -153,6 +229,7 @@ display_summary() {
echo -e "\n${BLUE}📊 Setup Summary${NC}"
echo -e "${BLUE}=================${NC}"
echo -e "Keycloak URL: ${KEYCLOAK_URL:-http://localhost:8080}"
echo -e "LDAP URL: ${LDAP_URL:-ldap://localhost:389}"
echo -e "S3 Endpoint: ${S3_ENDPOINT:-http://localhost:8333}"
echo -e "Test Timeout: ${TEST_TIMEOUT:-60m}"
echo -e "IAM Config: ${SCRIPT_DIR}/iam_config.json"
@@ -161,6 +238,7 @@ display_summary() {
echo -e "${YELLOW}💡 You can now run tests with: make run-all-tests${NC}"
echo -e "${YELLOW}💡 Or run specific tests with: go test -v -timeout=60m -run TestName${NC}"
echo -e "${YELLOW}💡 To stop Keycloak: docker stop keycloak-iam-test${NC}"
echo -e "${YELLOW}💡 To stop LDAP: docker stop openldap-iam-test${NC}"
}
# Main execution
@@ -177,6 +255,10 @@ main() {
exit 1
fi
# LDAP is optional but we try to set it up
setup_ldap
setup_steps+=("ldap")
if setup_seaweedfs_cluster; then
setup_steps+=("seaweedfs")
else

View File

@@ -139,7 +139,7 @@ ensure_realm() {
echo -e "${GREEN}[OK] Realm '${REALM_NAME}' already exists${NC}"
else
echo -e "${YELLOW}📝 Creating realm '${REALM_NAME}'...${NC}"
if kcadm create realms -s realm="${REALM_NAME}" -s enabled=true 2>/dev/null; then
if kcadm create realms -s realm="${REALM_NAME}" -s enabled=true; then
echo -e "${GREEN}[OK] Realm created${NC}"
else
# Check if it exists now (might have been created by another process)