Files
seaweedFS/weed/s3api/s3api_embedded_iam_test.go
Chris Lu f41925b60b Embed IAM API into S3 server (#7740)
* Embed IAM API into S3 server

This change simplifies the S3 and IAM deployment by embedding the IAM API
directly into the S3 server, following the patterns used by MinIO and Ceph RGW.

Changes:
- Add -iam flag to S3 server (enabled by default)
- Create embedded IAM API handler in s3api package
- Register IAM routes (POST to /) in S3 server when enabled
- Deprecate standalone 'weed iam' command with warning

Benefits:
- Single binary, single port for both S3 and IAM APIs
- Simpler deployment and configuration
- Shared credential manager between S3 and IAM
- Backward compatible: 'weed iam' still works with deprecation warning

Usage:
- weed s3 -port=8333          # S3 + IAM on same port (default)
- weed s3 -iam=false          # S3 only, disable embedded IAM
- weed iam -port=8111         # Deprecated, shows warning

* Fix nil pointer panic: add s3.iam flag to weed server command

The enableIam field was not initialized when running S3 via 'weed server',
causing a nil pointer dereference when checking *s3opt.enableIam.

* Fix nil pointer panic: add s3.iam flag to weed filer command

The enableIam field was not initialized when running S3 via 'weed filer -s3',
causing a nil pointer dereference when checking *s3opt.enableIam.

* Add integration tests for embedded IAM API

Tests cover:
- CreateUser, ListUsers, GetUser, UpdateUser, DeleteUser
- CreateAccessKey, DeleteAccessKey, ListAccessKeys
- CreatePolicy, PutUserPolicy, GetUserPolicy
- Implicit username extraction from authorization header
- Full user lifecycle workflow test

These tests validate the embedded IAM API functionality that was
added in the S3 server, ensuring IAM operations work correctly
when served from the same port as S3.

* Security: Use crypto/rand for IAM credential generation

SECURITY FIX: Replace math/rand with crypto/rand for generating
access keys and secret keys.

Using math/rand is not cryptographically secure and can lead to
predictable credentials. This change:

1. Replaces math/rand with crypto/rand in both:
   - weed/s3api/s3api_embedded_iam.go (embedded IAM)
   - weed/iamapi/iamapi_management_handlers.go (standalone IAM)

2. Removes the seededRand variable that was initialized with
   time-based seed (predictable)

3. Updates StringWithCharset/iamStringWithCharset to:
   - Use crypto/rand.Int() for secure random index generation
   - Return an error for proper error handling

4. Updates CreateAccessKey to handle the new error return

5. Updates DoActions handlers to propagate errors properly

* Fix critical bug: DeleteUserPolicy was deleting entire user instead of policy

BUG FIX: DeleteUserPolicy was incorrectly deleting the entire user
identity from s3cfg.Identities instead of just clearing the user's
inline policy (Actions).

Before (wrong):
  s3cfg.Identities = append(s3cfg.Identities[:i], s3cfg.Identities[i+1:]...)

After (correct):
  ident.Actions = nil

Also:
- Added proper iamDeleteUserPolicyResponse / DeleteUserPolicyResponse types
- Fixed return type from iamPutUserPolicyResponse to iamDeleteUserPolicyResponse

Affected files:
- weed/s3api/s3api_embedded_iam.go (embedded IAM)
- weed/iamapi/iamapi_management_handlers.go (standalone IAM)
- weed/iamapi/iamapi_response.go (response types)

* Add tests for DeleteUserPolicy to prevent regression

Added two tests:
1. TestEmbeddedIamDeleteUserPolicy - Verifies that:
   - User is NOT deleted (identity still exists)
   - Credentials are NOT deleted
   - Only Actions (policy) are cleared to nil

2. TestEmbeddedIamDeleteUserPolicyUserNotFound - Verifies:
   - Returns 404 when user doesn't exist

These tests ensure the bug fixed in the previous commit
(deleting user instead of policy) doesn't regress.

* Fix race condition: Add mutex lock to IAM DoActions

The DoActions function performs a read-modify-write operation on the
shared IAM configuration without any locking. This could lead to race
conditions and data loss if multiple requests modify the IAM config
concurrently.

Added mutex lock at the start of DoActions in both:
- weed/s3api/s3api_embedded_iam.go (embedded IAM)
- weed/iamapi/iamapi_management_handlers.go (standalone IAM)

The lock protects the entire read-modify-write cycle:
1. GetS3ApiConfiguration (read)
2. Modify s3cfg based on action
3. PutS3ApiConfiguration (write)

* Fix action comparison and document CreatePolicy limitation

1. Replace reflect.DeepEqual with order-independent string slice comparison
   - Added iamStringSlicesEqual/stringSlicesEqual helper functions
   - Prevents duplicate policy statements when actions are in different order

2. Document CreatePolicy limitation in embedded IAM
   - Added TODO comment explaining that managed policies are not persisted
   - Users should use PutUserPolicy for inline policies

3. Fix deadlock in standalone IAM's CreatePolicy
   - Removed nested lock acquisition (DoActions already holds the lock)

Files changed:
- weed/s3api/s3api_embedded_iam.go
- weed/iamapi/iamapi_management_handlers.go

* Add rate limiting to embedded IAM endpoint

Apply circuit breaker rate limiting to the IAM endpoint to prevent abuse.
Also added request tracking for IAM operations.

The IAM endpoint now follows the same pattern as other S3 endpoints:
- track() for request metrics
- s3a.iam.Auth() for authentication
- s3a.cb.Limit() for rate limiting

* Fix handleImplicitUsername to properly look up username from AccessKeyId

According to AWS spec, when UserName is not specified in an IAM request,
IAM should determine the username implicitly based on the AccessKeyId
signing the request.

Previously, the code incorrectly extracted s[2] (region field) from the
SigV4 credential string as the username. This fix:

1. Extracts the AccessKeyId from s[0] of the credential string
2. Looks up the AccessKeyId in the credential store using LookupByAccessKey
3. Uses the identity's Name field as the username if found

Also:
- Added exported LookupByAccessKey wrapper method to IdentityAccessManagement
- Updated tests to verify correct access key lookup behavior
- Applied fix to both embedded IAM and standalone IAM implementations

* Fix CreatePolicy to not trigger unnecessary save

CreatePolicy validates the policy document and returns metadata but does not
actually store the policy (SeaweedFS uses inline policies attached via
PutUserPolicy). However, 'changed' was left as true, triggering an unnecessary
save operation.

Set changed = false after successful CreatePolicy validation in both embedded
IAM and standalone IAM implementations.

* Improve embedded IAM test quality

- Remove unused mock types (mockCredentialManager, mockEmbeddedIamApi)
- Use proto.Clone instead of proto.Merge for proper deep copy semantics
- Replace brittle regex-based XML error extraction with proper XML unmarshalling
- Remove unused regexp import
- Add state and field assertions to tests:
  - CreateUser: verify username in response and user persisted in config
  - ListUsers: verify response contains expected users
  - GetUser: verify username in response
  - CreatePolicy: verify policy metadata in response
  - PutUserPolicy: verify actions were attached to user
  - CreateAccessKey: verify credentials in response and persisted in config

* Remove shared test state and improve executeEmbeddedIamRequest

- Remove package-level embeddedIamApi variable to avoid shared test state
- Update executeEmbeddedIamRequest to accept API instance as parameter
- Only call xml.Unmarshal when v != nil, making nil-v cases explicit
- Return unmarshal error properly instead of always returning it
- Update all tests to create their own EmbeddedIamApiForTest instance
- Each test now has isolated state, preventing test interdependencies

* Add comprehensive test coverage for embedded IAM

Added tests for previously uncovered functions:
- iamStringSlicesEqual: 0% → 100%
- iamMapToStatementAction: 40% → 100%
- iamMapToIdentitiesAction: 30% → 70%
- iamHash: 100%
- iamStringWithCharset: 85.7%
- GetPolicyDocument: 75% → 100%
- CreatePolicy: 91.7% → 100%
- DeleteUser: 83.3% → 100%
- GetUser: 83.3% → 100%
- ListAccessKeys: 55.6% → 88.9%

New test cases for helper functions, error handling, and edge cases.

* Document IAM code duplication and reference GitHub issue #7747

Added comments to both IAM implementations noting the code duplication
and referencing the tracking issue for future refactoring:
- weed/s3api/s3api_embedded_iam.go (embedded IAM)
- weed/iamapi/iamapi_management_handlers.go (standalone IAM)

See: https://github.com/seaweedfs/seaweedfs/issues/7747

* Implement granular IAM authorization for self-service operations

Previously, all IAM actions required ACTION_ADMIN permission, which was
overly restrictive. This change implements AWS-like granular permissions:

Self-service operations (allowed without admin for own resources):
- CreateAccessKey (on own user)
- DeleteAccessKey (on own user)
- ListAccessKeys (on own user)
- GetUser (on own user)
- UpdateAccessKey (on own user)

Admin-only operations:
- CreateUser, DeleteUser, UpdateUser
- PutUserPolicy, GetUserPolicy, DeleteUserPolicy
- CreatePolicy
- ListUsers
- Operations on other users

The new AuthIam middleware:
1. Authenticates the request (signature verification)
2. Parses the IAM Action and target UserName
3. For self-service actions, allows if user is operating on own resources
4. For all other actions or operations on other users, requires admin

* Fix misleading comment in standalone IAM CreatePolicy

The comment incorrectly stated that CreatePolicy only validates the policy
document. In the standalone IAM server, CreatePolicy actually persists
the policy via iama.s3ApiConfig.PutPolicies(). The changed flag is false
because it doesn't modify s3cfg.Identities, not because nothing is stored.

* Simplify IAM auth and add RequestId to responses

- Remove redundant ACTION_ADMIN fallback in AuthIam: The action parameter
  in authRequest is for permission checking, not signature verification.
  If auth fails with ACTION_READ, it will fail with ACTION_ADMIN too.

- Add SetRequestId() call before writing IAM responses for AWS compatibility.
  All IAM response structs embed iamCommonResponse which has SetRequestId().

* Address code review feedback for IAM implementation

1. auth_credentials.go: Add documentation warning that LookupByAccessKey
   returns internal pointers that should not be mutated.

2. iamapi_management_handlers.go & s3api_embedded_iam.go: Add input guards
   for StringWithCharset/iamStringWithCharset when length <= 0 or charset
   is empty to avoid runtime errors from rand.Int.

3. s3api_embedded_iam_test.go: Don't ignore xml.Marshal errors in test
   DoActions handler. Return proper error response if marshaling fails.

4. s3api_embedded_iam_test.go: Use obviously fake access key IDs
   (AKIATESTFAKEKEY*) to avoid CI secret scanner false positives.

* Address code review feedback for IAM implementation (batch 2)

1. iamapi/iamapi_management_handlers.go:
   - Redact Authorization header log (security: avoid exposing signature)
   - Add nil-guard for iama.iam before LookupByAccessKey call

2. iamapi/iamapi_test.go:
   - Replace real-looking access keys with obviously fake ones
     (AKIATESTFAKEKEY*) to avoid CI secret scanner false positives

3. s3api/s3api_embedded_iam.go - CreateUser:
   - Validate UserName is not empty (return ErrCodeInvalidInputException)
   - Check for duplicate users (return ErrCodeEntityAlreadyExistsException)

4. s3api/s3api_embedded_iam.go - CreateAccessKey:
   - Return ErrCodeNoSuchEntityException if user doesn't exist
   - Removed implicit user creation behavior

5. s3api/s3api_embedded_iam.go - getActions:
   - Fix S3 ARN parsing for bucket/path patterns
   - Handle mybucket, mybucket/*, mybucket/path/* correctly
   - Return error if no valid actions found in policy

6. s3api/s3api_embedded_iam.go - handleImplicitUsername:
   - Redact Authorization header log
   - Add nil-guard for e.iam

7. s3api/s3api_embedded_iam.go - DoActions:
   - Reload in-memory IAM maps after credential mutations
   - Call LoadS3ApiConfigurationFromCredentialManager after save

8. s3api/auth_credentials.go - AuthSignatureOnly:
   - Add new signature-only authentication method
   - Bypasses S3 authorization checks for IAM operations
   - Used by AuthIam to properly separate signature verification
     from IAM-specific permission checks

* Fix nil pointer dereference and error handling in IAM

1. AuthIam: Add nil check for identity after AuthSignatureOnly
   - AuthSignatureOnly can return nil identity with ErrNone for
     authTypePostPolicy or authTypeStreamingUnsigned
   - Now returns ErrAccessDenied if identity is nil

2. writeIamErrorResponse: Add missing error code cases
   - ErrCodeEntityAlreadyExistsException -> HTTP 409 Conflict
   - ErrCodeInvalidInputException -> HTTP 400 Bad Request

3. UpdateUser: Use consistent error handling
   - Changed from direct ErrInvalidRequest to writeIamErrorResponse
   - Now returns correct HTTP status codes based on error type

* Add IAM config reload to standalone IAM server after mutations

Match the behavior of embedded IAM (s3api_embedded_iam.go) by reloading
the in-memory identity maps after persisting configuration changes.
This ensures newly created access keys are visible to LookupByAccessKey
immediately without requiring a server restart.

* Minor improvements to test helpers and log masking

1. iamapi_test.go: Update mustMarshalJSON to use t.Helper() and t.Fatal()
   instead of panic() for better test diagnostics

2. s3api_embedded_iam.go: Mask access key in 'not found' log message
   to avoid exposing full access key IDs in logs

* Mask access key in standalone IAM log message for consistency

Match the embedded IAM version by masking the access key ID in
the 'not found' log message (show only first 4 chars).
2025-12-14 16:02:06 -08:00

1029 lines
32 KiB
Go

package s3api
import (
"encoding/json"
"encoding/xml"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/gorilla/mux"
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
)
// EmbeddedIamApiForTest is a testable version of EmbeddedIamApi
type EmbeddedIamApiForTest struct {
*EmbeddedIamApi
mockConfig *iam_pb.S3ApiConfiguration
}
func NewEmbeddedIamApiForTest() *EmbeddedIamApiForTest {
e := &EmbeddedIamApiForTest{
EmbeddedIamApi: &EmbeddedIamApi{
iam: &IdentityAccessManagement{},
},
mockConfig: &iam_pb.S3ApiConfiguration{},
}
return e
}
// Override GetS3ApiConfiguration for testing
func (e *EmbeddedIamApiForTest) GetS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
// Use proto.Clone for proper deep copy semantics
if e.mockConfig != nil {
cloned := proto.Clone(e.mockConfig).(*iam_pb.S3ApiConfiguration)
proto.Merge(s3cfg, cloned)
}
return nil
}
// Override PutS3ApiConfiguration for testing
func (e *EmbeddedIamApiForTest) PutS3ApiConfiguration(s3cfg *iam_pb.S3ApiConfiguration) error {
// Use proto.Clone for proper deep copy semantics
e.mockConfig = proto.Clone(s3cfg).(*iam_pb.S3ApiConfiguration)
return nil
}
// DoActions handles IAM API actions for testing
func (e *EmbeddedIamApiForTest) DoActions(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
values := r.PostForm
s3cfg := &iam_pb.S3ApiConfiguration{}
if err := e.GetS3ApiConfiguration(s3cfg); err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
var response interface{}
var iamErr *iamError
changed := true
switch r.Form.Get("Action") {
case "ListUsers":
response = e.ListUsers(s3cfg, values)
changed = false
case "ListAccessKeys":
e.handleImplicitUsername(r, values)
response = e.ListAccessKeys(s3cfg, values)
changed = false
case "CreateUser":
response, iamErr = e.CreateUser(s3cfg, values)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
case "GetUser":
userName := values.Get("UserName")
response, iamErr = e.GetUser(s3cfg, userName)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
changed = false
case "UpdateUser":
response, iamErr = e.UpdateUser(s3cfg, values)
if iamErr != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
case "DeleteUser":
userName := values.Get("UserName")
response, iamErr = e.DeleteUser(s3cfg, userName)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
case "CreateAccessKey":
e.handleImplicitUsername(r, values)
response, iamErr = e.CreateAccessKey(s3cfg, values)
if iamErr != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
case "DeleteAccessKey":
e.handleImplicitUsername(r, values)
response = e.DeleteAccessKey(s3cfg, values)
case "CreatePolicy":
response, iamErr = e.CreatePolicy(s3cfg, values)
if iamErr != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
case "PutUserPolicy":
response, iamErr = e.PutUserPolicy(s3cfg, values)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
case "GetUserPolicy":
response, iamErr = e.GetUserPolicy(s3cfg, values)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
changed = false
case "DeleteUserPolicy":
response, iamErr = e.DeleteUserPolicy(s3cfg, values)
if iamErr != nil {
e.writeIamErrorResponse(w, r, iamErr)
return
}
default:
http.Error(w, "Not implemented", http.StatusNotImplemented)
return
}
if changed {
if err := e.PutS3ApiConfiguration(s3cfg); err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/xml")
w.WriteHeader(http.StatusOK)
xmlBytes, err := xml.Marshal(response)
if err != nil {
// This should not happen in tests, but log it for debugging
http.Error(w, "Internal error: failed to marshal response", http.StatusInternalServerError)
return
}
_, _ = w.Write(xmlBytes)
}
// executeEmbeddedIamRequest executes an IAM request against the given API instance.
// If v is non-nil, the response body is unmarshalled into it.
func executeEmbeddedIamRequest(api *EmbeddedIamApiForTest, req *http.Request, v interface{}) (*httptest.ResponseRecorder, error) {
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
if v != nil {
if err := xml.Unmarshal(rr.Body.Bytes(), v); err != nil {
return rr, err
}
}
return rr, nil
}
// embeddedIamErrorResponseForTest is used for parsing IAM error responses in tests
type embeddedIamErrorResponseForTest struct {
Error struct {
Code string `xml:"Code"`
Message string `xml:"Message"`
} `xml:"Error"`
}
func extractEmbeddedIamErrorCodeAndMessage(response *httptest.ResponseRecorder) (string, string) {
var er embeddedIamErrorResponseForTest
if err := xml.Unmarshal(response.Body.Bytes(), &er); err != nil {
return "", ""
}
return er.Error.Code, er.Error.Message
}
// TestEmbeddedIamCreateUser tests creating a user via the embedded IAM API
func TestEmbeddedIamCreateUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
userName := aws.String("TestUser")
params := &iam.CreateUserInput{UserName: userName}
req, _ := iam.New(session.New()).CreateUserRequest(params)
_ = req.Build()
out := iamCreateUserResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify response contains correct username
assert.NotNil(t, out.CreateUserResult.User.UserName)
assert.Equal(t, "TestUser", *out.CreateUserResult.User.UserName)
// Verify user was persisted in config
assert.Len(t, api.mockConfig.Identities, 1)
assert.Equal(t, "TestUser", api.mockConfig.Identities[0].Name)
}
// TestEmbeddedIamListUsers tests listing users via the embedded IAM API
func TestEmbeddedIamListUsers(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "User1"},
{Name: "User2"},
},
}
params := &iam.ListUsersInput{}
req, _ := iam.New(session.New()).ListUsersRequest(params)
_ = req.Build()
out := iamListUsersResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify response contains the users
assert.Len(t, out.ListUsersResult.Users, 2)
}
// TestEmbeddedIamListAccessKeys tests listing access keys via the embedded IAM API
func TestEmbeddedIamListAccessKeys(t *testing.T) {
api := NewEmbeddedIamApiForTest()
svc := iam.New(session.New())
params := &iam.ListAccessKeysInput{}
req, _ := svc.ListAccessKeysRequest(params)
_ = req.Build()
out := iamListAccessKeysResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
}
// TestEmbeddedIamGetUser tests getting a user via the embedded IAM API
func TestEmbeddedIamGetUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "TestUser"},
},
}
userName := aws.String("TestUser")
params := &iam.GetUserInput{UserName: userName}
req, _ := iam.New(session.New()).GetUserRequest(params)
_ = req.Build()
out := iamGetUserResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify response contains correct username
assert.NotNil(t, out.GetUserResult.User.UserName)
assert.Equal(t, "TestUser", *out.GetUserResult.User.UserName)
}
// TestEmbeddedIamCreatePolicy tests creating a policy via the embedded IAM API
func TestEmbeddedIamCreatePolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
params := &iam.CreatePolicyInput{
PolicyName: aws.String("S3-read-only-example-bucket"),
PolicyDocument: aws.String(`
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": [
"arn:aws:s3:::EXAMPLE-BUCKET",
"arn:aws:s3:::EXAMPLE-BUCKET/*"
]
}
]
}`),
}
req, _ := iam.New(session.New()).CreatePolicyRequest(params)
_ = req.Build()
out := iamCreatePolicyResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify response contains policy metadata
assert.NotNil(t, out.CreatePolicyResult.Policy.PolicyName)
assert.Equal(t, "S3-read-only-example-bucket", *out.CreatePolicyResult.Policy.PolicyName)
assert.NotNil(t, out.CreatePolicyResult.Policy.Arn)
assert.NotNil(t, out.CreatePolicyResult.Policy.PolicyId)
}
// TestEmbeddedIamPutUserPolicy tests attaching a policy to a user
func TestEmbeddedIamPutUserPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "TestUser"},
},
}
userName := aws.String("TestUser")
params := &iam.PutUserPolicyInput{
UserName: userName,
PolicyName: aws.String("S3-read-only-example-bucket"),
PolicyDocument: aws.String(
`{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": [
"arn:aws:s3:::EXAMPLE-BUCKET",
"arn:aws:s3:::EXAMPLE-BUCKET/*"
]
}
]
}`),
}
req, _ := iam.New(session.New()).PutUserPolicyRequest(params)
_ = req.Build()
out := iamPutUserPolicyResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify policy was attached to the user (actions should be set)
assert.Len(t, api.mockConfig.Identities, 1)
assert.NotEmpty(t, api.mockConfig.Identities[0].Actions)
}
// TestEmbeddedIamPutUserPolicyError tests error handling when user doesn't exist
func TestEmbeddedIamPutUserPolicyError(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
userName := aws.String("InvalidUser")
params := &iam.PutUserPolicyInput{
UserName: userName,
PolicyName: aws.String("S3-read-only-example-bucket"),
PolicyDocument: aws.String(
`{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:Get*",
"s3:List*"
],
"Resource": [
"arn:aws:s3:::EXAMPLE-BUCKET",
"arn:aws:s3:::EXAMPLE-BUCKET/*"
]
}
]
}`),
}
req, _ := iam.New(session.New()).PutUserPolicyRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusNotFound, response.Code)
expectedCode := "NoSuchEntity"
code, _ := extractEmbeddedIamErrorCodeAndMessage(response)
assert.Equal(t, expectedCode, code)
}
// TestEmbeddedIamGetUserPolicy tests getting a user's policy
func TestEmbeddedIamGetUserPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "TestUser",
Actions: []string{"Read", "List"},
},
},
}
userName := aws.String("TestUser")
params := &iam.GetUserPolicyInput{
UserName: userName,
PolicyName: aws.String("S3-read-only-example-bucket"),
}
req, _ := iam.New(session.New()).GetUserPolicyRequest(params)
_ = req.Build()
out := iamGetUserPolicyResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
}
// TestEmbeddedIamDeleteUserPolicy tests deleting a user's policy (clears actions)
func TestEmbeddedIamDeleteUserPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "TestUser",
Actions: []string{"Read", "Write", "List"},
Credentials: []*iam_pb.Credential{
{AccessKey: "AKIATEST12345", SecretKey: "secret"},
},
},
},
}
// Use direct form post for DeleteUserPolicy
form := url.Values{}
form.Set("Action", "DeleteUserPolicy")
form.Set("UserName", "TestUser")
form.Set("PolicyName", "TestPolicy")
req, _ := http.NewRequest("POST", "/", nil)
req.PostForm = form
req.Form = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
// CRITICAL: Verify user still exists (was NOT deleted)
assert.Len(t, api.mockConfig.Identities, 1, "User should NOT be deleted")
assert.Equal(t, "TestUser", api.mockConfig.Identities[0].Name)
// Verify credentials are still intact
assert.Len(t, api.mockConfig.Identities[0].Credentials, 1, "Credentials should NOT be deleted")
assert.Equal(t, "AKIATEST12345", api.mockConfig.Identities[0].Credentials[0].AccessKey)
// Verify actions/policy was cleared
assert.Nil(t, api.mockConfig.Identities[0].Actions, "Actions should be cleared")
}
// TestEmbeddedIamDeleteUserPolicyUserNotFound tests error when user doesn't exist
func TestEmbeddedIamDeleteUserPolicyUserNotFound(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
form := url.Values{}
form.Set("Action", "DeleteUserPolicy")
form.Set("UserName", "NonExistentUser")
form.Set("PolicyName", "TestPolicy")
req, _ := http.NewRequest("POST", "/", nil)
req.PostForm = form
req.Form = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusNotFound, rr.Code)
}
// TestEmbeddedIamUpdateUser tests updating a user
func TestEmbeddedIamUpdateUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "TestUser"},
},
}
userName := aws.String("TestUser")
newUserName := aws.String("TestUser-New")
params := &iam.UpdateUserInput{NewUserName: newUserName, UserName: userName}
req, _ := iam.New(session.New()).UpdateUserRequest(params)
_ = req.Build()
out := iamUpdateUserResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
}
// TestEmbeddedIamDeleteUser tests deleting a user
func TestEmbeddedIamDeleteUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "TestUser-New"},
},
}
userName := aws.String("TestUser-New")
params := &iam.DeleteUserInput{UserName: userName}
req, _ := iam.New(session.New()).DeleteUserRequest(params)
_ = req.Build()
out := iamDeleteUserResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
}
// TestEmbeddedIamCreateAccessKey tests creating an access key
func TestEmbeddedIamCreateAccessKey(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "TestUser"},
},
}
userName := aws.String("TestUser")
params := &iam.CreateAccessKeyInput{UserName: userName}
req, _ := iam.New(session.New()).CreateAccessKeyRequest(params)
_ = req.Build()
out := iamCreateAccessKeyResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify response contains access key credentials
assert.NotNil(t, out.CreateAccessKeyResult.AccessKey.AccessKeyId)
assert.NotEmpty(t, *out.CreateAccessKeyResult.AccessKey.AccessKeyId)
assert.NotNil(t, out.CreateAccessKeyResult.AccessKey.SecretAccessKey)
assert.NotEmpty(t, *out.CreateAccessKeyResult.AccessKey.SecretAccessKey)
assert.NotNil(t, out.CreateAccessKeyResult.AccessKey.UserName)
assert.Equal(t, "TestUser", *out.CreateAccessKeyResult.AccessKey.UserName)
// Verify credentials were persisted
assert.Len(t, api.mockConfig.Identities[0].Credentials, 1)
}
// TestEmbeddedIamDeleteAccessKey tests deleting an access key via direct form post
func TestEmbeddedIamDeleteAccessKey(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "TestUser",
Credentials: []*iam_pb.Credential{
{AccessKey: "AKIATEST12345", SecretKey: "secret"},
},
},
},
}
// Use direct form post since AWS SDK may format differently
form := url.Values{}
form.Set("Action", "DeleteAccessKey")
form.Set("UserName", "TestUser")
form.Set("AccessKeyId", "AKIATEST12345")
req, _ := http.NewRequest("POST", "/", nil)
req.PostForm = form
req.Form = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
// Verify the access key was deleted
assert.Len(t, api.mockConfig.Identities[0].Credentials, 0)
}
// TestEmbeddedIamHandleImplicitUsername tests implicit username extraction from authorization header
func TestEmbeddedIamHandleImplicitUsername(t *testing.T) {
// Create IAM with test credentials - the handleImplicitUsername function now looks
// up the username from the credential store based on AccessKeyId
// Note: Using obviously fake access keys to avoid secret scanner false positives
iam := &IdentityAccessManagement{}
testConfig := &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "testuser1",
Credentials: []*iam_pb.Credential{
{AccessKey: "AKIATESTFAKEKEY000001", SecretKey: "testsecretfake"},
},
},
},
}
err := iam.LoadS3ApiConfigurationFromBytes(mustMarshalJSON(testConfig))
if err != nil {
t.Fatalf("Failed to load test config: %v", err)
}
embeddedApi := &EmbeddedIamApi{
iam: iam,
}
var tests = []struct {
r *http.Request
values url.Values
userName string
}{
// No authorization header - should not set username
{&http.Request{}, url.Values{}, ""},
// Valid auth header with known access key - should look up and find "testuser1"
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=AKIATESTFAKEKEY000001/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, "testuser1"},
// Malformed auth header (no Credential=) - should not set username
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 =AKIATESTFAKEKEY000001/20220420/test1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
// Unknown access key - should not set username
{&http.Request{Header: http.Header{"Authorization": []string{"AWS4-HMAC-SHA256 Credential=AKIATESTUNKNOWN000000/20220420/us-east-1/iam/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=fakesignature0123456789abcdef"}}}, url.Values{}, ""},
}
for i, test := range tests {
embeddedApi.handleImplicitUsername(test.r, test.values)
if un := test.values.Get("UserName"); un != test.userName {
t.Errorf("No.%d: Got: %v, Expected: %v", i, un, test.userName)
}
}
}
func mustMarshalJSON(v interface{}) []byte {
data, err := json.Marshal(v)
if err != nil {
panic(err)
}
return data
}
// TestEmbeddedIamFullWorkflow tests a complete user lifecycle
func TestEmbeddedIamFullWorkflow(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
// 1. Create user
t.Run("CreateUser", func(t *testing.T) {
userName := aws.String("WorkflowUser")
params := &iam.CreateUserInput{UserName: userName}
req, _ := iam.New(session.New()).CreateUserRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
})
// 2. Create access key for user
t.Run("CreateAccessKey", func(t *testing.T) {
userName := aws.String("WorkflowUser")
params := &iam.CreateAccessKeyInput{UserName: userName}
req, _ := iam.New(session.New()).CreateAccessKeyRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
})
// 3. Attach policy to user
t.Run("PutUserPolicy", func(t *testing.T) {
params := &iam.PutUserPolicyInput{
UserName: aws.String("WorkflowUser"),
PolicyName: aws.String("ReadWritePolicy"),
PolicyDocument: aws.String(`{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:Get*", "s3:Put*"],
"Resource": ["arn:aws:s3:::*"]
}]
}`),
}
req, _ := iam.New(session.New()).PutUserPolicyRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
})
// 4. List users to verify
t.Run("ListUsers", func(t *testing.T) {
params := &iam.ListUsersInput{}
req, _ := iam.New(session.New()).ListUsersRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
})
// 5. Delete user
t.Run("DeleteUser", func(t *testing.T) {
params := &iam.DeleteUserInput{UserName: aws.String("WorkflowUser")}
req, _ := iam.New(session.New()).DeleteUserRequest(params)
_ = req.Build()
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
})
}
// TestIamStringSlicesEqual tests the iamStringSlicesEqual helper function
func TestIamStringSlicesEqual(t *testing.T) {
tests := []struct {
name string
a []string
b []string
expected bool
}{
{"both empty", []string{}, []string{}, true},
{"both nil", nil, nil, true},
{"same elements same order", []string{"a", "b", "c"}, []string{"a", "b", "c"}, true},
{"same elements different order", []string{"c", "a", "b"}, []string{"a", "b", "c"}, true},
{"different lengths", []string{"a", "b"}, []string{"a", "b", "c"}, false},
{"different elements", []string{"a", "b", "c"}, []string{"a", "b", "d"}, false},
{"one empty one not", []string{}, []string{"a"}, false},
{"duplicates same", []string{"a", "a", "b"}, []string{"a", "b", "a"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := iamStringSlicesEqual(tt.a, tt.b)
assert.Equal(t, tt.expected, result)
})
}
}
// TestIamHash tests the iamHash function
func TestIamHash(t *testing.T) {
input := "test-policy-document"
hash := iamHash(&input)
// Hash should be non-empty
assert.NotEmpty(t, hash)
// Same input should produce same hash
hash2 := iamHash(&input)
assert.Equal(t, hash, hash2)
// Different input should produce different hash
input2 := "different-policy"
hash3 := iamHash(&input2)
assert.NotEqual(t, hash, hash3)
}
// TestIamStringWithCharset tests the cryptographically secure random string generator
func TestIamStringWithCharset(t *testing.T) {
charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
length := 20
str, err := iamStringWithCharset(length, charset)
assert.NoError(t, err)
assert.Len(t, str, length)
// All characters should be from the charset
for _, c := range str {
assert.Contains(t, charset, string(c))
}
// Two calls should produce different strings (with very high probability)
str2, err := iamStringWithCharset(length, charset)
assert.NoError(t, err)
assert.NotEqual(t, str, str2)
}
// TestIamMapToStatementAction tests action mapping
func TestIamMapToStatementAction(t *testing.T) {
// iamMapToStatementAction maps IAM statement action patterns to internal action names
tests := []struct {
input string
expected string
}{
{"*", "Admin"},
{"Get*", "Read"},
{"Put*", "Write"},
{"List*", "List"},
{"Tagging*", "Tagging"},
{"DeleteBucket*", "DeleteBucket"},
{"PutBucketAcl", "WriteAcp"},
{"GetBucketAcl", "ReadAcp"},
{"InvalidAction", ""},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result := iamMapToStatementAction(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
// TestIamMapToIdentitiesAction tests reverse action mapping
func TestIamMapToIdentitiesAction(t *testing.T) {
// iamMapToIdentitiesAction maps internal action names to IAM statement action patterns
tests := []struct {
input string
expected string
}{
{"Admin", "*"},
{"Read", "Get*"},
{"Write", "Put*"},
{"List", "List*"},
{"Tagging", "Tagging*"},
{"Unknown", ""},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result := iamMapToIdentitiesAction(tt.input)
assert.Equal(t, tt.expected, result)
})
}
}
// TestEmbeddedIamGetUserNotFound tests GetUser with non-existent user
func TestEmbeddedIamGetUserNotFound(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "ExistingUser"},
},
}
userName := aws.String("NonExistentUser")
params := &iam.GetUserInput{UserName: userName}
req, _ := iam.New(session.New()).GetUserRequest(params)
_ = req.Build()
response, _ := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.Equal(t, http.StatusNotFound, response.Code)
}
// TestEmbeddedIamDeleteUserNotFound tests DeleteUser with non-existent user
func TestEmbeddedIamDeleteUserNotFound(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
userName := aws.String("NonExistentUser")
params := &iam.DeleteUserInput{UserName: userName}
req, _ := iam.New(session.New()).DeleteUserRequest(params)
_ = req.Build()
response, _ := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.Equal(t, http.StatusNotFound, response.Code)
}
// TestEmbeddedIamUpdateUserNotFound tests UpdateUser with non-existent user
func TestEmbeddedIamUpdateUserNotFound(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
params := &iam.UpdateUserInput{
UserName: aws.String("NonExistentUser"),
NewUserName: aws.String("NewName"),
}
req, _ := iam.New(session.New()).UpdateUserRequest(params)
_ = req.Build()
response, _ := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.Equal(t, http.StatusBadRequest, response.Code)
}
// TestEmbeddedIamCreateAccessKeyForExistingUser tests CreateAccessKey creates credentials for existing user
func TestEmbeddedIamCreateAccessKeyForExistingUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{Name: "ExistingUser"},
},
}
// Use direct form post
form := url.Values{}
form.Set("Action", "CreateAccessKey")
form.Set("UserName", "ExistingUser")
req, _ := http.NewRequest("POST", "/", nil)
req.PostForm = form
req.Form = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
// Verify credentials were created
assert.Len(t, api.mockConfig.Identities[0].Credentials, 1)
}
// TestEmbeddedIamGetUserPolicyUserNotFound tests GetUserPolicy with non-existent user
func TestEmbeddedIamGetUserPolicyUserNotFound(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{}
params := &iam.GetUserPolicyInput{
UserName: aws.String("NonExistentUser"),
PolicyName: aws.String("TestPolicy"),
}
req, _ := iam.New(session.New()).GetUserPolicyRequest(params)
_ = req.Build()
response, _ := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.Equal(t, http.StatusNotFound, response.Code)
}
// TestEmbeddedIamCreatePolicyMalformed tests CreatePolicy with invalid policy document
func TestEmbeddedIamCreatePolicyMalformed(t *testing.T) {
api := NewEmbeddedIamApiForTest()
params := &iam.CreatePolicyInput{
PolicyName: aws.String("TestPolicy"),
PolicyDocument: aws.String("invalid json"),
}
req, _ := iam.New(session.New()).CreatePolicyRequest(params)
_ = req.Build()
response, _ := executeEmbeddedIamRequest(api, req.HTTPRequest, nil)
assert.Equal(t, http.StatusBadRequest, response.Code)
}
// TestEmbeddedIamListAccessKeysForUser tests listing access keys for a specific user
func TestEmbeddedIamListAccessKeysForUser(t *testing.T) {
api := NewEmbeddedIamApiForTest()
api.mockConfig = &iam_pb.S3ApiConfiguration{
Identities: []*iam_pb.Identity{
{
Name: "TestUser",
Credentials: []*iam_pb.Credential{
{AccessKey: "AKIATEST1", SecretKey: "secret1"},
{AccessKey: "AKIATEST2", SecretKey: "secret2"},
},
},
},
}
params := &iam.ListAccessKeysInput{UserName: aws.String("TestUser")}
req, _ := iam.New(session.New()).ListAccessKeysRequest(params)
_ = req.Build()
out := iamListAccessKeysResponse{}
response, err := executeEmbeddedIamRequest(api, req.HTTPRequest, &out)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, response.Code)
// Verify both access keys are listed
assert.Len(t, out.ListAccessKeysResult.AccessKeyMetadata, 2)
}
// TestEmbeddedIamNotImplementedAction tests handling of unimplemented actions
func TestEmbeddedIamNotImplementedAction(t *testing.T) {
api := NewEmbeddedIamApiForTest()
form := url.Values{}
form.Set("Action", "SomeUnknownAction")
req, _ := http.NewRequest("POST", "/", nil)
req.PostForm = form
req.Form = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
apiRouter := mux.NewRouter().SkipClean(true)
apiRouter.Path("/").Methods(http.MethodPost).HandlerFunc(api.DoActions)
apiRouter.ServeHTTP(rr, req)
assert.Equal(t, http.StatusNotImplemented, rr.Code)
}
// TestGetPolicyDocument tests parsing of policy documents
func TestGetPolicyDocument(t *testing.T) {
api := NewEmbeddedIamApiForTest()
validPolicy := `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::bucket/*"]
}]
}`
doc, err := api.GetPolicyDocument(&validPolicy)
assert.NoError(t, err)
assert.Equal(t, "2012-10-17", doc.Version)
assert.Len(t, doc.Statement, 1)
// Test invalid JSON
invalidPolicy := "not valid json"
_, err = api.GetPolicyDocument(&invalidPolicy)
assert.Error(t, err)
}
// TestEmbeddedIamGetActionsFromPolicy tests action extraction from policy documents
func TestEmbeddedIamGetActionsFromPolicy(t *testing.T) {
api := NewEmbeddedIamApiForTest()
// Actions must use wildcards (Get*, Put*, List*, etc.) as expected by the mapper
policyDoc := `{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:Get*", "s3:Put*"],
"Resource": ["arn:aws:s3:::mybucket/*"]
}]
}`
policy, err := api.GetPolicyDocument(&policyDoc)
assert.NoError(t, err)
actions, err := api.getActions(&policy)
assert.NoError(t, err)
assert.NotEmpty(t, actions)
// Should have Read and Write actions for the bucket
// arn:aws:s3:::mybucket/* means all objects in mybucket, represented as "Action:mybucket"
assert.Contains(t, actions, "Read:mybucket")
assert.Contains(t, actions, "Write:mybucket")
}