chore: remove ~50k lines of unreachable dead code (#8913)

* chore: remove unreachable dead code across the codebase

Remove ~50,000 lines of unreachable code identified by static analysis.

Major removals:
- weed/filer/redis_lua: entire unused Redis Lua filer store implementation
- weed/wdclient/net2, resource_pool: unused connection/resource pool packages
- weed/plugin/worker/lifecycle: unused lifecycle plugin worker
- weed/s3api: unused S3 policy templates, presigned URL IAM, streaming copy,
  multipart IAM, key rotation, and various SSE helper functions
- weed/mq/kafka: unused partition mapping, compression, schema, and protocol functions
- weed/mq/offset: unused SQL storage and migration code
- weed/worker: unused registry, task, and monitoring functions
- weed/query: unused SQL engine, parquet scanner, and type functions
- weed/shell: unused EC proportional rebalance functions
- weed/storage/erasure_coding/distribution: unused distribution analysis functions
- Individual unreachable functions removed from 150+ files across admin,
  credential, filer, iam, kms, mount, mq, operation, pb, s3api, server,
  shell, storage, topology, and util packages

* fix(s3): reset shared memory store in IAM test to prevent flaky failure

TestLoadIAMManagerFromConfig_EmptyConfigWithFallbackKey was flaky because
the MemoryStore credential backend is a singleton registered via init().
Earlier tests that create anonymous identities pollute the shared store,
causing LookupAnonymous() to unexpectedly return true.

Fix by calling Reset() on the memory store before the test runs.

* style: run gofmt on changed files

* fix: restore KMS functions used by integration tests

* fix(plugin): prevent panic on send to closed worker session channel

The Plugin.sendToWorker method could panic with "send on closed channel"
when a worker disconnected while a message was being sent. The race was
between streamSession.close() closing the outgoing channel and sendToWorker
writing to it concurrently.

Add a done channel to streamSession that is closed before the outgoing
channel, and check it in sendToWorker's select to safely detect closed
sessions without panicking.
This commit is contained in:
Chris Lu
2026-04-03 16:04:27 -07:00
committed by GitHub
parent 8fad85aed7
commit 995dfc4d5d
264 changed files with 62 additions and 46027 deletions

View File

@@ -1,687 +0,0 @@
package policy
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConditionSetOperators(t *testing.T) {
engine := setupTestPolicyEngine(t)
t.Run("ForAnyValue:StringEquals", func(t *testing.T) {
trustPolicy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowOIDC",
Effect: "Allow",
Action: []string{"sts:AssumeRoleWithWebIdentity"},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringEquals": {
"oidc:roles": []string{"Dev.SeaweedFS.TestBucket.ReadWrite", "Dev.SeaweedFS.Admin"},
},
},
},
},
}
// Match: Admin is in the requested roles
evalCtxMatch := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"Dev.SeaweedFS.Admin", "OtherRole"},
},
}
resultMatch, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicy, evalCtxMatch)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultMatch.Effect)
// No Match
evalCtxNoMatch := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"OtherRole1", "OtherRole2"},
},
}
resultNoMatch, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicy, evalCtxNoMatch)
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultNoMatch.Effect)
// No Match: Empty context for ForAnyValue (should deny)
evalCtxEmpty := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{},
},
}
resultEmpty, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicy, evalCtxEmpty)
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultEmpty.Effect, "ForAnyValue should deny when context is empty")
})
t.Run("ForAllValues:StringEquals", func(t *testing.T) {
trustPolicyAll := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowOIDCAll",
Effect: "Allow",
Action: []string{"sts:AssumeRoleWithWebIdentity"},
Condition: map[string]map[string]interface{}{
"ForAllValues:StringEquals": {
"oidc:roles": []string{"RoleA", "RoleB", "RoleC"},
},
},
},
},
}
// Match: All requested roles ARE in the allowed set
evalCtxAllMatch := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"RoleA", "RoleB"},
},
}
resultAllMatch, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicyAll, evalCtxAllMatch)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultAllMatch.Effect)
// Fail: RoleD is NOT in the allowed set
evalCtxAllFail := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"RoleA", "RoleD"},
},
}
resultAllFail, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicyAll, evalCtxAllFail)
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultAllFail.Effect)
// Vacuously true: Request has NO roles
evalCtxEmpty := &EvaluationContext{
Principal: "web-identity-user",
Action: "sts:AssumeRoleWithWebIdentity",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{},
},
}
resultEmpty, err := engine.EvaluateTrustPolicy(context.Background(), trustPolicyAll, evalCtxEmpty)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultEmpty.Effect)
})
t.Run("ForAllValues:NumericEqualsVacuouslyTrue", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowNumericAll",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:NumericEquals": {
"aws:MultiFactorAuthAge": []string{"3600", "7200"},
},
},
},
},
}
// Vacuously true: Request has NO MFA age info
evalCtxEmpty := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:MultiFactorAuthAge": []string{},
},
}
resultEmpty, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxEmpty)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultEmpty.Effect, "Should allow when numeric context is empty for ForAllValues")
})
t.Run("ForAllValues:BoolVacuouslyTrue", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowBoolAll",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:Bool": {
"aws:SecureTransport": "true",
},
},
},
},
}
// Vacuously true
evalCtxEmpty := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:SecureTransport": []interface{}{},
},
}
resultEmpty, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxEmpty)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultEmpty.Effect, "Should allow when bool context is empty for ForAllValues")
})
t.Run("ForAllValues:DateVacuouslyTrue", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowDateAll",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:DateGreaterThan": {
"aws:CurrentTime": "2020-01-01T00:00:00Z",
},
},
},
},
}
// Vacuously true
evalCtxEmpty := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:CurrentTime": []interface{}{},
},
}
resultEmpty, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxEmpty)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultEmpty.Effect, "Should allow when date context is empty for ForAllValues")
})
t.Run("ForAllValues:DateWithLabelsAsStrings", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowDateStrings",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:DateGreaterThan": {
"aws:CurrentTime": "2020-01-01T00:00:00Z",
},
},
},
},
}
evalCtx := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:CurrentTime": []string{"2021-01-01T00:00:00Z", "2022-01-01T00:00:00Z"},
},
}
result, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtx)
require.NoError(t, err)
assert.Equal(t, EffectAllow, result.Effect, "Should allow when date context is a slice of strings")
})
t.Run("ForAllValues:BoolWithLabelsAsStrings", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowBoolStrings",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:Bool": {
"aws:SecureTransport": "true",
},
},
},
},
}
evalCtx := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:SecureTransport": []string{"true", "true"},
},
}
result, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtx)
require.NoError(t, err)
assert.Equal(t, EffectAllow, result.Effect, "Should allow when bool context is a slice of strings")
})
t.Run("StringEqualsIgnoreCaseWithVariable", func(t *testing.T) {
policyDoc := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowVar",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::bucket/*"},
Condition: map[string]map[string]interface{}{
"StringEqualsIgnoreCase": {
"s3:prefix": "${aws:username}/",
},
},
},
},
}
err := engine.AddPolicy("", "var-policy", policyDoc)
require.NoError(t, err)
evalCtx := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/ALICE/file.txt",
RequestContext: map[string]interface{}{
"s3:prefix": "ALICE/",
"aws:username": "alice",
},
}
result, err := engine.Evaluate(context.Background(), "", evalCtx, []string{"var-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, result.Effect, "Should allow when variable expands and matches case-insensitively")
})
t.Run("StringLike:CaseSensitivity", func(t *testing.T) {
policyDoc := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowCaseSensitiveLike",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::bucket/*"},
Condition: map[string]map[string]interface{}{
"StringLike": {
"s3:prefix": "Project/*",
},
},
},
},
}
err := engine.AddPolicy("", "like-policy", policyDoc)
require.NoError(t, err)
// Match: Case sensitive match
evalCtxMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/Project/file.txt",
RequestContext: map[string]interface{}{
"s3:prefix": "Project/data",
},
}
resultMatch, err := engine.Evaluate(context.Background(), "", evalCtxMatch, []string{"like-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultMatch.Effect, "Should allow when case matches exactly")
// Fail: Case insensitive match (should fail for StringLike)
evalCtxFail := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/project/file.txt",
RequestContext: map[string]interface{}{
"s3:prefix": "project/data", // lowercase 'p'
},
}
resultFail, err := engine.Evaluate(context.Background(), "", evalCtxFail, []string{"like-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultFail.Effect, "Should deny when case does not match for StringLike")
})
t.Run("NumericNotEquals:Logic", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "DenySpecificAges",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"ForAllValues:NumericNotEquals": {
"aws:MultiFactorAuthAge": []string{"3600", "7200"},
},
},
},
},
}
err := engine.AddPolicy("", "numeric-not-equals-policy", policy)
require.NoError(t, err)
// Fail: One age matches an excluded value (3600)
evalCtxFail := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:MultiFactorAuthAge": []string{"3600", "1800"},
},
}
resultFail, err := engine.Evaluate(context.Background(), "", evalCtxFail, []string{"numeric-not-equals-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultFail.Effect, "Should deny when one age matches an excluded value")
// Pass: No age matches any excluded value
evalCtxPass := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:MultiFactorAuthAge": []string{"1800", "900"},
},
}
resultPass, err := engine.Evaluate(context.Background(), "", evalCtxPass, []string{"numeric-not-equals-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultPass.Effect, "Should allow when no age matches excluded values")
})
t.Run("DateNotEquals:Logic", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "DenySpecificTimes",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"ForAllValues:DateNotEquals": {
"aws:CurrentTime": []string{"2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z"},
},
},
},
},
}
err := engine.AddPolicy("", "date-not-equals-policy", policy)
require.NoError(t, err)
// Fail: One time matches an excluded value
evalCtxFail := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"aws:CurrentTime": []string{"2024-01-01T00:00:00Z", "2024-01-03T00:00:00Z"},
},
}
resultFail, err := engine.Evaluate(context.Background(), "", evalCtxFail, []string{"date-not-equals-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultFail.Effect, "Should deny when one date matches an excluded value")
})
t.Run("IpAddress:SetOperators", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowSpecificIPs",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"ForAllValues:IpAddress": {
"aws:SourceIp": []string{"192.168.1.0/24", "10.0.0.1"},
},
},
},
},
}
err := engine.AddPolicy("", "ip-set-policy", policy)
require.NoError(t, err)
// Match: All source IPs are in allowed ranges
evalCtxMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": []string{"192.168.1.10", "10.0.0.1"},
},
}
resultMatch, err := engine.Evaluate(context.Background(), "", evalCtxMatch, []string{"ip-set-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultMatch.Effect)
// Fail: One source IP is NOT in allowed ranges
evalCtxFail := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": []string{"192.168.1.10", "172.16.0.1"},
},
}
resultFail, err := engine.Evaluate(context.Background(), "", evalCtxFail, []string{"ip-set-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultFail.Effect)
// ForAnyValue: IPAddress
policyAny := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowAnySpecificIPs",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"ForAnyValue:IpAddress": {
"aws:SourceIp": []string{"192.168.1.0/24"},
},
},
},
},
}
err = engine.AddPolicy("", "ip-any-policy", policyAny)
require.NoError(t, err)
evalCtxAnyMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": []string{"192.168.1.10", "172.16.0.1"},
},
}
resultAnyMatch, err := engine.Evaluate(context.Background(), "", evalCtxAnyMatch, []string{"ip-any-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultAnyMatch.Effect)
})
t.Run("IpAddress:SingleStringValue", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowSingleIP",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"IpAddress": {
"aws:SourceIp": "192.168.1.1",
},
},
},
},
}
err := engine.AddPolicy("", "ip-single-policy", policy)
require.NoError(t, err)
evalCtxMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "192.168.1.1",
},
}
resultMatch, err := engine.Evaluate(context.Background(), "", evalCtxMatch, []string{"ip-single-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultMatch.Effect)
evalCtxNoMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "10.0.0.1",
},
}
resultNoMatch, err := engine.Evaluate(context.Background(), "", evalCtxNoMatch, []string{"ip-single-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultNoMatch.Effect)
})
t.Run("Bool:StringSlicePolicyValues", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowWithBoolStrings",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"Bool": {
"aws:SecureTransport": []string{"true", "false"},
},
},
},
},
}
err := engine.AddPolicy("", "bool-string-slice-policy", policy)
require.NoError(t, err)
evalCtx := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SecureTransport": "true",
},
}
result, err := engine.Evaluate(context.Background(), "", evalCtx, []string{"bool-string-slice-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, result.Effect)
})
t.Run("StringEqualsIgnoreCase:StringSlicePolicyValues", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowWithIgnoreCaseStrings",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"StringEqualsIgnoreCase": {
"s3:x-amz-server-side-encryption": []string{"AES256", "aws:kms"},
},
},
},
},
}
err := engine.AddPolicy("", "string-ignorecase-slice-policy", policy)
require.NoError(t, err)
evalCtx := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"s3:x-amz-server-side-encryption": "aes256",
},
}
result, err := engine.Evaluate(context.Background(), "", evalCtx, []string{"string-ignorecase-slice-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, result.Effect)
})
t.Run("IpAddress:CustomContextKey", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowCustomIPKey",
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"*"},
Condition: map[string]map[string]interface{}{
"IpAddress": {
"custom:VpcIp": "10.0.0.0/16",
},
},
},
},
}
err := engine.AddPolicy("", "ip-custom-key-policy", policy)
require.NoError(t, err)
evalCtxMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"custom:VpcIp": "10.0.5.1",
},
}
resultMatch, err := engine.Evaluate(context.Background(), "", evalCtxMatch, []string{"ip-custom-key-policy"})
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultMatch.Effect)
evalCtxNoMatch := &EvaluationContext{
Principal: "user",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::bucket/file.txt",
RequestContext: map[string]interface{}{
"custom:VpcIp": "192.168.1.1",
},
}
resultNoMatch, err := engine.Evaluate(context.Background(), "", evalCtxNoMatch, []string{"ip-custom-key-policy"})
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultNoMatch.Effect)
})
}

