Files
versitygw/iamapi/storage/common.go
T
niksis02 26a54b33e9 feat: add IAM user tagging actions
Adds `TagUser`, `UntagUser` and `ListUserTags` to the standalone IAM service, backed by both the internal and Vault storers. Tag keys are matched case-insensitively but stored case-preserving, TagUser merges into the user's existing tags and rejects duplicate keys, UntagUser removal is idempotent, and ListUserTags is sorted by key and paginated. The per-request member count and the per-user tag total are enforced as separate quotas.

All three actions are authorized against the target user's ARN, and TagUser and UntagUser populate aws:RequestTag/<key> and aws:TagKeys respectively, so a tag-scoped policy Condition governs which tags a caller may set or remove.

The WebGUI gains a Tags section in the IAM user manage view, with an editor that applies a whole edited tag set as a single UntagUser and TagUser pair.

Also corrects two error shapes that never matched AWS: a half-supplied tag member now reports a ValidationError naming the member field instead of MissingParameter, and the maxItems bound check reports separate lower- and upper-bound errors across every IAM list action.
2026-08-28 00:49:20 +04:00

273 lines
7.3 KiB
Go

// 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 storage
import (
"errors"
"slices"
"strings"
"time"
"github.com/versity/versitygw/iamapi/iamerr"
"github.com/versity/versitygw/iamapi/types"
)
// MaxAccessKeysPerUser is the maximum number of access keys a single IAM
// user may hold at once, matching the AWS IAM quota.
const MaxAccessKeysPerUser = 2
// MaxTagsPerUser is the maximum number of tags a single IAM user may carry
// at once, matching the AWS IAM quota.
const MaxTagsPerUser = 50
// MaxInlinePolicyBytesPerUser is the maximum aggregate size, in bytes, of
// all of a single IAM user's inline policy documents combined
const MaxInlinePolicyBytesPerUser = 2048
// MaxInlinePolicyBytesPerRole is the maximum aggregate size, in bytes, of
// all of a single IAM role's inline policy documents combined
const MaxInlinePolicyBytesPerRole = 10240
// MaxClientIDsPerOIDCProvider is the maximum number of client IDs a single
// OIDC provider may hold at once
const MaxClientIDsPerOIDCProvider = 100
// MaxOIDCProvidersPerAccount is the maximum number of OIDC providers a
// single account may hold
const MaxOIDCProvidersPerAccount = 100
// MaxActiveSessionsPerRole bounds how many currently-unexpired
// AssumeRoleWithWebIdentity sessions a single role may have at once.
// AWS manages and rate-limits STS as a hosted service with no
// customer-visible equivalent quota to match for fidelity; this exists
// purely as local resource protection, since without it a single valid
// federated token can be replayed indefinitely to grow the session
// store — every InternalStore rewrite, or Vault KV path/metadata entry —
// without bound. Chosen generously enough to not constrain any legitimate
// workload's concurrent session count.
//
// A var, not a const, so tests can temporarily lower it rather than paying
// the cost of actually creating 1000 sessions to exercise the cap.
var MaxActiveSessionsPerRole = 1000
var (
ErrUserIDAlreadyExists = errors.New("iamapi: user id already exists")
ErrAccessKeyIDAlreadyExists = errors.New("iamapi: access key id already exists")
ErrRoleIDAlreadyExists = errors.New("iamapi: role id already exists")
// ErrSessionNotFound is returned by GetSession when accessKeyID names no
// session, or names one whose Expiration has already passed.
ErrSessionNotFound = errors.New("iamapi: session not found")
)
type ListUsersInput struct {
PathPrefix string
Marker string
MaxItems int32
}
type ListUsersOutput struct {
Users []types.User
IsTruncated bool
Marker string
}
type ListUserTagsInput struct {
UserName string
Marker string
MaxItems int32
}
type ListUserTagsOutput struct {
Tags []types.Tag
IsTruncated bool
Marker string
}
type UpdateUserInput struct {
UserName string
NewPath string
NewUserName string
NewArn string
}
type CreateAccessKeyInput struct {
UserName string
AccessKeyID string
SecretAccessKey string
Status string
CreateDate time.Time
}
type UpdateAccessKeyInput struct {
UserName string
AccessKeyID string
Status string
}
type ListAccessKeysInput struct {
UserName string
Marker string
MaxItems int32
}
type ListAccessKeysOutput struct {
AccessKeys []types.AccessKeyMetadata
IsTruncated bool
Marker string
}
type GetAccessKeyLastUsedOutput struct {
UserName string
LastUsedDate time.Time
ServiceName string
Region string
}
type PutUserPolicyInput struct {
UserName string
PolicyName string
PolicyDocument string
}
type ListUserPoliciesInput struct {
UserName string
Marker string
MaxItems int32
}
type ListUserPoliciesOutput struct {
PolicyNames []string
IsTruncated bool
Marker string
}
type ListRolesInput struct {
PathPrefix string
Marker string
MaxItems int32
}
type ListRolesOutput struct {
Roles []types.Role
IsTruncated bool
Marker string
}
type UpdateAssumeRolePolicyInput struct {
RoleName string
PolicyDocument string
}
type PutRolePolicyInput struct {
RoleName string
PolicyName string
PolicyDocument string
}
type ListRolePoliciesInput struct {
RoleName string
Marker string
MaxItems int32
}
type ListRolePoliciesOutput struct {
PolicyNames []string
IsTruncated bool
Marker string
}
type ListOIDCProvidersOutput struct {
Providers []types.OpenIDConnectProviderListEntry
}
// mergeTags applies TagUser's merge semantics to existing: an incoming tag
// replaces the existing tag whose key matches case-insensitively — taking
// over its position and its key's casing — and any remaining incoming tag
// is appended in the order supplied. AWS caps the merged total, not the
// request, so replacing a tag on a user already at the cap is allowed.
func mergeTags(existing, incoming []types.Tag) ([]types.Tag, error) {
merged := slices.Clone(existing)
for _, tag := range incoming {
if idx := indexOfTagKey(merged, tag.Key); idx >= 0 {
merged[idx] = tag
continue
}
if len(merged) >= MaxTagsPerUser {
return nil, iamerr.GetAPIError(iamerr.ErrTagLimitExceeded)
}
merged = append(merged, tag)
}
return merged, nil
}
// removeTags applies UntagUser's removal semantics to existing: every tag
// whose key case-insensitively matches one of tagKeys is dropped, and a key
// naming no existing tag is ignored rather than reported.
func removeTags(existing []types.Tag, tagKeys []string) []types.Tag {
return slices.DeleteFunc(slices.Clone(existing), func(tag types.Tag) bool {
return slices.ContainsFunc(tagKeys, func(key string) bool {
return strings.EqualFold(key, tag.Key)
})
})
}
func indexOfTagKey(tags []types.Tag, key string) int {
return slices.IndexFunc(tags, func(tag types.Tag) bool {
return strings.EqualFold(tag.Key, key)
})
}
// paginateTags sorts tags by key and applies input's Marker/MaxItems window.
// AWS's own ListUserTags returns tags in an unspecified order (its docs
// claim sorted by key; live responses are not), so this sorts by key: a
// stable order is what makes a Marker meaningful, and it's the order the
// documentation promises.
func paginateTags(tags []types.Tag, input ListUserTagsInput) *ListUserTagsOutput {
sorted := slices.Clone(tags)
slices.SortFunc(sorted, func(a, b types.Tag) int {
return strings.Compare(a.Key, b.Key)
})
if input.Marker != "" {
start := len(sorted)
if idx := indexOfTagKey(sorted, input.Marker); idx >= 0 {
start = idx + 1
}
sorted = sorted[start:]
}
limit := len(sorted)
if input.MaxItems > 0 && int(input.MaxItems) < limit {
limit = int(input.MaxItems)
}
out := &ListUserTagsOutput{Tags: sorted[:limit]}
if limit < len(sorted) {
out.IsTruncated = true
out.Marker = out.Tags[limit-1].Key
}
return out
}
func unwrapAPIError(err error) error {
var apiErr iamerr.APIError
if errors.As(err, &apiErr) {
return apiErr
}
return err
}