feat: add IAM user inline policy CRUD

Add support for AWS-compatible inline identity-based policies on IAM
users, implementing the `PutUserPolicy`, `GetUserPolicy`, `DeleteUserPolicy`, and `ListUserPolicies` actions on both the internal and Vault storage
backends.

- iamapi/policy is a new package that parses and validates policy documents against IAM's parameter-level constraints (max length, allowed charset) and policy grammar (Version, Effect, mutually exclusive Action/NotAction and Resource/NotResource, vendor-prefixed actions, ARN-shaped resources, no Principal/NotPrincipal, unique Sids).
- `PutUserPolicy` creates or replaces a named inline policy on a user, enforcing a 2048-byte aggregate quota across all of a user's inline policies (MaxInlinePolicyBytesPerUser), matching the AWS IAM quota.
- `GetUserPolicy` returns a policy's document RFC 3986 percent-encoded, matching how real IAM encodes the PolicyDocument response element.
- `DeleteUserPolicy` removes a named inline policy from a user.
- `ListUserPolicies` returns a paginated, sorted list of a user's inline policy names, honoring Marker/MaxItems like the other IAM list APIs.
- `DeleteUser` is now rejected with a DeleteConflict error if the user still has inline policies attached, mirroring the existing access-key delete-conflict behavior.
This commit is contained in:
niksis02
2026-07-10 03:17:23 +04:00
parent 001e7d88e4
commit 89b64910f3
20 changed files with 2645 additions and 78 deletions
+74
View File
@@ -1233,6 +1233,47 @@ func TestIAMListAccessKeys(ts *TestState) {
ts.Run(IAMListAccessKeys_pagination)
}
func TestIAMPutUserPolicy(ts *TestState) {
ts.Run(IAMPutUserPolicy_missing_user_name)
ts.Run(IAMPutUserPolicy_missing_policy_name)
ts.Run(IAMPutUserPolicy_missing_policy_document)
ts.Run(IAMPutUserPolicy_invalid_policy_name)
ts.Run(IAMPutUserPolicy_long_policy_name)
ts.Run(IAMPutUserPolicy_non_ascii_policy_document)
ts.Run(IAMPutUserPolicy_non_existing_user)
ts.Run(IAMPutUserPolicy_malformed_policy_document)
ts.Run(IAMPutUserPolicy_principal_not_allowed)
ts.Run(IAMPutUserPolicy_limit_exceeded)
ts.Run(IAMPutUserPolicy_success)
ts.Run(IAMPutUserPolicy_overwrite_updates_existing)
}
func TestIAMGetUserPolicy(ts *TestState) {
ts.Run(IAMGetUserPolicy_missing_user_name)
ts.Run(IAMGetUserPolicy_missing_policy_name)
ts.Run(IAMGetUserPolicy_non_existing_user)
ts.Run(IAMGetUserPolicy_non_existing_policy)
ts.Run(IAMGetUserPolicy_success)
}
func TestIAMDeleteUserPolicy(ts *TestState) {
ts.Run(IAMDeleteUserPolicy_missing_user_name)
ts.Run(IAMDeleteUserPolicy_missing_policy_name)
ts.Run(IAMDeleteUserPolicy_non_existing_user)
ts.Run(IAMDeleteUserPolicy_non_existing_policy)
ts.Run(IAMDeleteUserPolicy_success)
ts.Run(IAMDeleteUserPolicy_blocks_user_deletion)
}
func TestIAMListUserPolicies(ts *TestState) {
ts.Run(IAMListUserPolicies_missing_user_name)
ts.Run(IAMListUserPolicies_non_existing_user)
ts.Run(IAMListUserPolicies_invalid_max_items)
ts.Run(IAMListUserPolicies_empty_result)
ts.Run(IAMListUserPolicies_success)
ts.Run(IAMListUserPolicies_pagination)
}
func TestIAM(ts *TestState) {
TestIAMAuth(ts)
TestIAMQueryAuth(ts)
@@ -1246,6 +1287,10 @@ func TestIAM(ts *TestState) {
TestIAMDeleteAccessKey(ts)
TestIAMGetAccessKeyLastUsed(ts)
TestIAMListAccessKeys(ts)
TestIAMPutUserPolicy(ts)
TestIAMGetUserPolicy(ts)
TestIAMDeleteUserPolicy(ts)
TestIAMListUserPolicies(ts)
}
func TestAccessControl(ts *TestState) {
@@ -1674,6 +1719,35 @@ func GetIntTests() IntTests {
"IAMListAccessKeys_empty_result": IAMListAccessKeys_empty_result,
"IAMListAccessKeys_success": IAMListAccessKeys_success,
"IAMListAccessKeys_pagination": IAMListAccessKeys_pagination,
"IAMPutUserPolicy_missing_user_name": IAMPutUserPolicy_missing_user_name,
"IAMPutUserPolicy_missing_policy_name": IAMPutUserPolicy_missing_policy_name,
"IAMPutUserPolicy_missing_policy_document": IAMPutUserPolicy_missing_policy_document,
"IAMPutUserPolicy_invalid_policy_name": IAMPutUserPolicy_invalid_policy_name,
"IAMPutUserPolicy_long_policy_name": IAMPutUserPolicy_long_policy_name,
"IAMPutUserPolicy_non_ascii_policy_document": IAMPutUserPolicy_non_ascii_policy_document,
"IAMPutUserPolicy_non_existing_user": IAMPutUserPolicy_non_existing_user,
"IAMPutUserPolicy_malformed_policy_document": IAMPutUserPolicy_malformed_policy_document,
"IAMPutUserPolicy_principal_not_allowed": IAMPutUserPolicy_principal_not_allowed,
"IAMPutUserPolicy_limit_exceeded": IAMPutUserPolicy_limit_exceeded,
"IAMPutUserPolicy_success": IAMPutUserPolicy_success,
"IAMPutUserPolicy_overwrite_updates_existing": IAMPutUserPolicy_overwrite_updates_existing,
"IAMGetUserPolicy_missing_user_name": IAMGetUserPolicy_missing_user_name,
"IAMGetUserPolicy_missing_policy_name": IAMGetUserPolicy_missing_policy_name,
"IAMGetUserPolicy_non_existing_user": IAMGetUserPolicy_non_existing_user,
"IAMGetUserPolicy_non_existing_policy": IAMGetUserPolicy_non_existing_policy,
"IAMGetUserPolicy_success": IAMGetUserPolicy_success,
"IAMDeleteUserPolicy_missing_user_name": IAMDeleteUserPolicy_missing_user_name,
"IAMDeleteUserPolicy_missing_policy_name": IAMDeleteUserPolicy_missing_policy_name,
"IAMDeleteUserPolicy_non_existing_user": IAMDeleteUserPolicy_non_existing_user,
"IAMDeleteUserPolicy_non_existing_policy": IAMDeleteUserPolicy_non_existing_policy,
"IAMDeleteUserPolicy_success": IAMDeleteUserPolicy_success,
"IAMDeleteUserPolicy_blocks_user_deletion": IAMDeleteUserPolicy_blocks_user_deletion,
"IAMListUserPolicies_missing_user_name": IAMListUserPolicies_missing_user_name,
"IAMListUserPolicies_non_existing_user": IAMListUserPolicies_non_existing_user,
"IAMListUserPolicies_invalid_max_items": IAMListUserPolicies_invalid_max_items,
"IAMListUserPolicies_empty_result": IAMListUserPolicies_empty_result,
"IAMListUserPolicies_success": IAMListUserPolicies_success,
"IAMListUserPolicies_pagination": IAMListUserPolicies_pagination,
"PresignedAuth_security_token_not_supported": PresignedAuth_security_token_not_supported,
"PresignedAuth_unsupported_algorithm": PresignedAuth_unsupported_algorithm,
"PresignedAuth_ECDSA_not_supported": PresignedAuth_ECDSA_not_supported,
+203
View File
@@ -0,0 +1,203 @@
// Copyright 2026 Versity Software
// This file is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package integration
import (
"context"
"fmt"
"net/http"
"net/url"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/versity/versitygw/iamapi/iamerr"
)
func IAMDeleteUserPolicy_missing_user_name(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_missing_user_name"
body := []byte(url.Values{
"Action": {"DeleteUserPolicy"},
"Version": {"2010-05-08"},
"PolicyName": {"p"},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("userName"))
})
}
func IAMDeleteUserPolicy_missing_policy_name(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_missing_policy_name"
body := []byte(url.Values{
"Action": {"DeleteUserPolicy"},
"Version": {"2010-05-08"},
"UserName": {newIAMUserName()},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("policyName"))
})
}
func IAMDeleteUserPolicy_non_existing_user(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_non_existing_user"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := "non-existing-" + genRandString(16)
_, err := deleteIAMUserPolicyRaw(client, &iam.DeleteUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
})
return checkIAMApiErr(err, iamerr.NoSuchEntityUser(userName))
})
}
func IAMDeleteUserPolicy_non_existing_policy(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_non_existing_policy"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := checkIAMApiErr(
func() error {
_, err := deleteIAMUserPolicyRaw(client, &iam.DeleteUserPolicyInput{UserName: &userName, PolicyName: aws.String("missing")})
return err
}(),
iamerr.NoSuchEntityUserPolicy(userName, "missing"),
)
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMDeleteUserPolicy_success(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_success"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
out, err := deleteIAMUserPolicyRaw(client, &iam.DeleteUserPolicyInput{UserName: &userName, PolicyName: aws.String("p")})
if err != nil {
return err
}
if requestID, ok := awsmiddleware.GetRequestIDMetadata(out.ResultMetadata); !ok || requestID == "" {
return fmt.Errorf("expected DeleteUserPolicy response request id")
}
_, err = getIAMUserPolicy(client, &iam.GetUserPolicyInput{UserName: &userName, PolicyName: aws.String("p")})
return checkIAMApiErr(err, iamerr.NoSuchEntityUserPolicy(userName, "p"))
}()
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMDeleteUserPolicy_blocks_user_deletion(s *S3Conf) error {
testName := "IAMDeleteUserPolicy_blocks_user_deletion"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
checkErr := checkIAMApiErr(deleteIAMUser(client, userName), iamerr.GetAPIError(iamerr.ErrDeleteConflictPolicies))
deletePolicyErr := deleteIAMUserPolicy(client, userName, "p")
deleteUserErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
if deletePolicyErr != nil {
return deletePolicyErr
}
return deleteUserErr
})
}
func deleteIAMUserPolicyRaw(client *iam.Client, input *iam.DeleteUserPolicyInput) (*iam.DeleteUserPolicyOutput, error) {
ctx, cancel := context.WithTimeout(context.Background(), shortTimeout)
defer cancel()
return client.DeleteUserPolicy(ctx, input)
}
func deleteIAMUserPolicy(client *iam.Client, userName, policyName string) error {
_, err := deleteIAMUserPolicyRaw(client, &iam.DeleteUserPolicyInput{UserName: &userName, PolicyName: &policyName})
return err
}
// deleteIAMUserAndPolicies deletes all of the user's inline policies before
// deleting the user, since DeleteUser rejects users with policies still
// attached. Use this for test cleanup after a test has created inline
// policies.
func deleteIAMUserAndPolicies(client *iam.Client, userName string) error {
out, err := listIAMUserPolicies(client, &iam.ListUserPoliciesInput{UserName: &userName})
if err != nil {
return err
}
for _, policyName := range out.PolicyNames {
if err := deleteIAMUserPolicy(client, userName, policyName); err != nil {
return err
}
}
return deleteIAMUser(client, userName)
}
+165
View File
@@ -0,0 +1,165 @@
// Copyright 2026 Versity Software
// This file is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package integration
import (
"context"
"fmt"
"net/http"
"net/url"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/versity/versitygw/iamapi/iamerr"
)
func IAMGetUserPolicy_missing_user_name(s *S3Conf) error {
testName := "IAMGetUserPolicy_missing_user_name"
body := []byte(url.Values{
"Action": {"GetUserPolicy"},
"Version": {"2010-05-08"},
"PolicyName": {"p"},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("userName"))
})
}
func IAMGetUserPolicy_missing_policy_name(s *S3Conf) error {
testName := "IAMGetUserPolicy_missing_policy_name"
body := []byte(url.Values{
"Action": {"GetUserPolicy"},
"Version": {"2010-05-08"},
"UserName": {newIAMUserName()},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("policyName"))
})
}
func IAMGetUserPolicy_non_existing_user(s *S3Conf) error {
testName := "IAMGetUserPolicy_non_existing_user"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := "non-existing-" + genRandString(16)
_, err := getIAMUserPolicy(client, &iam.GetUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
})
return checkIAMApiErr(err, iamerr.NoSuchEntityUser(userName))
})
}
func IAMGetUserPolicy_non_existing_policy(s *S3Conf) error {
testName := "IAMGetUserPolicy_non_existing_policy"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := checkIAMApiErr(
func() error {
_, err := getIAMUserPolicy(client, &iam.GetUserPolicyInput{UserName: &userName, PolicyName: aws.String("missing")})
return err
}(),
iamerr.NoSuchEntityUserPolicy(userName, "missing"),
)
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMGetUserPolicy_success(s *S3Conf) error {
testName := "IAMGetUserPolicy_success"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("ReadOnly"),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
out, err := getIAMUserPolicy(client, &iam.GetUserPolicyInput{UserName: &userName, PolicyName: aws.String("ReadOnly")})
if err != nil {
return err
}
if out == nil {
return fmt.Errorf("expected GetUserPolicy output")
}
if aws.ToString(out.UserName) != userName {
return fmt.Errorf("expected user name %q, instead got %q", userName, aws.ToString(out.UserName))
}
if aws.ToString(out.PolicyName) != "ReadOnly" {
return fmt.Errorf("expected policy name %q, instead got %q", "ReadOnly", aws.ToString(out.PolicyName))
}
gotDocument, err := url.QueryUnescape(aws.ToString(out.PolicyDocument))
if err != nil {
return fmt.Errorf("failed to url-decode policy document %q: %w", aws.ToString(out.PolicyDocument), err)
}
if gotDocument != validIAMPolicyDocument {
return fmt.Errorf("expected policy document %q, instead got %q", validIAMPolicyDocument, gotDocument)
}
if requestID, ok := awsmiddleware.GetRequestIDMetadata(out.ResultMetadata); !ok || requestID == "" {
return fmt.Errorf("expected GetUserPolicy response request id")
}
return nil
}()
deleteErr := deleteIAMUserAndPolicies(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func getIAMUserPolicy(client *iam.Client, input *iam.GetUserPolicyInput) (*iam.GetUserPolicyOutput, error) {
ctx, cancel := context.WithTimeout(context.Background(), shortTimeout)
defer cancel()
return client.GetUserPolicy(ctx, input)
}
+223
View File
@@ -0,0 +1,223 @@
// Copyright 2026 Versity Software
// This file is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package integration
import (
"context"
"fmt"
"net/http"
"slices"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/versity/versitygw/iamapi/iamerr"
)
func IAMListUserPolicies_missing_user_name(s *S3Conf) error {
testName := "IAMListUserPolicies_missing_user_name"
body := []byte("Action=ListUserPolicies&Version=2010-05-08")
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("userName"))
})
}
func IAMListUserPolicies_non_existing_user(s *S3Conf) error {
testName := "IAMListUserPolicies_non_existing_user"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := "non-existing-" + genRandString(16)
_, err := listIAMUserPolicies(client, &iam.ListUserPoliciesInput{UserName: &userName})
return checkIAMApiErr(err, iamerr.NoSuchEntityUser(userName))
})
}
func IAMListUserPolicies_invalid_max_items(s *S3Conf) error {
testName := "IAMListUserPolicies_invalid_max_items"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := checkIAMApiErr(
func() error {
_, err := listIAMUserPolicies(client, &iam.ListUserPoliciesInput{UserName: &userName, MaxItems: aws.Int32(1001)})
return err
}(),
iamerr.InvalidMaxItems("1001"),
)
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMListUserPolicies_empty_result(s *S3Conf) error {
testName := "IAMListUserPolicies_empty_result"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
out, err := listIAMUserPolicies(client, &iam.ListUserPoliciesInput{UserName: &userName})
if err != nil {
return err
}
if len(out.PolicyNames) != 0 {
return fmt.Errorf("expected no policies, instead got %v", out.PolicyNames)
}
if out.IsTruncated {
return fmt.Errorf("expected IsTruncated to be false")
}
return nil
}()
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMListUserPolicies_success(s *S3Conf) error {
testName := "IAMListUserPolicies_success"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
want := []string{"Alpha", "Beta"}
for _, name := range want {
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String(name),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
}
out, err := listIAMUserPolicies(client, &iam.ListUserPoliciesInput{UserName: &userName})
if err != nil {
return err
}
if requestID, ok := awsmiddleware.GetRequestIDMetadata(out.ResultMetadata); !ok || requestID == "" {
return fmt.Errorf("expected ListUserPolicies response request id")
}
got := slices.Clone(out.PolicyNames)
slices.Sort(got)
if !slices.Equal(got, want) {
return fmt.Errorf("expected policy names %v, instead got %v", want, got)
}
if out.IsTruncated {
return fmt.Errorf("expected IsTruncated to be false")
}
return nil
}()
deleteErr := deleteIAMUserAndPolicies(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMListUserPolicies_pagination(s *S3Conf) error {
testName := "IAMListUserPolicies_pagination"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
want := []string{"Alpha", "Beta", "Gamma"}
for _, name := range want {
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String(name),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
}
input := iam.ListUserPoliciesInput{UserName: &userName, MaxItems: aws.Int32(1)}
var pages []*iam.ListUserPoliciesOutput
for {
out, err := listIAMUserPolicies(client, &input)
if err != nil {
return err
}
pages = append(pages, out)
if !out.IsTruncated {
break
}
input.Marker = out.Marker
}
if len(pages) != len(want) {
return fmt.Errorf("expected %d pages, instead got %d", len(want), len(pages))
}
var got []string
for i, page := range pages {
if len(page.PolicyNames) != 1 {
return fmt.Errorf("expected page %d to contain 1 policy, instead got %d", i+1, len(page.PolicyNames))
}
if page.IsTruncated != (i < len(pages)-1) {
return fmt.Errorf("unexpected IsTruncated value on page %d", i+1)
}
got = append(got, page.PolicyNames...)
}
slices.Sort(got)
if !slices.Equal(got, want) {
return fmt.Errorf("expected policy names %v, instead got %v", want, got)
}
return nil
}()
deleteErr := deleteIAMUserAndPolicies(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func listIAMUserPolicies(client *iam.Client, input *iam.ListUserPoliciesInput) (*iam.ListUserPoliciesOutput, error) {
ctx, cancel := context.WithTimeout(context.Background(), shortTimeout)
defer cancel()
return client.ListUserPolicies(ctx, input)
}
+376
View File
@@ -0,0 +1,376 @@
// Copyright 2026 Versity Software
// This file is licensed under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package integration
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/service/iam"
"github.com/versity/versitygw/iamapi/iamerr"
"github.com/versity/versitygw/iamapi/storage"
)
const validIAMPolicyDocument = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}`
func IAMPutUserPolicy_missing_user_name(s *S3Conf) error {
testName := "IAMPutUserPolicy_missing_user_name"
body := []byte(url.Values{
"Action": {"PutUserPolicy"},
"Version": {"2010-05-08"},
"PolicyName": {"p"},
"PolicyDocument": {validIAMPolicyDocument},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("userName"))
})
}
func IAMPutUserPolicy_missing_policy_name(s *S3Conf) error {
testName := "IAMPutUserPolicy_missing_policy_name"
body := []byte(url.Values{
"Action": {"PutUserPolicy"},
"Version": {"2010-05-08"},
"UserName": {newIAMUserName()},
"PolicyDocument": {validIAMPolicyDocument},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("policyName"))
})
}
func IAMPutUserPolicy_missing_policy_document(s *S3Conf) error {
testName := "IAMPutUserPolicy_missing_policy_document"
body := []byte(url.Values{
"Action": {"PutUserPolicy"},
"Version": {"2010-05-08"},
"UserName": {newIAMUserName()},
"PolicyName": {"p"},
}.Encode())
return authHandler(s, &authConfig{
testName: testName,
method: http.MethodPost,
service: "iam",
region: iamAuthRegion,
body: body,
date: time.Now().UTC(),
headers: map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
},
}, func(req *http.Request) error {
return checkIAMAuthRequest(s, req, iamerr.MissingValue("policyDocument"))
})
}
func IAMPutUserPolicy_invalid_policy_name(s *S3Conf) error {
testName := "IAMPutUserPolicy_invalid_policy_name"
return iamActionHandler(s, testName, func(client *iam.Client) error {
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: aws.String(newIAMUserName()),
PolicyName: aws.String("bad/name"),
PolicyDocument: aws.String(validIAMPolicyDocument),
})
return checkIAMApiErr(err, iamerr.InvalidUserName("policyName"))
})
}
func IAMPutUserPolicy_long_policy_name(s *S3Conf) error {
testName := "IAMPutUserPolicy_long_policy_name"
return iamActionHandler(s, testName, func(client *iam.Client) error {
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: aws.String(newIAMUserName()),
PolicyName: aws.String(strings.Repeat("p", 129)),
PolicyDocument: aws.String(validIAMPolicyDocument),
})
return checkIAMApiErr(err, iamerr.UserNameTooLong("policyName", 128))
})
}
func IAMPutUserPolicy_non_ascii_policy_document(s *S3Conf) error {
testName := "IAMPutUserPolicy_non_ascii_policy_document"
return iamActionHandler(s, testName, func(client *iam.Client) error {
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: aws.String(newIAMUserName()),
PolicyName: aws.String("p"),
PolicyDocument: aws.String("emoji\U0001F600test"),
})
return checkIAMApiErr(err, iamerr.InvalidCharset("policyDocument"))
})
}
func IAMPutUserPolicy_non_existing_user(s *S3Conf) error {
testName := "IAMPutUserPolicy_non_existing_user"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := "non-existing-" + genRandString(16)
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(validIAMPolicyDocument),
})
return checkIAMApiErr(err, iamerr.NoSuchEntityUser(userName))
})
}
func IAMPutUserPolicy_malformed_policy_document(s *S3Conf) error {
testName := "IAMPutUserPolicy_malformed_policy_document"
return iamActionHandler(s, testName, func(client *iam.Client) error {
cases := []struct {
name string
doc string
wantErr iamerr.APIError
}{
{"invalid json syntax", `{not valid json`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"empty object", `{}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"invalid version", `{"Version":"2020-01-01","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"missing statement", `{"Version":"2012-10-17"}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"null statement", `{"Version":"2012-10-17","Statement":null}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"empty statement array", `{"Version":"2012-10-17","Statement":[]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"statement is a string", `{"Version":"2012-10-17","Statement":"hello"}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"missing effect", `{"Version":"2012-10-17","Statement":[{"Action":"s3:GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"invalid effect value", `{"Version":"2012-10-17","Statement":[{"Effect":"Maybe","Action":"s3:GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"action and notaction both present", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","NotAction":"s3:PutObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"resource and notresource both present", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*","NotResource":"foo"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"numeric action wrong type", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":123,"Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Syntax errors in policy.")},
{"missing action and notaction", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Policy statement must contain actions.")},
{"missing resource and notresource", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject"}]}`, iamerr.MalformedPolicyDocument("Policy statement must contain resources.")},
{"empty resource array", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":[]}]}`, iamerr.MalformedPolicyDocument("Policy statement must contain resources.")},
{"empty string action", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Actions/Conditions must be prefaced by a vendor, e.g., iam, sdb, ec2, etc.")},
{"action missing vendor colon", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Actions/Conditions must be prefaced by a vendor, e.g., iam, sdb, ec2, etc.")},
{"notaction missing vendor colon", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","NotAction":"GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Actions/Conditions must be prefaced by a vendor, e.g., iam, sdb, ec2, etc.")},
{"empty vendor prefix", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":":GetObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Vendor is not valid")},
{"vendor with invalid character", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam :Get","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Vendor iam is not valid")},
{"resource with no colon at all", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"invalid"}]}`, iamerr.MalformedPolicyDocument(`Resource invalid must be in ARN format or "*".`)},
{"notresource with no colon at all", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","NotResource":"invalid"}]}`, iamerr.MalformedPolicyDocument(`Resource invalid must be in ARN format or "*".`)},
{"resource with colon but no arn prefix", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"s3::example-bucket/*"}]}`, iamerr.MalformedPolicyDocument(`Partition "" is not valid for resource "arn::example-bucket/*:*:*:*".`)},
{"resource with arn prefix but too few fields", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:awss3::example-bucket/*"}]}`, iamerr.MalformedPolicyDocument("The policy failed legacy parsing")},
{"resource with invalid partition", `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws2:s3:::example-bucket/*"}]}`, iamerr.MalformedPolicyDocument(`Partition "aws2" is not valid for resource "arn:aws2:s3:::example-bucket/*".`)},
{"duplicate sid across statements", `{"Version":"2012-10-17","Statement":[{"Sid":"Dup","Effect":"Allow","Action":"s3:GetObject","Resource":"*"},{"Sid":"Dup","Effect":"Allow","Action":"s3:PutObject","Resource":"*"}]}`, iamerr.MalformedPolicyDocument("Statement IDs (SID) in a single policy must be unique.")},
}
for _, c := range cases {
if err := func() error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return fmt.Errorf("%s: %w", c.name, err)
}
checkErr := func() error {
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(c.doc),
})
if err := checkIAMApiErr(err, c.wantErr); err != nil {
return fmt.Errorf("%s: %w", c.name, err)
}
return nil
}()
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
}(); err != nil {
return err
}
}
return nil
})
}
func IAMPutUserPolicy_principal_not_allowed(s *S3Conf) error {
testName := "IAMPutUserPolicy_principal_not_allowed"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
doc := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"*"}]}`
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(doc),
})
return checkIAMApiErr(err, iamerr.MalformedPolicyDocument("Policy document should not specify a principal."))
}()
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMPutUserPolicy_limit_exceeded(s *S3Conf) error {
testName := "IAMPutUserPolicy_limit_exceeded"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
oversized := `{"Version":"2012-10-17","Statement":[{"Sid":"` + strings.Repeat("x", 2000) + `","Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}`
_, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(oversized),
})
return checkIAMApiErr(err, iamerr.InlinePolicyQuotaExceeded("user", userName, storage.MaxInlinePolicyBytesPerUser))
}()
deleteErr := deleteIAMUser(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMPutUserPolicy_success(s *S3Conf) error {
testName := "IAMPutUserPolicy_success"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
out, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("ReadOnly"),
PolicyDocument: aws.String(validIAMPolicyDocument),
})
checkErr := func() error {
if err != nil {
return err
}
if out == nil {
return fmt.Errorf("expected PutUserPolicy output")
}
if requestID, ok := awsmiddleware.GetRequestIDMetadata(out.ResultMetadata); !ok || requestID == "" {
return fmt.Errorf("expected PutUserPolicy response request id")
}
got, err := getIAMUserPolicy(client, &iam.GetUserPolicyInput{UserName: &userName, PolicyName: aws.String("ReadOnly")})
if err != nil {
return err
}
gotDocument, err := url.QueryUnescape(aws.ToString(got.PolicyDocument))
if err != nil {
return fmt.Errorf("failed to url-decode policy document %q: %w", aws.ToString(got.PolicyDocument), err)
}
if gotDocument != validIAMPolicyDocument {
return fmt.Errorf("expected policy document %q, instead got %q", validIAMPolicyDocument, gotDocument)
}
return nil
}()
deleteErr := deleteIAMUserAndPolicies(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func IAMPutUserPolicy_overwrite_updates_existing(s *S3Conf) error {
testName := "IAMPutUserPolicy_overwrite_updates_existing"
return iamActionHandler(s, testName, func(client *iam.Client) error {
userName := newIAMUserName()
if _, err := createIAMUser(client, &iam.CreateUserInput{UserName: &userName}); err != nil {
return err
}
checkErr := func() error {
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(validIAMPolicyDocument),
}); err != nil {
return err
}
updated := `{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"s3:DeleteObject","Resource":"*"}]}`
if _, err := putIAMUserPolicy(client, &iam.PutUserPolicyInput{
UserName: &userName,
PolicyName: aws.String("p"),
PolicyDocument: aws.String(updated),
}); err != nil {
return err
}
got, err := getIAMUserPolicy(client, &iam.GetUserPolicyInput{UserName: &userName, PolicyName: aws.String("p")})
if err != nil {
return err
}
gotDocument, err := url.QueryUnescape(aws.ToString(got.PolicyDocument))
if err != nil {
return fmt.Errorf("failed to url-decode policy document %q: %w", aws.ToString(got.PolicyDocument), err)
}
if gotDocument != updated {
return fmt.Errorf("expected overwritten policy document %q, instead got %q", updated, gotDocument)
}
return nil
}()
deleteErr := deleteIAMUserAndPolicies(client, userName)
if checkErr != nil {
return checkErr
}
return deleteErr
})
}
func putIAMUserPolicy(client *iam.Client, input *iam.PutUserPolicyInput) (*iam.PutUserPolicyOutput, error) {
ctx, cancel := context.WithTimeout(context.Background(), shortTimeout)
defer cancel()
return client.PutUserPolicy(ctx, input)
}