View File

@@ -1,101 +0,0 @@
package policy
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNegationSetOperators(t *testing.T) {
engine := setupTestPolicyEngine(t)
t.Run("ForAllValues:StringNotEquals", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "DenyAdmin",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAllValues:StringNotEquals": {
"oidc:roles": []string{"Admin"},
},
},
},
},
}
// All roles are NOT "Admin" -> Should Allow
evalCtxAllow := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"User", "Developer"},
},
}
resultAllow, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxAllow)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultAllow.Effect, "Should allow when ALL roles satisfy StringNotEquals Admin")
// One role is "Admin" -> Should Deny
evalCtxDeny := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"Admin", "User"},
},
}
resultDeny, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxDeny)
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultDeny.Effect, "Should deny when one role is Admin and fails StringNotEquals")
})
t.Run("ForAnyValue:StringNotEquals", func(t *testing.T) {
policy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "Requirement",
Effect: "Allow",
Action: []string{"sts:AssumeRole"},
Condition: map[string]map[string]interface{}{
"ForAnyValue:StringNotEquals": {
"oidc:roles": []string{"Prohibited"},
},
},
},
},
}
// At least one role is NOT prohibited -> Should Allow
evalCtxAllow := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"Prohibited", "Allowed"},
},
}
resultAllow, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxAllow)
require.NoError(t, err)
assert.Equal(t, EffectAllow, resultAllow.Effect, "Should allow when at least one role is NOT Prohibited")
// All roles are Prohibited -> Should Deny
evalCtxDeny := &EvaluationContext{
Principal: "user",
Action: "sts:AssumeRole",
Resource: "arn:aws:iam::role/test-role",
RequestContext: map[string]interface{}{
"oidc:roles": []string{"Prohibited", "Prohibited"},
},
}
resultDeny, err := engine.EvaluateTrustPolicy(context.Background(), policy, evalCtxDeny)
require.NoError(t, err)
assert.Equal(t, EffectDeny, resultDeny.Effect, "Should deny when ALL roles are Prohibited")
})
}

