Files
versitygw/iamapi/internal/iamutil/access_key.go
T
niksis02 4756b4d236 feat: add STS web identity federation, IAM policy Condition support, and access control enforcement
Implements the `AssumeRoleWithWebIdentity` and `GetCallerIdentity` STS actions, letting callers exchange an external OIDC token for temporary credentials scoped to an IAM role. Token handling covers JWT claim parsing, issuer/audience resolution (including `azp` override semantics), JWKS fetching and caching with `singleflight`-deduplicated refresh, and rate-limited forced refresh on unrecognized `kid` values. OIDC provider thumbprint fetching now performs a real TLS handshake verified against the system trust store and the provider hostname (previously `InsecureSkipVerify`), since the observed certificate is persisted as a long-lived trust anchor rather than used once and discarded; all discovery-document and JWKS fetches go through an SSRF-safe HTTP client with bounded redirects and response size.

Adds policy `Condition` block evaluation, supporting `String`, `Numeric`, `Date`, `Bool`, `BinaryEquals`, and `IpAddress` operators along with their `IfExists`/`Not` variants and `ForAllValues`/`ForAnyValues` set qualifiers, plus policy variable substitution (e.g. `${aws:username}`) in supported operators. Adds identity-based inline policy evaluation and a new IAM authorization middleware that authorizes each request against action, resource, and condition context together, applying the session-policy-intersects-role-policy semantics for assumed-role sessions.

Adds a new debug logger `--log-level` flag (`silent`/`debug`/`unsafe`), along with a tree-based XML masker that redacts secrets and tokens at the property level in logged request/response bodies instead of skipping the whole body. The old `--debug/VGW_DEBUG` flag is kept as a deprecated alias for `--log-level=debug`, printing a console warning that points users at `--log-level` for finer-grained control.

Fixes a Vault storage bug where CAS (check-and-set) writes always read the current document version as 0 because `kvVersion` asserted metadata as `float64` while the Vault client actually returns `json.Number`, causing every write past the first to be rejected as a concurrent modification. Also adds a constant-time `SecureCompare` for signature/token comparisons in sigv4 auth.

Adds an integration test suite (`iam_access_control.go`) covering IAM access control across user, role, and session identities.
2026-08-15 17:49:00 +04:00

129 lines
4.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 iamutil
import (
"crypto/rand"
"encoding/base64"
"regexp"
"strings"
"github.com/versity/versitygw/debuglogger"
"github.com/versity/versitygw/iamapi/iamerr"
)
const (
AccessKeyStatusActive = "Active"
AccessKeyStatusInactive = "Inactive"
accessKeyIDPrefix = "AKIA"
accessKeyIDRandomLen = 17
minAccessKeyIDLen = 16
maxAccessKeyIDLen = 128
secretAccessKeyBytes = 30
// tempAccessKeyIDPrefix marks temporary credentials minted by
// AssumeRoleWithWebIdentity, matching AWS's ASIA… convention that
// distinguishes them from long-term AKIA… access keys.
tempAccessKeyIDPrefix = "ASIA"
sessionTokenBytes = 128
)
var accessKeyIDPattern = regexp.MustCompile(`^[\w]+$`)
// GenerateAccessKeyID returns a new cryptographically random IAM access key
// id in the AKIA… format.
func GenerateAccessKeyID() (string, error) {
id, err := generateAWSID(accessKeyIDPrefix, accessKeyIDRandomLen)
if err != nil {
debuglogger.Logf("failed to generate IAM access key id: %v", err)
return "", err
}
return id, nil
}
// GenerateSecretAccessKey returns a new cryptographically random 40 character
// secret access key.
func GenerateSecretAccessKey() (string, error) {
b := make([]byte, secretAccessKeyBytes)
if _, err := rand.Read(b); err != nil {
debuglogger.Logf("failed to generate IAM secret access key: %v", err)
return "", err
}
return base64.StdEncoding.EncodeToString(b), nil
}
// GenerateTempAccessKeyID returns a new cryptographically random temporary
// access key id in the ASIA… format, for credentials minted by
// AssumeRoleWithWebIdentity.
func GenerateTempAccessKeyID() (string, error) {
id, err := generateAWSID(tempAccessKeyIDPrefix, accessKeyIDRandomLen)
if err != nil {
debuglogger.Logf("failed to generate temporary IAM access key id: %v", err)
return "", err
}
return id, nil
}
// GenerateSessionToken returns a new cryptographically random opaque
// session token for temporary credentials. Unlike AWS's own STS, whose
// session token self-encodes the session (so any STS host can validate it
// without shared state), this gateway looks the token up in its own
// session store, so an opaque random value is sufficient.
func GenerateSessionToken() (string, error) {
b := make([]byte, sessionTokenBytes)
if _, err := rand.Read(b); err != nil {
debuglogger.Logf("failed to generate IAM session token: %v", err)
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// IsTempAccessKeyID reports whether accessKeyID has the ASIA… prefix used
// for temporary credentials minted by AssumeRoleWithWebIdentity, as opposed
// to a long-term AKIA… access key.
func IsTempAccessKeyID(accessKeyID string) bool {
return strings.HasPrefix(accessKeyID, tempAccessKeyIDPrefix)
}
// ValidateAccessKeyID checks that accessKeyID fits within the allowed length
// range and character set.
func ValidateAccessKeyID(accessKeyID string) error {
if len(accessKeyID) < minAccessKeyIDLen {
debuglogger.Logf("IAM access key id too short: value=%q", accessKeyID)
return iamerr.AccessKeyIDTooShort(minAccessKeyIDLen)
}
if len(accessKeyID) > maxAccessKeyIDLen {
debuglogger.Logf("IAM access key id too long: value=%q", accessKeyID)
return iamerr.AccessKeyIDTooLong(maxAccessKeyIDLen)
}
if !accessKeyIDPattern.MatchString(accessKeyID) {
debuglogger.Logf("invalid IAM access key id characters: value=%q", accessKeyID)
return iamerr.GetAPIError(iamerr.ErrInvalidAccessKeyIDChars)
}
return nil
}
// ValidateAccessKeyStatus checks that status is either Active or Inactive.
func ValidateAccessKeyStatus(status string) error {
if status != AccessKeyStatusActive && status != AccessKeyStatusInactive {
debuglogger.Logf("invalid IAM access key status: %q", status)
return iamerr.InvalidAccessKeyStatus(status)
}
return nil
}