View File

@@ -1155,11 +1155,6 @@ func ValidatePolicyDocumentWithType(policy *PolicyDocument, policyType string) e
return nil
}
// validateStatement validates a single statement (for backward compatibility)
func validateStatement(statement *Statement) error {
return validateStatementWithType(statement, "resource")
}
// validateStatementWithType validates a single statement based on policy type
func validateStatementWithType(statement *Statement, policyType string) error {
if statement.Effect != "Allow" && statement.Effect != "Deny" {
@@ -1198,29 +1193,6 @@ func validateStatementWithType(statement *Statement, policyType string) error {
return nil
}
// matchResource checks if a resource pattern matches a requested resource
// Uses hybrid approach: simple suffix wildcards for compatibility, filepath.Match for complex patterns
func matchResource(pattern, resource string) bool {
if pattern == resource {
return true
}
// Handle simple suffix wildcard (backward compatibility)
if strings.HasSuffix(pattern, "*") {
prefix := pattern[:len(pattern)-1]
return strings.HasPrefix(resource, prefix)
}
// For complex patterns, use filepath.Match for advanced wildcard support (*, ?, [])
matched, err := filepath.Match(pattern, resource)
if err != nil {
// Fallback to exact match if pattern is malformed
return pattern == resource
}
return matched
}
// awsIAMMatch performs AWS IAM-compliant pattern matching with case-insensitivity and policy variable support
func awsIAMMatch(pattern, value string, evalCtx *EvaluationContext) bool {
// Step 1: Substitute policy variables (e.g., ${aws:username}, ${saml:username})
@@ -1274,16 +1246,6 @@ func expandPolicyVariables(pattern string, evalCtx *EvaluationContext) string {
return result
}
// getContextValue safely gets a value from the evaluation context
func getContextValue(evalCtx *EvaluationContext, key, defaultValue string) string {
if value, exists := evalCtx.RequestContext[key]; exists {
if str, ok := value.(string); ok {
return str
}
}
return defaultValue
}
// AwsWildcardMatch performs case-insensitive wildcard matching like AWS IAM
func AwsWildcardMatch(pattern, value string) bool {
// Create regex pattern key for caching
@@ -1322,29 +1284,6 @@ func AwsWildcardMatch(pattern, value string) bool {
return regex.MatchString(value)
}
// matchAction checks if an action pattern matches a requested action
// Uses hybrid approach: simple suffix wildcards for compatibility, filepath.Match for complex patterns
func matchAction(pattern, action string) bool {
if pattern == action {
return true
}
// Handle simple suffix wildcard (backward compatibility)
if strings.HasSuffix(pattern, "*") {
prefix := pattern[:len(pattern)-1]
return strings.HasPrefix(action, prefix)
}
// For complex patterns, use filepath.Match for advanced wildcard support (*, ?, [])
matched, err := filepath.Match(pattern, action)
if err != nil {
// Fallback to exact match if pattern is malformed
return pattern == action
}
return matched
}
// evaluateStringConditionIgnoreCase evaluates string conditions with case insensitivity
func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interface{}, evalCtx *EvaluationContext, shouldMatch bool, useWildcard bool, forAllValues bool) bool {
for key, expectedValues := range block {

View File

@@ -1,421 +0,0 @@
package policy
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestPrincipalMatching tests the matchesPrincipal method
func TestPrincipalMatching(t *testing.T) {
engine := setupTestPolicyEngine(t)
tests := []struct {
name string
principal interface{}
evalCtx *EvaluationContext
want bool
}{
{
name: "plain wildcard principal",
principal: "*",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: true,
},
{
name: "structured wildcard federated principal",
principal: map[string]interface{}{
"Federated": "*",
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: true,
},
{
name: "wildcard in array",
principal: map[string]interface{}{
"Federated": []interface{}{"specific-provider", "*"},
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: true,
},
{
name: "specific federated provider match",
principal: map[string]interface{}{
"Federated": "https://example.com/oidc",
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://example.com/oidc",
},
},
want: true,
},
{
name: "specific federated provider no match",
principal: map[string]interface{}{
"Federated": "https://example.com/oidc",
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://other.com/oidc",
},
},
want: false,
},
{
name: "array with specific provider match",
principal: map[string]interface{}{
"Federated": []string{"https://provider1.com", "https://provider2.com"},
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://provider2.com",
},
},
want: true,
},
{
name: "AWS principal match",
principal: map[string]interface{}{
"AWS": "arn:aws:iam::123456789012:user/alice",
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:PrincipalArn": "arn:aws:iam::123456789012:user/alice",
},
},
want: true,
},
{
name: "Service principal match",
principal: map[string]interface{}{
"Service": "s3.amazonaws.com",
},
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:PrincipalServiceName": "s3.amazonaws.com",
},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := engine.matchesPrincipal(tt.principal, tt.evalCtx)
assert.Equal(t, tt.want, result, "Principal matching failed for: %s", tt.name)
})
}
}
// TestEvaluatePrincipalValue tests the evaluatePrincipalValue method
func TestEvaluatePrincipalValue(t *testing.T) {
engine := setupTestPolicyEngine(t)
tests := []struct {
name string
principalValue interface{}
contextKey string
evalCtx *EvaluationContext
want bool
}{
{
name: "wildcard string",
principalValue: "*",
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: true,
},
{
name: "specific string match",
principalValue: "https://example.com",
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://example.com",
},
},
want: true,
},
{
name: "specific string no match",
principalValue: "https://example.com",
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://other.com",
},
},
want: false,
},
{
name: "wildcard in array",
principalValue: []interface{}{"provider1", "*"},
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: true,
},
{
name: "array match",
principalValue: []string{"provider1", "provider2", "provider3"},
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "provider2",
},
},
want: true,
},
{
name: "array no match",
principalValue: []string{"provider1", "provider2"},
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "provider3",
},
},
want: false,
},
{
name: "missing context key",
principalValue: "specific-value",
contextKey: "aws:FederatedProvider",
evalCtx: &EvaluationContext{
RequestContext: map[string]interface{}{},
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := engine.evaluatePrincipalValue(tt.principalValue, tt.evalCtx, tt.contextKey)
assert.Equal(t, tt.want, result, "Principal value evaluation failed for: %s", tt.name)
})
}
}
// TestTrustPolicyEvaluation tests the EvaluateTrustPolicy method
func TestTrustPolicyEvaluation(t *testing.T) {
engine := setupTestPolicyEngine(t)
tests := []struct {
name string
trustPolicy *PolicyDocument
evalCtx *EvaluationContext
wantEffect Effect
wantErr bool
}{
{
name: "wildcard federated principal allows any provider",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "*",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://any-provider.com",
},
},
wantEffect: EffectAllow,
wantErr: false,
},
{
name: "specific federated principal matches",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "https://example.com/oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://example.com/oidc",
},
},
wantEffect: EffectAllow,
wantErr: false,
},
{
name: "specific federated principal does not match",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "https://example.com/oidc",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://other.com/oidc",
},
},
wantEffect: EffectDeny,
wantErr: false,
},
{
name: "plain wildcard principal",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: "*",
Action: []string{"sts:AssumeRoleWithWebIdentity"},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://any-provider.com",
},
},
wantEffect: EffectAllow,
wantErr: false,
},
{
name: "trust policy with conditions",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "*",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
Condition: map[string]map[string]interface{}{
"StringEquals": {
"oidc:aud": "my-app-id",
},
},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://provider.com",
"oidc:aud": "my-app-id",
},
},
wantEffect: EffectAllow,
wantErr: false,
},
{
name: "trust policy condition not met",
trustPolicy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Allow",
Principal: map[string]interface{}{
"Federated": "*",
},
Action: []string{"sts:AssumeRoleWithWebIdentity"},
Condition: map[string]map[string]interface{}{
"StringEquals": {
"oidc:aud": "my-app-id",
},
},
},
},
},
evalCtx: &EvaluationContext{
Action: "sts:AssumeRoleWithWebIdentity",
RequestContext: map[string]interface{}{
"aws:FederatedProvider": "https://provider.com",
"oidc:aud": "wrong-app-id",
},
},
wantEffect: EffectDeny,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := engine.EvaluateTrustPolicy(context.Background(), tt.trustPolicy, tt.evalCtx)
if tt.wantErr {
assert.Error(t, err)
} else {
require.NoError(t, err)
assert.Equal(t, tt.wantEffect, result.Effect, "Trust policy evaluation failed for: %s", tt.name)
}
})
}
}
// TestGetPrincipalContextKey tests the context key mapping
func TestGetPrincipalContextKey(t *testing.T) {
tests := []struct {
name string
principalType string
want string
}{
{
name: "Federated principal",
principalType: "Federated",
want: "aws:FederatedProvider",
},
{
name: "AWS principal",
principalType: "AWS",
want: "aws:PrincipalArn",
},
{
name: "Service principal",
principalType: "Service",
want: "aws:PrincipalServiceName",
},
{
name: "Custom principal type",
principalType: "CustomType",
want: "aws:PrincipalCustomType",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := getPrincipalContextKey(tt.principalType)
assert.Equal(t, tt.want, result, "Context key mapping failed for: %s", tt.name)
})
}
}

View File

@@ -1,426 +0,0 @@
package policy
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestPolicyEngineInitialization tests policy engine initialization
func TestPolicyEngineInitialization(t *testing.T) {
tests := []struct {
name string
config *PolicyEngineConfig
wantErr bool
}{
{
name: "valid config",
config: &PolicyEngineConfig{
DefaultEffect: "Deny",
StoreType: "memory",
},
wantErr: false,
},
{
name: "invalid default effect",
config: &PolicyEngineConfig{
DefaultEffect: "Invalid",
StoreType: "memory",
},
wantErr: true,
},
{
name: "nil config",
config: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
engine := NewPolicyEngine()
err := engine.Initialize(tt.config)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.True(t, engine.IsInitialized())
}
})
}
}
// TestPolicyDocumentValidation tests policy document structure validation
func TestPolicyDocumentValidation(t *testing.T) {
tests := []struct {
name string
policy *PolicyDocument
wantErr bool
errorMsg string
}{
{
name: "valid policy document",
policy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowS3Read",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:ListBucket"},
Resource: []string{"arn:aws:s3:::mybucket/*"},
},
},
},
wantErr: false,
},
{
name: "missing version",
policy: &PolicyDocument{
Statement: []Statement{
{
Effect: "Allow",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::mybucket/*"},
},
},
},
wantErr: true,
errorMsg: "version is required",
},
{
name: "empty statements",
policy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{},
},
wantErr: true,
errorMsg: "at least one statement is required",
},
{
name: "invalid effect",
policy: &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Effect: "Maybe",
Action: []string{"s3:GetObject"},
Resource: []string{"arn:aws:s3:::mybucket/*"},
},
},
},
wantErr: true,
errorMsg: "invalid effect",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidatePolicyDocument(tt.policy)
if tt.wantErr {
assert.Error(t, err)
if tt.errorMsg != "" {
assert.Contains(t, err.Error(), tt.errorMsg)
}
} else {
assert.NoError(t, err)
}
})
}
}
// TestPolicyEvaluation tests policy evaluation logic
func TestPolicyEvaluation(t *testing.T) {
engine := setupTestPolicyEngine(t)
// Add test policies
readPolicy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowS3Read",
Effect: "Allow",
Action: []string{"s3:GetObject", "s3:ListBucket"},
Resource: []string{
"arn:aws:s3:::public-bucket/*", // For object operations
"arn:aws:s3:::public-bucket", // For bucket operations
},
},
},
}
err := engine.AddPolicy("", "read-policy", readPolicy)
require.NoError(t, err)
denyPolicy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "DenyS3Delete",
Effect: "Deny",
Action: []string{"s3:DeleteObject"},
Resource: []string{"arn:aws:s3:::*"},
},
},
}
err = engine.AddPolicy("", "deny-policy", denyPolicy)
require.NoError(t, err)
tests := []struct {
name string
context *EvaluationContext
policies []string
want Effect
}{
{
name: "allow read access",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::public-bucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "192.168.1.100",
},
},
policies: []string{"read-policy"},
want: EffectAllow,
},
{
name: "deny delete access (explicit deny)",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:DeleteObject",
Resource: "arn:aws:s3:::public-bucket/file.txt",
},
policies: []string{"read-policy", "deny-policy"},
want: EffectDeny,
},
{
name: "deny by default (no matching policy)",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:PutObject",
Resource: "arn:aws:s3:::public-bucket/file.txt",
},
policies: []string{"read-policy"},
want: EffectDeny,
},
{
name: "allow with wildcard action",
context: &EvaluationContext{
Principal: "user:admin",
Action: "s3:ListBucket",
Resource: "arn:aws:s3:::public-bucket",
},
policies: []string{"read-policy"},
want: EffectAllow,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := engine.Evaluate(context.Background(), "", tt.context, tt.policies)
assert.NoError(t, err)
assert.Equal(t, tt.want, result.Effect)
// Verify evaluation details
assert.NotNil(t, result.EvaluationDetails)
assert.Equal(t, tt.context.Action, result.EvaluationDetails.Action)
assert.Equal(t, tt.context.Resource, result.EvaluationDetails.Resource)
})
}
}
// TestConditionEvaluation tests policy conditions
func TestConditionEvaluation(t *testing.T) {
engine := setupTestPolicyEngine(t)
// Policy with IP address condition
conditionalPolicy := &PolicyDocument{
Version: "2012-10-17",
Statement: []Statement{
{
Sid: "AllowFromOfficeIP",
Effect: "Allow",
Action: []string{"s3:*"},
Resource: []string{"arn:aws:s3:::*"},
Condition: map[string]map[string]interface{}{
"IpAddress": {
"aws:SourceIp": []string{"192.168.1.0/24", "10.0.0.0/8"},
},
},
},
},
}
err := engine.AddPolicy("", "ip-conditional", conditionalPolicy)
require.NoError(t, err)
tests := []struct {
name string
context *EvaluationContext
want Effect
}{
{
name: "allow from office IP",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::mybucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "192.168.1.100",
},
},
want: EffectAllow,
},
{
name: "deny from external IP",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:GetObject",
Resource: "arn:aws:s3:::mybucket/file.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "8.8.8.8",
},
},
want: EffectDeny,
},
{
name: "allow from internal IP",
context: &EvaluationContext{
Principal: "user:alice",
Action: "s3:PutObject",
Resource: "arn:aws:s3:::mybucket/newfile.txt",
RequestContext: map[string]interface{}{
"aws:SourceIp": "10.1.2.3",
},
},
want: EffectAllow,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := engine.Evaluate(context.Background(), "", tt.context, []string{"ip-conditional"})
assert.NoError(t, err)
assert.Equal(t, tt.want, result.Effect)
})
}
}
// TestResourceMatching tests resource ARN matching
func TestResourceMatching(t *testing.T) {
tests := []struct {
name string
policyResource string
requestResource string
want bool
}{
{
name: "exact match",
policyResource: "arn:aws:s3:::mybucket/file.txt",
requestResource: "arn:aws:s3:::mybucket/file.txt",
want: true,
},
{
name: "wildcard match",
policyResource: "arn:aws:s3:::mybucket/*",
requestResource: "arn:aws:s3:::mybucket/folder/file.txt",
want: true,
},
{
name: "bucket wildcard",
policyResource: "arn:aws:s3:::*",
requestResource: "arn:aws:s3:::anybucket/file.txt",
want: true,
},
{
name: "no match different bucket",
policyResource: "arn:aws:s3:::mybucket/*",
requestResource: "arn:aws:s3:::otherbucket/file.txt",
want: false,
},
{
name: "prefix match",
policyResource: "arn:aws:s3:::mybucket/documents/*",
requestResource: "arn:aws:s3:::mybucket/documents/secret.txt",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := matchResource(tt.policyResource, tt.requestResource)
assert.Equal(t, tt.want, result)
})
}
}
// TestActionMatching tests action pattern matching
func TestActionMatching(t *testing.T) {
tests := []struct {
name string
policyAction string
requestAction string
want bool
}{
{
name: "exact match",
policyAction: "s3:GetObject",
requestAction: "s3:GetObject",
want: true,
},
{
name: "wildcard service",
policyAction: "s3:*",
requestAction: "s3:PutObject",
want: true,
},
{
name: "wildcard all",
policyAction: "*",
requestAction: "filer:CreateEntry",
want: true,
},
{
name: "prefix match",
policyAction: "s3:Get*",
requestAction: "s3:GetObject",
want: true,
},
{
name: "no match different service",
policyAction: "s3:GetObject",
requestAction: "filer:GetEntry",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := matchAction(tt.policyAction, tt.requestAction)
assert.Equal(t, tt.want, result)
})
}
}
// Helper function to set up test policy engine
func setupTestPolicyEngine(t *testing.T) *PolicyEngine {
engine := NewPolicyEngine()
config := &PolicyEngineConfig{
DefaultEffect: "Deny",
StoreType: "memory",
}
err := engine.Initialize(config)
require.NoError(t, err)
return engine
}