mirror of
https://github.com/versity/versitygw.git
synced 2026-09-13 03:24:16 +00:00
feat: add AWS-compatible standalone IAM service
Closes #1640 Add a standalone AWS IAM Query API implementation for managing IAM users through standard AWS SDKs and the AWS CLI. Server usage Start the IAM server with internal file-backed storage: mkdir -p /tmp/versitygw-iam ./versitygw --port 127.0.0.1:7070 --access user --secret pass iam --dir /tmp/versitygw-iam Start the IAM server with Vault KV v2 storage using AppRole: VGW_IAM_VAULT_ROLE_SECRET=<role-secret> ./versitygw --port 127.0.0.1:7070 --access user --secret pass iam --vault-endpoint-url http://127.0.0.1:8200 --vault-auth-method approle --vault-role-id <role-id> --vault-mount-path kv --vault-secret-storage-path iam Vault authentication also supports root tokens, separate authentication and secret-storage namespaces, custom mount paths, server certificate validation, and mutual TLS client certificates. Configure the AWS CLI credentials used by the IAM server: export AWS_ACCESS_KEY_ID=user export AWS_SECRET_ACCESS_KEY=pass export AWS_DEFAULT_REGION=us-east-1 Implemented IAM actions CreateUser creates an IAM user with an AWS-compatible ARN, generated AIDA user ID, creation timestamp, optional path, and tags. It validates usernames, paths, tag limits, reserved tag prefixes, duplicate tag keys, and existing users. aws --endpoint-url http://127.0.0.1:7070 iam create-user --user-name bob aws --endpoint-url http://127.0.0.1:7070 iam create-user --user-name bob --path /engineering/ --tags Key=team,Value=storage GetUser returns a stored user or the root identity when requested without a username through the IAM Query API. aws --endpoint-url http://127.0.0.1:7070 iam get-user --user-name bob ListUsers returns users in deterministic username order and supports path filtering, marker-based pagination, and MaxItems limits. aws --endpoint-url http://127.0.0.1:7070 iam list-users aws --endpoint-url http://127.0.0.1:7070 iam list-users --path-prefix /engineering/ --max-items 100 UpdateUser updates the username and/or path, recalculates the user ARN, and rejects conflicts with existing users. aws --endpoint-url http://127.0.0.1:7070 iam update-user --user-name bob --new-user-name robert --new-path /platform/ DeleteUser permanently removes an IAM user and returns AWS-compatible errors for missing users. aws --endpoint-url http://127.0.0.1:7070 iam delete-user --user-name robert IAM protocol and authentication - Support the AWS IAM Query protocol version 2010-05-08 over GET and POST form requests. - Return AWS-compatible XML responses, error documents, status codes, request IDs, user metadata, and pagination fields. - Authenticate root credentials with AWS Signature Version 4 for the IAM service in us-east-1. - Support both Authorization-header and query-string SigV4 authentication. - Validate credential scope, signed headers, timestamps, clock skew, content length, signatures, and unsupported signature or session-token modes. - Add IAM-specific validation and error mapping for malformed requests, invalid actions, duplicate entities, missing users, throttling, and internal failures. Storage implementations - Add an internal JSON-backed store using iam.json and iam.json.backup with atomic temporary-file replacement, concurrent access protection, stable ordering, pagination, and persistence across restarts. - Add a Vault KV v2 store with one secret per user, CAS-based duplicate protection, permanent deletion, AppRole reauthentication, namespace support, configurable authentication and KV mounts, root-token authentication, and TLS/mTLS configuration. - Introduce a common Storer interface and require exactly one storage backend to be configured. Server and embedding support - Register the new `versitygw iam` command with environment-variable and CLI configuration for both storage backends. - Add `embedgw.RunIAMAPI` and `IAMConfig` for embedding the IAM service in Go applications. Gateway-level internal packages - Add `internal/iamstore` as a reusable generic file-backed IAM persistence engine and migrate the existing gateway internal IAM service to it. - Add `internal/sigv4auth` for shared SigV4 header and presigned-query parsing, canonical request generation, signature verification, and structured authentication errors. - Refactor the S3 authentication paths to use the shared SigV4 implementation while preserving S3-specific error responses. - Add `internal/httpctx` for shared Fiber context keys and AWS-style request ID handling. - Add `internal/routekit` for shared query, form, and header route matchers. - Add `internal/netutil` for reusable certificate storage, hostname-aware listeners, multi-address serving, TLS listeners, and UNIX socket handling. - Update the custom SigV4 signer to honor an explicitly supplied signed-header list so unrelated headers do not alter IAM signatures. Testing and CI - Add AWS IAM SDK-based integration coverage for all supported user actions, header authentication, query authentication, validation, errors, filtering, and pagination. - Split standalone IAM tests into `versitygw test iam` and retain existing gateway IAM tests under `versitygw test gw-iam`. - Add unit coverage for controllers, authentication, routing, storage, embedding, listeners, request matching, persistence, and signing behavior. - Add `runiamtests.sh` to exercise internal storage over HTTP and HTTPS plus Vault storage through AppRole. - Add a dedicated IAM functional-test workflow with a Vault service and merged runtime coverage reporting. - Include the IAM test runner in shellcheck and add the AWS IAM SDK dependency.
This commit is contained in:
@@ -0,0 +1,626 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
awsv4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
vgwv4 "github.com/versity/versitygw/aws/signer/v4"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
"github.com/versity/versitygw/internal/sigv4auth"
|
||||
)
|
||||
|
||||
var testRoot = RootCredentials{
|
||||
Access: "AKID",
|
||||
Secret: "SECRET",
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthAcceptsSignedGet(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", resp.StatusCode, http.StatusOK, readBody(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthAcceptsSignedPost(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
body := []byte("Action=CreateUser&UserName=test-user&Version=2010-05-08")
|
||||
req := signedIAMRequest(t, http.MethodPost, "http://example.com/", body, testRoot.Secret)
|
||||
req.Header.Set("Content-Type", fiber.MIMEApplicationForm)
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", resp.StatusCode, http.StatusOK, readBody(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthAcceptsUnsignedNonHostHeaders(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
req.Header.Set("X-Amz-Copy-Source", "source-bucket/source-key")
|
||||
req.Header.Set("X-Amz-Content-Sha256", "invalid_sha256")
|
||||
req.Header.Set("X-Amz-Tagging", "key=value")
|
||||
req.Header.Set("X-Custom-Header", "value")
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", resp.StatusCode, http.StatusOK, readBody(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsUnsignedHost(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
authorization := req.Header.Get("Authorization")
|
||||
withoutHost := strings.Replace(authorization, "SignedHeaders=host;", "SignedHeaders=", 1)
|
||||
if withoutHost == authorization {
|
||||
t.Fatalf("Authorization does not contain a signed host header: %q", authorization)
|
||||
}
|
||||
req.Header.Set("Authorization", withoutHost)
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrMissingHostSignedHeader)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthAcceptsQuerySignedGet(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", resp.StatusCode, http.StatusOK, readBody(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsMissingQueryParameters(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
parameter string
|
||||
want iamerr.Error
|
||||
}{
|
||||
{
|
||||
name: "algorithm",
|
||||
parameter: sigv4auth.QueryAlgorithm,
|
||||
want: iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken),
|
||||
},
|
||||
{
|
||||
name: "credential",
|
||||
parameter: sigv4auth.QueryCredential,
|
||||
want: iamerr.IncompleteSignatureMissingQueryParameter(sigv4auth.QueryCredential),
|
||||
},
|
||||
{
|
||||
name: "date",
|
||||
parameter: sigv4auth.QueryDate,
|
||||
want: iamerr.IncompleteSignatureMissingQueryParameter(sigv4auth.QueryDate),
|
||||
},
|
||||
{
|
||||
name: "signed headers",
|
||||
parameter: sigv4auth.QuerySignedHeaders,
|
||||
want: iamerr.IncompleteSignatureMissingQueryParameter(sigv4auth.QuerySignedHeaders),
|
||||
},
|
||||
{
|
||||
name: "signature",
|
||||
parameter: sigv4auth.QuerySignature,
|
||||
want: iamerr.IncompleteSignatureMissingQueryParameter(sigv4auth.QuerySignature),
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
query := req.URL.Query()
|
||||
query.Del(testCase.parameter)
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := testCase.want
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsUnsupportedQueryAlgorithm(t *testing.T) {
|
||||
for _, algorithm := range []string{"AWS4-SHA256", sigv4auth.AlgorithmECDSAP256SHA256} {
|
||||
t.Run(algorithm, func(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
query := req.URL.Query()
|
||||
query.Set(sigv4auth.QueryAlgorithm, algorithm)
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrUnsupportedQueryAlgorithm)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsInvalidQueryDate(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
const invalidDate = "03032006"
|
||||
query := req.URL.Query()
|
||||
query.Set(sigv4auth.QueryDate, invalidDate)
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.IncompleteSignatureInvalidXAmzDate(invalidDate)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsQueryCredentialDateMismatch(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
query := req.URL.Query()
|
||||
credential := strings.Split(query.Get(sigv4auth.QueryCredential), "/")
|
||||
credential[1] = "20000101"
|
||||
query.Set(sigv4auth.QueryCredential, strings.Join(credential, "/"))
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthQueryCredentialParsingMatchesHeaderAuth(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
credential string
|
||||
want iamerr.Error
|
||||
}{
|
||||
{
|
||||
name: "malformed",
|
||||
credential: "access/hello/world",
|
||||
want: iamerr.IncompleteSignatureMalformedCredential("access/hello/world"),
|
||||
},
|
||||
{
|
||||
name: "invalid terminal",
|
||||
credential: "access/20260627/us-east-1/iam/aws_request",
|
||||
want: iamerr.GetAPIError(iamerr.ErrInvalidTerminal),
|
||||
},
|
||||
{
|
||||
name: "incorrect service",
|
||||
credential: "access/20260627/us-east-1/ec2/aws4_request",
|
||||
want: iamerr.GetAPIError(iamerr.ErrIncorrectService),
|
||||
},
|
||||
{
|
||||
name: "invalid credential date",
|
||||
credential: "access/3223423234/us-east-1/iam/aws4_request",
|
||||
want: iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate),
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
query := req.URL.Query()
|
||||
query.Set(sigv4auth.QueryCredential, testCase.credential)
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := testCase.want
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsQuerySignatureMismatch(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret+"-wrong", iammiddleware.SigningRegion, time.Now().UTC())
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "SignatureDoesNotMatch", "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsUnsignedQueryParameter(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
query := req.URL.Query()
|
||||
query.Set("ExtraParam", "value")
|
||||
req.URL.RawQuery = query.Encode()
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrSignatureDoesNotMatch)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsQueryWrongCredentialRegion(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, "us-west-2", time.Now().UTC())
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "SignatureDoesNotMatch", "Credential should be scoped to a valid region. ")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsMissingAuthorization(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/?Action=ListUsers&Version=2010-05-08", nil))
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "MissingAuthenticationToken", "Request is missing Authentication Token")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsUnrecognizedAuthorizationHeaders(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
authorization string
|
||||
}{
|
||||
{
|
||||
name: "invalid header",
|
||||
authorization: "invalid_header",
|
||||
},
|
||||
{
|
||||
name: "unsupported signature version",
|
||||
authorization: "AWS2-HMAC-SHA1 Credential=AKID/20260701/us-east-1/iam/aws4_request,SignedHeaders=host;x-amz-date,Signature=signature",
|
||||
},
|
||||
{
|
||||
name: "ECDSA algorithm",
|
||||
authorization: sigv4auth.AlgorithmECDSAP256SHA256 + " Credential=AKID/20260701/us-east-1/iam/aws4_request,SignedHeaders=host;x-amz-date,Signature=signature",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
req.Header.Set("Authorization", testCase.authorization)
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsMalformedAuthorizationComponent(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
const component = "SignedHeaders-Content-Length"
|
||||
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260701/us-east-1/iam/aws4_request,"+component+",Signature=signature")
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.IncompleteSignatureMalformedComponent(component)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsMissingDate(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
authorization := req.Header.Get("Authorization")
|
||||
req.Header.Del("X-Amz-Date")
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.IncompleteSignatureMissingDate(authorization)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsInvalidDate(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
const invalidDate = "03032006"
|
||||
req.Header.Set("X-Amz-Date", invalidDate)
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.IncompleteSignatureInvalidXAmzDate(invalidDate)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsSignatureMismatch(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret+"-wrong")
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "SignatureDoesNotMatch", "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsWrongCredentialRegion(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequestWithRegion(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret, "us-west-2")
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "SignatureDoesNotMatch", "Credential should be scoped to a valid region. ")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsCredentialDateMismatch(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
authorization := req.Header.Get("Authorization")
|
||||
regExp := regexp.MustCompile("Credential=[^,]+,")
|
||||
req.Header.Set("Authorization", regExp.ReplaceAllString(authorization, "Credential=access/20000101/us-east-1/iam/aws4_request,"))
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsMalformedCredential(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
const credential = "access/32234/us-east-1/iam/extra/things"
|
||||
authHdr := req.Header.Get("Authorization")
|
||||
regExp := regexp.MustCompile("Credential=[^,]+,")
|
||||
req.Header.Set("Authorization", regExp.ReplaceAllString(authHdr, "Credential="+credential+","))
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
requireIAMError(t, resp, http.StatusBadRequest, "Sender", "IncompleteSignature", "Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, got '"+credential+"'")
|
||||
}
|
||||
|
||||
func TestVerifyIAMAuthRejectsInvalidCredentialTerminal(t *testing.T) {
|
||||
app := newIAMAuthTestApp(t)
|
||||
req := signedIAMRequest(t, http.MethodGet, "http://example.com/?Action=ListUsers&Version=2010-05-08", nil, testRoot.Secret)
|
||||
authHdr := req.Header.Get("Authorization")
|
||||
regExp := regexp.MustCompile("Credential=[^,]+,")
|
||||
req.Header.Set("Authorization", regExp.ReplaceAllString(authHdr, "Credential=access/32234/us-east-1/iam/aws_request,"))
|
||||
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
|
||||
want := iamerr.GetAPIError(iamerr.ErrInvalidTerminal)
|
||||
requireIAMError(t, resp, want.HTTPStatusCode, string(want.Type), want.Code, want.Message)
|
||||
}
|
||||
|
||||
func TestValidateDateAtRejectsFutureDate(t *testing.T) {
|
||||
serverTime := time.Date(2026, time.June, 27, 20, 18, 14, 0, time.UTC)
|
||||
requestTime := time.Date(2026, time.July, 2, 20, 18, 13, 0, time.UTC)
|
||||
|
||||
err := iammiddleware.ValidateDateAt(requestTime, serverTime)
|
||||
want := iamerr.SignatureDoesNotMatchNotYetCurrent(requestTime, serverTime, 15*time.Minute)
|
||||
if err != want {
|
||||
t.Fatalf("ValidateDateAt() error = %#v, want %#v", err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateDateAtRejectsPastDate(t *testing.T) {
|
||||
serverTime := time.Date(2026, time.June, 27, 20, 19, 55, 0, time.UTC)
|
||||
requestTime := time.Date(2026, time.June, 22, 20, 19, 54, 0, time.UTC)
|
||||
|
||||
err := iammiddleware.ValidateDateAt(requestTime, serverTime)
|
||||
want := iamerr.SignatureDoesNotMatchExpired(requestTime, serverTime, 15*time.Minute)
|
||||
if err != want {
|
||||
t.Fatalf("ValidateDateAt() error = %#v, want %#v", err, want)
|
||||
}
|
||||
}
|
||||
|
||||
func newIAMAuthTestApp(t *testing.T) *fiber.App {
|
||||
t.Helper()
|
||||
|
||||
app := fiber.New(fiber.Config{ErrorHandler: iammiddleware.GlobalErrorHandler})
|
||||
app.All("/", ProcessHandlers(
|
||||
func(ctx fiber.Ctx) (*Response, error) {
|
||||
return &Response{Status: http.StatusOK}, nil
|
||||
},
|
||||
iammiddleware.VerifyIAMAuth(&testRoot),
|
||||
))
|
||||
return app
|
||||
}
|
||||
|
||||
func signedIAMRequest(t *testing.T, method, target string, body []byte, secret string) *http.Request {
|
||||
t.Helper()
|
||||
|
||||
return signedIAMRequestWithRegion(t, method, target, body, secret, iammiddleware.SigningRegion)
|
||||
}
|
||||
|
||||
func signedIAMRequestWithRegion(t *testing.T, method, target string, body []byte, secret, region string) *http.Request {
|
||||
t.Helper()
|
||||
|
||||
req := httptest.NewRequest(method, target, bytes.NewReader(body))
|
||||
hash := sha256.Sum256(body)
|
||||
payloadHash := hex.EncodeToString(hash[:])
|
||||
|
||||
signer := awsv4.NewSigner()
|
||||
if err := signer.SignHTTP(
|
||||
context.Background(),
|
||||
aws.Credentials{AccessKeyID: testRoot.Access, SecretAccessKey: secret},
|
||||
req,
|
||||
payloadHash,
|
||||
"iam",
|
||||
region,
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatalf("sign request: %v", err)
|
||||
}
|
||||
|
||||
return req
|
||||
}
|
||||
|
||||
func querySignedIAMRequest(t *testing.T, method, target string, body []byte, secret, region string, signingTime time.Time) *http.Request {
|
||||
t.Helper()
|
||||
|
||||
req := httptest.NewRequest(method, target, bytes.NewReader(body))
|
||||
|
||||
hash := sha256.Sum256(body)
|
||||
payloadHash := hex.EncodeToString(hash[:])
|
||||
|
||||
signer := vgwv4.NewSigner()
|
||||
signedURL, signedHeaders, _, err := signer.PresignHTTP(
|
||||
context.Background(),
|
||||
aws.Credentials{AccessKeyID: testRoot.Access, SecretAccessKey: secret},
|
||||
req,
|
||||
payloadHash,
|
||||
"iam",
|
||||
region,
|
||||
signingTime,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("presign request: %v", err)
|
||||
}
|
||||
|
||||
signedReq := httptest.NewRequest(method, signedURL, bytes.NewReader(body))
|
||||
for key, values := range signedHeaders {
|
||||
for _, value := range values {
|
||||
signedReq.Header.Add(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
return signedReq
|
||||
}
|
||||
|
||||
func requireIAMError(t *testing.T, resp *http.Response, status int, errType, code, message string) {
|
||||
t.Helper()
|
||||
|
||||
body := readBody(t, resp)
|
||||
if resp.StatusCode != status {
|
||||
t.Fatalf("status = %d, want %d; body=%s", resp.StatusCode, status, body)
|
||||
}
|
||||
|
||||
var errResp struct {
|
||||
XMLName xml.Name `xml:"ErrorResponse"`
|
||||
Error struct {
|
||||
Type string
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
RequestID string `xml:"RequestId"`
|
||||
}
|
||||
if err := xml.Unmarshal([]byte(body), &errResp); err != nil {
|
||||
t.Fatalf("unmarshal IAM error: %v\n%s", err, body)
|
||||
}
|
||||
|
||||
wantNamespace := iamerr.Namespace
|
||||
if code == "InvalidAction" {
|
||||
wantNamespace = iamerr.AWSFaultNamespace
|
||||
}
|
||||
if errResp.XMLName.Space != wantNamespace {
|
||||
t.Fatalf("namespace = %q, want %q", errResp.XMLName.Space, wantNamespace)
|
||||
}
|
||||
if errResp.Error.Type != errType || errResp.Error.Code != code || errResp.Error.Message != message {
|
||||
t.Fatalf("error = %#v, want type=%q code=%q message=%q", errResp.Error, errType, code, message)
|
||||
}
|
||||
if errResp.RequestID == "" {
|
||||
t.Fatal("missing RequestId")
|
||||
}
|
||||
}
|
||||
|
||||
func readBody(t *testing.T, resp *http.Response) string {
|
||||
t.Helper()
|
||||
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/internal/iamutil"
|
||||
"github.com/versity/versitygw/iamapi/storage"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
type IAMApiController struct {
|
||||
store storage.Storer
|
||||
}
|
||||
|
||||
func NewController(store storage.Storer) IAMApiController {
|
||||
return IAMApiController{store: store}
|
||||
}
|
||||
|
||||
func (c IAMApiController) CreateUser(ctx fiber.Ctx) (*Response, error) {
|
||||
userName, ok := iamutil.RequestParam(ctx, "UserName")
|
||||
if !ok {
|
||||
debuglogger.Logf("missing required CreateUser parameter: UserName")
|
||||
return nil, iamerr.GetAPIError(iamerr.ErrMissingUserNameValue)
|
||||
}
|
||||
if err := iamutil.ValidateUserName("userName", userName, iamutil.MaxUserNameLen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
path, ok := iamutil.RequestParam(ctx, "Path")
|
||||
if !ok || path == "" {
|
||||
path = iamutil.DefaultUserPath
|
||||
}
|
||||
if err := iamutil.ValidatePath("path", path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tags, err := iamutil.ParseTags(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for range 3 {
|
||||
userID, err := iamutil.GenerateUserID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user := types.User{
|
||||
Path: path,
|
||||
UserName: userName,
|
||||
UserID: userID,
|
||||
Arn: iamutil.BuildUserArn(iamutil.DefaultAccountID, path, userName),
|
||||
CreateDate: time.Now().UTC().Truncate(time.Second),
|
||||
Tags: tags,
|
||||
}
|
||||
|
||||
stored, err := c.store.CreateUser(ctx.Context(), user)
|
||||
if errors.Is(err, storage.ErrUserIDAlreadyExists) {
|
||||
debuglogger.Logf("IAM user ID collision while creating user %q: %v", userName, err)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to create IAM user %q: %v", userName, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Response{Data: &types.CreateUserResponse{
|
||||
Result: types.CreateUserResult{User: *stored},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
err = fmt.Errorf("generate IAM user id: exhausted collision retries")
|
||||
debuglogger.Logf("failed to create IAM user %q: %v", userName, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (c IAMApiController) DeleteUser(ctx fiber.Ctx) (*Response, error) {
|
||||
username, ok := iamutil.RequestParam(ctx, "UserName")
|
||||
if !ok || username == "" {
|
||||
debuglogger.Logf("missing required DeleteUser parameter: UserName")
|
||||
return nil, iamerr.MissingParameter("UserName")
|
||||
}
|
||||
if err := iamutil.ValidateUserName("userName", username, iamutil.MaxUserLookupLen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := c.store.DeleteUser(ctx.Context(), username); err != nil {
|
||||
debuglogger.Logf("failed to delete IAM user %q: %v", username, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Response{Data: &types.DeleteUserResponse{}}, nil
|
||||
}
|
||||
|
||||
func (c IAMApiController) GetUser(ctx fiber.Ctx) (*Response, error) {
|
||||
username, ok := iamutil.RequestParam(ctx, "UserName")
|
||||
if !ok {
|
||||
debuglogger.Logf("missing required GetUser parameter: UserName")
|
||||
return nil, iamerr.MissingParameter("UserName")
|
||||
}
|
||||
if username == "" {
|
||||
return &Response{Data: &types.GetUserResponse{
|
||||
Result: types.GetUserResult{User: types.User{
|
||||
UserID: iamutil.DefaultAccountID,
|
||||
Arn: fmt.Sprintf("arn:aws:iam::%s:root", iamutil.DefaultAccountID),
|
||||
}},
|
||||
}}, nil
|
||||
}
|
||||
if err := iamutil.ValidateUserName("userName", username, iamutil.MaxUserLookupLen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, err := c.store.GetUser(ctx.Context(), username)
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to get IAM user %q: %v", username, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Response{Data: &types.GetUserResponse{
|
||||
Result: types.GetUserResult{User: *user},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (c IAMApiController) ListUsers(ctx fiber.Ctx) (*Response, error) {
|
||||
pathPrefix, ok := iamutil.RequestParam(ctx, "PathPrefix")
|
||||
if !ok || pathPrefix == "" {
|
||||
pathPrefix = iamutil.DefaultUserPath
|
||||
}
|
||||
if err := iamutil.ValidatePathPrefix(pathPrefix); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
maxItems := int32(iamutil.DefaultMaxItems)
|
||||
if rawMaxItems, ok := iamutil.RequestParam(ctx, "MaxItems"); ok && rawMaxItems != "" {
|
||||
parsed, err := strconv.ParseInt(rawMaxItems, 10, 32)
|
||||
if err != nil || parsed < 1 || parsed > iamutil.MaxListItems {
|
||||
debuglogger.Logf("invalid ListUsers MaxItems value %q: parse_error=%v", rawMaxItems, err)
|
||||
return nil, iamerr.InvalidMaxItems(rawMaxItems)
|
||||
}
|
||||
maxItems = int32(parsed)
|
||||
}
|
||||
|
||||
marker, _ := iamutil.RequestParam(ctx, "Marker")
|
||||
out, err := c.store.ListUsers(ctx.Context(), storage.ListUsersInput{
|
||||
PathPrefix: pathPrefix,
|
||||
Marker: marker,
|
||||
MaxItems: maxItems,
|
||||
})
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to list IAM users: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Response{Data: &types.ListUsersResponse{
|
||||
Result: types.ListUsersResult{
|
||||
Users: types.Users{Members: out.Users},
|
||||
IsTruncated: out.IsTruncated,
|
||||
Marker: out.Marker,
|
||||
},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (c IAMApiController) UpdateUser(ctx fiber.Ctx) (*Response, error) {
|
||||
username, ok := iamutil.RequestParam(ctx, "UserName")
|
||||
if !ok || username == "" {
|
||||
debuglogger.Logf("missing required UpdateUser parameter: UserName")
|
||||
return nil, iamerr.MissingParameter("UserName")
|
||||
}
|
||||
if err := iamutil.ValidateUserName("userName", username, iamutil.MaxUserLookupLen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newPath, _ := iamutil.RequestParam(ctx, "NewPath")
|
||||
if newPath != "" {
|
||||
if err := iamutil.ValidatePath("newPath", newPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
newUserName, _ := iamutil.RequestParam(ctx, "NewUserName")
|
||||
if newUserName != "" {
|
||||
if err := iamutil.ValidateUserName("newUserName", newUserName, iamutil.MaxUserNameLen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
user, err := c.store.GetUser(ctx.Context(), username)
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to get IAM user %q for update: %v", username, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
finalPath := user.Path
|
||||
if newPath != "" {
|
||||
finalPath = newPath
|
||||
}
|
||||
finalUserName := user.UserName
|
||||
if newUserName != "" {
|
||||
finalUserName = newUserName
|
||||
}
|
||||
|
||||
updated, err := c.store.UpdateUser(ctx.Context(), storage.UpdateUserInput{
|
||||
UserName: username,
|
||||
NewPath: newPath,
|
||||
NewUserName: newUserName,
|
||||
NewArn: iamutil.BuildUserArn(iamutil.DefaultAccountID, finalPath, finalUserName),
|
||||
})
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to update IAM user %q: %v", finalUserName, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Response{Data: &types.UpdateUserResponse{
|
||||
Result: types.UpdateUserResult{User: updated},
|
||||
}}, nil
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
"github.com/versity/versitygw/iamapi/internal/iamutil"
|
||||
"github.com/versity/versitygw/iamapi/storage"
|
||||
iamtypes "github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
var userIDPattern = regexp.MustCompile(`^AIDA[A-Z2-7]{17}$`)
|
||||
|
||||
func TestIAMApiControllerUserLifecycle(t *testing.T) {
|
||||
server := newIAMControllerTestServer(t)
|
||||
|
||||
create := doIAMAction(t, server, url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Path": {"/engineering/"},
|
||||
"Tags.member.1.Key": {"env"},
|
||||
"Tags.member.1.Value": {"test"},
|
||||
"Tags.member.2.Key": {"empty"},
|
||||
"Tags.member.2.Value": {""},
|
||||
})
|
||||
if create.StatusCode != http.StatusOK {
|
||||
t.Fatalf("CreateUser status = %d, body=%s", create.StatusCode, readBody(t, create))
|
||||
}
|
||||
createBody := readBody(t, create)
|
||||
var createOut iamtypes.CreateUserResponse
|
||||
unmarshalXML(t, createBody, &createOut)
|
||||
if createOut.XMLName.Space != "https://iam.amazonaws.com/doc/2010-05-08/" || createOut.XMLName.Local != "CreateUserResponse" {
|
||||
t.Fatalf("CreateUser XMLName = %#v", createOut.XMLName)
|
||||
}
|
||||
user := createOut.Result.User
|
||||
if user.Path != "/engineering/" || user.UserName != "alice" {
|
||||
t.Fatalf("created user = %#v, want path/name", user)
|
||||
}
|
||||
if !userIDPattern.MatchString(user.UserID) {
|
||||
t.Fatalf("UserId = %q, want AWS IAM user id form", user.UserID)
|
||||
}
|
||||
if user.Arn != "arn:aws:iam::000000000000:user/engineering/alice" {
|
||||
t.Fatalf("Arn = %q", user.Arn)
|
||||
}
|
||||
if user.CreateDate.IsZero() {
|
||||
t.Fatal("CreateDate is zero")
|
||||
}
|
||||
requireUserTags(t, user.Tags)
|
||||
if createOut.ResponseMetadata.RequestID == "" {
|
||||
t.Fatal("CreateUser missing RequestId")
|
||||
}
|
||||
|
||||
duplicate := doIAMAction(t, server, url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
})
|
||||
requireIAMError(t, duplicate, http.StatusConflict, "Sender", "EntityAlreadyExists", "User with name alice already exists.")
|
||||
|
||||
update := doIAMAction(t, server, url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"alice"},
|
||||
"NewUserName": {"zoe"},
|
||||
"NewPath": {"/ops/"},
|
||||
})
|
||||
if update.StatusCode != http.StatusOK {
|
||||
t.Fatalf("UpdateUser status = %d, body=%s", update.StatusCode, readBody(t, update))
|
||||
}
|
||||
var updateOut iamtypes.UpdateUserResponse
|
||||
unmarshalXML(t, readBody(t, update), &updateOut)
|
||||
if updateOut.XMLName.Space != "https://iam.amazonaws.com/doc/2010-05-08/" || updateOut.XMLName.Local != "UpdateUserResponse" {
|
||||
t.Fatalf("UpdateUser XMLName = %#v", updateOut.XMLName)
|
||||
}
|
||||
if updateOut.ResponseMetadata.RequestID == "" {
|
||||
t.Fatal("UpdateUser missing RequestId")
|
||||
}
|
||||
updatedUser := updateOut.Result.User
|
||||
if updatedUser.UserID != user.UserID || !updatedUser.CreateDate.Equal(user.CreateDate) {
|
||||
t.Fatalf("UpdateUser result identity = %#v, want UserId/CreateDate preserved from %#v", updatedUser, user)
|
||||
}
|
||||
if updatedUser.UserName != "zoe" || updatedUser.Path != "/ops/" ||
|
||||
updatedUser.Arn != "arn:aws:iam::000000000000:user/ops/zoe" {
|
||||
t.Fatalf("UpdateUser result = %#v", updatedUser)
|
||||
}
|
||||
|
||||
get := doIAMAction(t, server, url.Values{
|
||||
"Action": {"GetUser"},
|
||||
"UserName": {"zoe"},
|
||||
})
|
||||
if get.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GetUser status = %d, body=%s", get.StatusCode, readBody(t, get))
|
||||
}
|
||||
var getOut iamtypes.GetUserResponse
|
||||
unmarshalXML(t, readBody(t, get), &getOut)
|
||||
gotUser := getOut.Result.User
|
||||
if gotUser.UserID != user.UserID || !gotUser.CreateDate.Equal(user.CreateDate) {
|
||||
t.Fatalf("updated user identity = %#v, want UserId/CreateDate preserved from %#v", gotUser, user)
|
||||
}
|
||||
if gotUser.Path != "/ops/" || gotUser.UserName != "zoe" ||
|
||||
gotUser.Arn != "arn:aws:iam::000000000000:user/ops/zoe" {
|
||||
t.Fatalf("GetUser after update = %#v", gotUser)
|
||||
}
|
||||
requireUserTags(t, gotUser.Tags)
|
||||
|
||||
list := doIAMAction(t, server, url.Values{
|
||||
"Action": {"ListUsers"},
|
||||
"PathPrefix": {"/ops/"},
|
||||
})
|
||||
if list.StatusCode != http.StatusOK {
|
||||
t.Fatalf("ListUsers status = %d, body=%s", list.StatusCode, readBody(t, list))
|
||||
}
|
||||
var listOut iamtypes.ListUsersResponse
|
||||
unmarshalXML(t, readBody(t, list), &listOut)
|
||||
if len(listOut.Result.Users.Members) != 1 || listOut.Result.Users.Members[0].UserName != "zoe" {
|
||||
t.Fatalf("ListUsers = %#v, want zoe", listOut.Result.Users.Members)
|
||||
}
|
||||
requireUserTags(t, listOut.Result.Users.Members[0].Tags)
|
||||
|
||||
deleteResp := doIAMAction(t, server, url.Values{
|
||||
"Action": {"DeleteUser"},
|
||||
"UserName": {"zoe"},
|
||||
})
|
||||
if deleteResp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("DeleteUser status = %d, body=%s", deleteResp.StatusCode, readBody(t, deleteResp))
|
||||
}
|
||||
var deleteOut iamtypes.DeleteUserResponse
|
||||
unmarshalXML(t, readBody(t, deleteResp), &deleteOut)
|
||||
if deleteOut.XMLName.Local != "DeleteUserResponse" || deleteOut.ResponseMetadata.RequestID == "" {
|
||||
t.Fatalf("DeleteUser output = %#v", deleteOut)
|
||||
}
|
||||
|
||||
missing := doIAMAction(t, server, url.Values{
|
||||
"Action": {"GetUser"},
|
||||
"UserName": {"zoe"},
|
||||
})
|
||||
requireIAMError(t, missing, http.StatusNotFound, "Sender", "NoSuchEntity", "The user with name zoe cannot be found.")
|
||||
}
|
||||
|
||||
func TestIAMApiControllerGetRootUser(t *testing.T) {
|
||||
server := newIAMControllerTestServer(t)
|
||||
resp := doIAMAction(t, server, url.Values{
|
||||
"Action": {"GetUser"},
|
||||
"UserName": {""},
|
||||
})
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GetUser root status = %d, body=%s", resp.StatusCode, readBody(t, resp))
|
||||
}
|
||||
|
||||
var out iamtypes.GetUserResponse
|
||||
unmarshalXML(t, readBody(t, resp), &out)
|
||||
if out.Result.User.UserID != iamutil.DefaultAccountID {
|
||||
t.Fatalf("GetUser root UserId = %q, want %q", out.Result.User.UserID, iamutil.DefaultAccountID)
|
||||
}
|
||||
if out.Result.User.Arn != "arn:aws:iam::000000000000:root" {
|
||||
t.Fatalf("GetUser root Arn = %q", out.Result.User.Arn)
|
||||
}
|
||||
if out.ResponseMetadata.RequestID == "" {
|
||||
t.Fatal("GetUser root missing RequestId")
|
||||
}
|
||||
|
||||
missing := doIAMAction(t, server, url.Values{"Action": {"GetUser"}})
|
||||
requireIAMError(t, missing, http.StatusBadRequest, "Sender", "MissingParameter", "The request must contain the parameter UserName.")
|
||||
}
|
||||
|
||||
func TestIAMApiControllerCreateUserValidationErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params url.Values
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}{
|
||||
{
|
||||
name: "missing username",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'userName' failed to satisfy constraint: Member must not be null",
|
||||
},
|
||||
{
|
||||
name: "invalid path",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Path": {"bad"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for path is invalid. It must begin and end with / and contain only alphanumeric characters and/or / characters.",
|
||||
},
|
||||
{
|
||||
name: "long path",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Path": {"/" + strings.Repeat("a", 511) + "/"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'path' failed to satisfy constraint: Member must have length less than or equal to 512",
|
||||
},
|
||||
{
|
||||
name: "invalid username",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"bad/name"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for userName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-",
|
||||
},
|
||||
{
|
||||
name: "long username",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {strings.Repeat("a", 65)},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'userName' failed to satisfy constraint: Member must have length less than or equal to 64",
|
||||
},
|
||||
{
|
||||
name: "invalid tag key",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {"bad*key"},
|
||||
"Tags.member.1.Value": {"test"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+",
|
||||
},
|
||||
{
|
||||
name: "long tag key",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {strings.Repeat("k", 129)},
|
||||
"Tags.member.1.Value": {"test"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'tags.1.member.key' failed to satisfy constraint: Member must have length less than or equal to 128",
|
||||
},
|
||||
{
|
||||
name: "invalid tag value",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {"badval"},
|
||||
"Tags.member.1.Value": {"bad*value"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'tags.1.member.value' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*",
|
||||
},
|
||||
{
|
||||
name: "long tag value",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {"key"},
|
||||
"Tags.member.1.Value": {strings.Repeat("v", 257)},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'tags.1.member.value' failed to satisfy constraint: Member must have length less than or equal to 256",
|
||||
},
|
||||
{
|
||||
name: "duplicate tag key",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {"dup"},
|
||||
"Tags.member.1.Value": {"one"},
|
||||
"Tags.member.2.Key": {"DUP"},
|
||||
"Tags.member.2.Value": {"two"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "InvalidInput",
|
||||
message: "Duplicate tag keys found. Please note that Tag keys are case insensitive.",
|
||||
},
|
||||
{
|
||||
name: "missing tag key",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Value": {"test"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "MissingParameter",
|
||||
message: "The request must contain the parameter Tags.member.1.Key.",
|
||||
},
|
||||
{
|
||||
name: "missing tag value",
|
||||
params: url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {"alice"},
|
||||
"Tags.member.1.Key": {"env"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "MissingParameter",
|
||||
message: "The request must contain the parameter Tags.member.1.Value.",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newIAMControllerTestServer(t)
|
||||
resp := doIAMAction(t, server, tt.params)
|
||||
requireIAMError(t, resp, tt.status, "Sender", tt.code, tt.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiControllerDeleteAndUpdateUserErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params url.Values
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}{
|
||||
{
|
||||
name: "delete invalid username",
|
||||
params: url.Values{
|
||||
"Action": {"DeleteUser"},
|
||||
"UserName": {"bad/name"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for userName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-",
|
||||
},
|
||||
{
|
||||
name: "delete long username",
|
||||
params: url.Values{
|
||||
"Action": {"DeleteUser"},
|
||||
"UserName": {strings.Repeat("a", 129)},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'userName' failed to satisfy constraint: Member must have length less than or equal to 128",
|
||||
},
|
||||
{
|
||||
name: "delete missing user",
|
||||
params: url.Values{
|
||||
"Action": {"DeleteUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
},
|
||||
status: http.StatusNotFound,
|
||||
code: "NoSuchEntity",
|
||||
message: "The user with name asdfadsf cannot be found.",
|
||||
},
|
||||
{
|
||||
name: "update invalid username",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"bad/name"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for userName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-",
|
||||
},
|
||||
{
|
||||
name: "update long username",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {strings.Repeat("a", 129)},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'userName' failed to satisfy constraint: Member must have length less than or equal to 128",
|
||||
},
|
||||
{
|
||||
name: "update invalid new username",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
"NewUserName": {"bad/name"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for newUserName is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-",
|
||||
},
|
||||
{
|
||||
name: "update long new username",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
"NewUserName": {strings.Repeat("a", 65)},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'newUserName' failed to satisfy constraint: Member must have length less than or equal to 64",
|
||||
},
|
||||
{
|
||||
name: "update invalid new path",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
"NewPath": {"invalid"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "The specified value for newPath is invalid. It must begin and end with / and contain only alphanumeric characters and/or / characters.",
|
||||
},
|
||||
{
|
||||
name: "update long new path",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
"NewPath": {"/" + strings.Repeat("a", 511) + "/"},
|
||||
},
|
||||
status: http.StatusBadRequest,
|
||||
code: "ValidationError",
|
||||
message: "1 validation error detected: Value at 'newPath' failed to satisfy constraint: Member must have length less than or equal to 512",
|
||||
},
|
||||
{
|
||||
name: "update missing user",
|
||||
params: url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"asdfadsf"},
|
||||
},
|
||||
status: http.StatusNotFound,
|
||||
code: "NoSuchEntity",
|
||||
message: "The user with name asdfadsf cannot be found.",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := newIAMControllerTestServer(t)
|
||||
resp := doIAMAction(t, server, tt.params)
|
||||
requireIAMError(t, resp, tt.status, "Sender", tt.code, tt.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiControllerUpdateUserAlreadyExists(t *testing.T) {
|
||||
server := newIAMControllerTestServer(t)
|
||||
for _, userName := range []string{"alice", "zoe"} {
|
||||
resp := doIAMAction(t, server, url.Values{
|
||||
"Action": {"CreateUser"},
|
||||
"UserName": {userName},
|
||||
})
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("CreateUser(%q) status = %d, body=%s", userName, resp.StatusCode, readBody(t, resp))
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
resp := doIAMAction(t, server, url.Values{
|
||||
"Action": {"UpdateUser"},
|
||||
"UserName": {"alice"},
|
||||
"NewUserName": {"zoe"},
|
||||
})
|
||||
requireIAMError(t, resp, http.StatusConflict, "Sender", "EntityAlreadyExists", "User with name zoe already exists.")
|
||||
}
|
||||
|
||||
func newIAMControllerTestServer(t *testing.T) *IAMApiServer {
|
||||
t.Helper()
|
||||
|
||||
store, err := storage.New(storage.Config{Dir: t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatalf("storage.New: %v", err)
|
||||
}
|
||||
server, err := New(store, WithQuiet(), WithRootUserCreds(testRoot))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
func doIAMAction(t *testing.T, server *IAMApiServer, params url.Values) *http.Response {
|
||||
t.Helper()
|
||||
if !params.Has("Version") {
|
||||
params.Set("Version", iamAPIVersion)
|
||||
}
|
||||
|
||||
req := querySignedIAMRequest(t, http.MethodGet, "http://example.com/?"+params.Encode(), nil, testRoot.Secret, iammiddleware.SigningRegion, time.Now().UTC())
|
||||
resp, err := server.app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func unmarshalXML(t *testing.T, body string, out any) {
|
||||
t.Helper()
|
||||
|
||||
if err := xml.Unmarshal([]byte(body), out); err != nil {
|
||||
t.Fatalf("unmarshal XML: %v\n%s", err, body)
|
||||
}
|
||||
}
|
||||
|
||||
func requireUserTags(t *testing.T, tags []iamtypes.Tag) {
|
||||
t.Helper()
|
||||
|
||||
if len(tags) != 2 || tags[0].Key != "env" || tags[0].Value != "test" ||
|
||||
tags[1].Key != "empty" || tags[1].Value != "" {
|
||||
t.Fatalf("Tags = %#v, want env=test and empty=", tags)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
// 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 iamerr
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
Namespace = "https://iam.amazonaws.com/doc/2010-05-08/"
|
||||
AWSFaultNamespace = "http://webservices.amazon.com/AWSFault/2005-15-09"
|
||||
)
|
||||
|
||||
type ErrorType string
|
||||
|
||||
const (
|
||||
TypeSender ErrorType = "Sender"
|
||||
TypeReceiver ErrorType = "Receiver"
|
||||
)
|
||||
|
||||
type ErrorCode int
|
||||
|
||||
const (
|
||||
ErrInternalFailure ErrorCode = iota
|
||||
|
||||
ErrSignatureDoesNotMatch
|
||||
ErrMissingAuthenticationToken
|
||||
ErrIncompleteSignature
|
||||
ErrUnsupportedSignatureVersion
|
||||
ErrMissingAuthorizationComponents
|
||||
ErrIncorrectService
|
||||
ErrInvalidCredentialDate
|
||||
ErrInvalidTerminal
|
||||
ErrUnsupportedQueryAlgorithm
|
||||
ErrInvalidRegion
|
||||
ErrMissingHostSignedHeader
|
||||
ErrInvalidClientTokenID
|
||||
|
||||
ErrInvalidContentLength
|
||||
ErrThrottling
|
||||
|
||||
ErrMissingUserNameValue
|
||||
ErrTooManyTags
|
||||
ErrInvalidPathPrefix
|
||||
ErrDuplicateTagKeys
|
||||
)
|
||||
|
||||
type APIError interface {
|
||||
error
|
||||
StatusCode() int
|
||||
XMLBody(requestID string) []byte
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Type ErrorType
|
||||
Code string
|
||||
Message string
|
||||
HTTPStatusCode int
|
||||
XMLNamespace string
|
||||
}
|
||||
|
||||
func (e Error) Error() string {
|
||||
return e.Code + ": " + e.Message
|
||||
}
|
||||
|
||||
func (e Error) StatusCode() int {
|
||||
return e.HTTPStatusCode
|
||||
}
|
||||
|
||||
func (e Error) XMLBody(requestID string) []byte {
|
||||
namespace := e.XMLNamespace
|
||||
if namespace == "" {
|
||||
namespace = Namespace
|
||||
}
|
||||
|
||||
body, err := xml.Marshal(struct {
|
||||
XMLName xml.Name
|
||||
Error errorXML
|
||||
RequestID string `xml:"RequestId"`
|
||||
}{
|
||||
XMLName: xml.Name{Space: namespace, Local: "ErrorResponse"},
|
||||
Error: errorXML{
|
||||
Type: e.Type,
|
||||
Code: e.Code,
|
||||
Message: e.Message,
|
||||
},
|
||||
RequestID: requestID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return append([]byte(xml.Header), body...)
|
||||
}
|
||||
|
||||
type errorXML struct {
|
||||
Type ErrorType
|
||||
Code string
|
||||
Message string
|
||||
}
|
||||
|
||||
var errorCodeResponse = map[ErrorCode]Error{
|
||||
ErrInternalFailure: {
|
||||
Type: TypeReceiver,
|
||||
Code: "InternalFailure",
|
||||
Message: "The request processing has failed because of an unknown error, exception or failure.",
|
||||
HTTPStatusCode: http.StatusInternalServerError,
|
||||
},
|
||||
|
||||
ErrInvalidContentLength: {
|
||||
Type: TypeSender,
|
||||
Code: "InvalidRequest",
|
||||
Message: "Content-Length must be a valid integer.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrThrottling: {
|
||||
Type: TypeSender,
|
||||
Code: "Throttling",
|
||||
Message: "Rate exceeded.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
|
||||
ErrMissingAuthenticationToken: {
|
||||
Type: TypeSender,
|
||||
Code: "MissingAuthenticationToken",
|
||||
Message: "Request is missing Authentication Token",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrUnsupportedQueryAlgorithm: {
|
||||
Type: TypeSender,
|
||||
Code: "MissingAuthenticationToken",
|
||||
Message: "Missing Authentication Token",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrInvalidClientTokenID: {
|
||||
Type: TypeSender,
|
||||
Code: "InvalidClientTokenId",
|
||||
Message: "The security token included in the request is invalid.",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
|
||||
ErrIncompleteSignature: {
|
||||
Type: TypeSender,
|
||||
Code: "IncompleteSignature",
|
||||
Message: "The request signature does not conform to AWS standards.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrUnsupportedSignatureVersion: {
|
||||
Type: TypeSender,
|
||||
Code: "IncompleteSignature",
|
||||
Message: "AWS Signature Version 2 is not supported.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrMissingAuthorizationComponents: {
|
||||
Type: TypeSender,
|
||||
Code: "IncompleteSignature",
|
||||
Message: "Authorization header requires Credential, SignedHeaders, and Signature.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
|
||||
ErrSignatureDoesNotMatch: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrIncorrectService: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "Credential should be scoped to correct service: 'iam'.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrInvalidCredentialDate: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "Date in Credential scope does not match YYYYMMDD from ISO-8601 version of date from HTTP.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrInvalidTerminal: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "Credential should be scoped with a valid terminator: 'aws4_request'.",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrInvalidRegion: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "Credential should be scoped to a valid region. ",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
ErrMissingHostSignedHeader: {
|
||||
Type: TypeSender,
|
||||
Code: "SignatureDoesNotMatch",
|
||||
Message: "'Host' or ':authority' must be a 'SignedHeader' in the AWS Authorization.",
|
||||
HTTPStatusCode: http.StatusForbidden,
|
||||
},
|
||||
|
||||
ErrMissingUserNameValue: {
|
||||
Type: TypeSender,
|
||||
Code: "ValidationError",
|
||||
Message: "1 validation error detected: Value at 'userName' failed to satisfy constraint: Member must not be null",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrInvalidPathPrefix: {
|
||||
Type: TypeSender,
|
||||
Code: "ValidationError",
|
||||
Message: "The specified value for pathPrefix is invalid. It must begin with the / character and contain only alphanumeric characters and/or / characters.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrTooManyTags: {
|
||||
Type: TypeSender,
|
||||
Code: "ValidationError",
|
||||
Message: "1 validation error detected: Value at 'tags' failed to satisfy constraint: Member must have length less than or equal to 50",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
ErrDuplicateTagKeys: {
|
||||
Type: TypeSender,
|
||||
Code: "InvalidInput",
|
||||
Message: "Duplicate tag keys found. Please note that Tag keys are case insensitive.",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
},
|
||||
}
|
||||
|
||||
func GetAPIError(code ErrorCode) Error {
|
||||
if err, ok := errorCodeResponse[code]; ok {
|
||||
return err
|
||||
}
|
||||
|
||||
return errorCodeResponse[ErrInternalFailure]
|
||||
}
|
||||
|
||||
func InvalidAction(action, version string) Error {
|
||||
err := newSenderError("InvalidAction", fmt.Sprintf("Could not find operation %s for version %s", action, version), http.StatusBadRequest)
|
||||
err.XMLNamespace = AWSFaultNamespace
|
||||
return err
|
||||
}
|
||||
|
||||
func MissingParameter(parameter string) Error {
|
||||
return newSenderError("MissingParameter", fmt.Sprintf("The request must contain the parameter %s.", parameter), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func IncompleteSignatureMalformedComponent(component string) Error {
|
||||
err := GetAPIError(ErrIncompleteSignature)
|
||||
err.Message = fmt.Sprintf("Authorization component %q is malformed.", component)
|
||||
return err
|
||||
}
|
||||
|
||||
func IncompleteSignatureMalformedCredential(credential string) Error {
|
||||
return newSenderError(
|
||||
"IncompleteSignature",
|
||||
fmt.Sprintf("Credential must have exactly 5 slash-delimited elements, e.g. keyid/date/region/service/term, got '%s'", credential),
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
}
|
||||
|
||||
func IncompleteSignatureMissingAuthorizationComponent(component, authorization string) Error {
|
||||
err := GetAPIError(ErrIncompleteSignature)
|
||||
err.Message = fmt.Sprintf("Authorization header requires '%s' parameter. (Hashed with SHA-256 and encoded with Base64) Authorization=%s",
|
||||
component,
|
||||
hashAuthorization(authorization))
|
||||
return err
|
||||
}
|
||||
|
||||
func IncompleteSignatureMissingQueryParameter(parameter string) Error {
|
||||
err := GetAPIError(ErrIncompleteSignature)
|
||||
err.Message = fmt.Sprintf("AWS query-string parameters must include '%s'. Re-examine the query-string parameters.", parameter)
|
||||
return err
|
||||
}
|
||||
|
||||
func IncompleteSignatureMissingDate(authorization string) Error {
|
||||
return newSenderError(
|
||||
"IncompleteSignature",
|
||||
fmt.Sprintf("Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. (Hashed with SHA-256 and encoded with Base64) Authorization=%s", hashAuthorization(authorization)),
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
}
|
||||
|
||||
func IncompleteSignatureInvalidXAmzDate(date string) Error {
|
||||
return newSenderError(
|
||||
"IncompleteSignature",
|
||||
fmt.Sprintf("Date must be in ISO-8601 'basic format'. Got '%s'. See http://en.wikipedia.org/wiki/ISO_8601", date),
|
||||
http.StatusBadRequest,
|
||||
)
|
||||
}
|
||||
|
||||
func IncompleteSignatureHeadersNotSigned(headers []string) Error {
|
||||
err := GetAPIError(ErrIncompleteSignature)
|
||||
err.Message = fmt.Sprintf("The request signature does not conform to AWS standards. Header(s) not signed: %s.", strings.Join(headers, ", "))
|
||||
return err
|
||||
}
|
||||
|
||||
func SignatureDoesNotMatchNotYetCurrent(requestTime, serverTime time.Time, allowedSkew time.Duration) Error {
|
||||
err := GetAPIError(ErrSignatureDoesNotMatch)
|
||||
err.Message = fmt.Sprintf("Signature not yet current: %s is still later than %s (%s + %d min.)",
|
||||
requestTime.UTC().Format("20060102T150405Z"),
|
||||
serverTime.UTC().Add(allowedSkew).Format("20060102T150405Z"),
|
||||
serverTime.UTC().Format("20060102T150405Z"),
|
||||
allowedSkew/time.Minute)
|
||||
return err
|
||||
}
|
||||
|
||||
func SignatureDoesNotMatchExpired(requestTime, serverTime time.Time, allowedSkew time.Duration) Error {
|
||||
err := GetAPIError(ErrSignatureDoesNotMatch)
|
||||
err.Message = fmt.Sprintf("Signature expired: %s is now earlier than %s (%s - %d min.)",
|
||||
requestTime.UTC().Format("20060102T150405Z"),
|
||||
serverTime.UTC().Add(-allowedSkew).Format("20060102T150405Z"),
|
||||
serverTime.UTC().Format("20060102T150405Z"),
|
||||
allowedSkew/time.Minute)
|
||||
return err
|
||||
}
|
||||
|
||||
func EntityAlreadyExistsUser(userName string) Error {
|
||||
return newSenderError("EntityAlreadyExists", fmt.Sprintf("User with name %s already exists.", userName), http.StatusConflict)
|
||||
}
|
||||
|
||||
func NoSuchEntityUser(userName string) Error {
|
||||
return newSenderError("NoSuchEntity", fmt.Sprintf("The user with name %s cannot be found.", userName), http.StatusNotFound)
|
||||
}
|
||||
|
||||
func ValidationError(message string) Error {
|
||||
return newSenderError("ValidationError", message, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func InvalidInput(message string) Error {
|
||||
return newSenderError("InvalidInput", message, http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func InvalidUserName(field string) Error {
|
||||
return ValidationError(fmt.Sprintf("The specified value for %s is invalid. It must contain only alphanumeric characters and/or the following: +=,.@_-", field))
|
||||
}
|
||||
|
||||
func UserNameTooLong(field string, maxLength int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at '%s' failed to satisfy constraint: Member must have length less than or equal to %d", field, maxLength))
|
||||
}
|
||||
|
||||
func InvalidPath(field string) Error {
|
||||
return ValidationError(fmt.Sprintf("The specified value for %s is invalid. It must begin and end with / and contain only alphanumeric characters and/or / characters.", field))
|
||||
}
|
||||
|
||||
func PathTooLong(field string, maxLength int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at '%s' failed to satisfy constraint: Member must have length less than or equal to %d", field, maxLength))
|
||||
}
|
||||
|
||||
func InvalidMaxItems(value string) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value '%s' at 'maxItems' failed to satisfy constraint: Member must have value between 1 and 1000", value))
|
||||
}
|
||||
|
||||
func TagKeyTooLong(index int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at 'tags.%d.member.key' failed to satisfy constraint: Member must have length less than or equal to 128", index))
|
||||
}
|
||||
|
||||
func InvalidTagKey(index int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at 'tags.%d.member.key' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+", index))
|
||||
}
|
||||
|
||||
func TagValueTooLong(index int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at 'tags.%d.member.value' failed to satisfy constraint: Member must have length less than or equal to 256", index))
|
||||
}
|
||||
|
||||
func InvalidTagValue(index int) Error {
|
||||
return ValidationError(fmt.Sprintf("1 validation error detected: Value at 'tags.%d.member.value' failed to satisfy constraint: Member must satisfy regular expression pattern: [\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*", index))
|
||||
}
|
||||
|
||||
func newSenderError(code, message string, statusCode int) Error {
|
||||
return Error{
|
||||
Type: TypeSender,
|
||||
Code: code,
|
||||
Message: message,
|
||||
HTTPStatusCode: statusCode,
|
||||
}
|
||||
}
|
||||
|
||||
func hashAuthorization(authorization string) string {
|
||||
hash := sha256.Sum256([]byte(authorization))
|
||||
return base64.StdEncoding.EncodeToString(hash[:])
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// 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 iammiddleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/internal/sigv4auth"
|
||||
)
|
||||
|
||||
const (
|
||||
SigningRegion = "us-east-1"
|
||||
timeExpiration = 15 * time.Minute
|
||||
)
|
||||
|
||||
var requiredSignedHeaders = []string{"host"}
|
||||
|
||||
type RootCredentials struct {
|
||||
Access string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func VerifyIAMAuth(root *RootCredentials) fiber.Handler {
|
||||
return func(ctx fiber.Ctx) error {
|
||||
authData, tdate, queryAuth, err := parseIAMAuth(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if authData.Access != root.Access {
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidClientTokenID)
|
||||
}
|
||||
|
||||
contentLength, err := parseContentLength(ctx.Get("Content-Length"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
payloadHash := sigv4auth.PayloadSHA256Hex(ctx.BodyRaw())
|
||||
if queryAuth {
|
||||
_, err = sigv4auth.CheckQuerySignature(ctx, authData, root.Secret, payloadHash, tdate, contentLength, sigv4auth.CheckOptions{
|
||||
Service: sigv4auth.ServiceIAM,
|
||||
RequiredSignedHeaders: requiredSignedHeaders,
|
||||
})
|
||||
} else {
|
||||
_, err = sigv4auth.CheckSignature(ctx, authData, root.Secret, payloadHash, tdate, contentLength, sigv4auth.CheckOptions{
|
||||
Service: sigv4auth.ServiceIAM,
|
||||
RequiredSignedHeaders: requiredSignedHeaders,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return mapIAMSigV4Error(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func parseIAMAuth(ctx fiber.Ctx) (sigv4auth.AuthData, time.Time, bool, error) {
|
||||
if sigv4auth.IsQueryAuth(ctx) {
|
||||
return parseIAMQueryAuth(ctx)
|
||||
}
|
||||
if sigv4auth.IsQueryAuthV2(ctx) {
|
||||
return sigv4auth.AuthData{}, time.Time{}, false, iamerr.GetAPIError(iamerr.ErrUnsupportedSignatureVersion)
|
||||
}
|
||||
|
||||
return parseIAMHeaderAuth(ctx)
|
||||
}
|
||||
|
||||
func parseIAMHeaderAuth(ctx fiber.Ctx) (sigv4auth.AuthData, time.Time, bool, error) {
|
||||
authData := sigv4auth.AuthData{}
|
||||
|
||||
authorization := ctx.Get("Authorization")
|
||||
if authorization == "" {
|
||||
return authData, time.Time{}, false, iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken)
|
||||
}
|
||||
|
||||
date := ctx.Get("X-Amz-Date")
|
||||
if date == "" {
|
||||
date = ctx.Get("Date")
|
||||
}
|
||||
if date == "" {
|
||||
return authData, time.Time{}, false, iamerr.IncompleteSignatureMissingDate(authorization)
|
||||
}
|
||||
|
||||
tdate, err := time.Parse(sigv4auth.ISO8601Format, date)
|
||||
if err != nil {
|
||||
return authData, time.Time{}, false, iamerr.IncompleteSignatureInvalidXAmzDate(date)
|
||||
}
|
||||
if err := ValidateDateAt(tdate, time.Now().UTC()); err != nil {
|
||||
return authData, time.Time{}, false, err
|
||||
}
|
||||
|
||||
authData, err = sigv4auth.ParseAuthorization(authorization, sigv4auth.ServiceIAM)
|
||||
if err != nil {
|
||||
return authData, time.Time{}, false, mapIAMSigV4Error(err, authorization)
|
||||
}
|
||||
|
||||
if authData.Region != SigningRegion {
|
||||
return authData, time.Time{}, false, iamerr.GetAPIError(iamerr.ErrInvalidRegion)
|
||||
}
|
||||
if date[:8] != authData.Date {
|
||||
return authData, time.Time{}, false, iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate)
|
||||
}
|
||||
|
||||
return authData, tdate, false, nil
|
||||
}
|
||||
|
||||
func parseIAMQueryAuth(ctx fiber.Ctx) (sigv4auth.AuthData, time.Time, bool, error) {
|
||||
if ctx.Request().URI().QueryArgs().Has(sigv4auth.QuerySecurityToken) {
|
||||
return sigv4auth.AuthData{}, time.Time{}, true, mapIAMSigV4Error(&sigv4auth.QueryError{Kind: sigv4auth.ErrQuerySecurityToken})
|
||||
}
|
||||
|
||||
authData, details, err := sigv4auth.ParseQueryAuthorization(ctx, sigv4auth.QueryAuthOptions{
|
||||
Service: sigv4auth.ServiceIAM,
|
||||
Region: SigningRegion,
|
||||
})
|
||||
if err != nil {
|
||||
return authData, time.Time{}, true, mapIAMSigV4Error(err)
|
||||
}
|
||||
if err := ValidateDateAt(details.SigningTime, time.Now().UTC()); err != nil {
|
||||
return authData, time.Time{}, true, err
|
||||
}
|
||||
|
||||
return authData, details.SigningTime, true, nil
|
||||
}
|
||||
|
||||
func parseContentLength(contentLengthStr string) (int64, error) {
|
||||
if contentLengthStr == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
contentLength, err := strconv.ParseInt(contentLengthStr, 10, 64)
|
||||
if err != nil {
|
||||
return 0, iamerr.GetAPIError(iamerr.ErrInvalidContentLength)
|
||||
}
|
||||
|
||||
return contentLength, nil
|
||||
}
|
||||
|
||||
// ValidateDateAt checks that date is within the allowed window relative to now.
|
||||
// Exported so tests can exercise it directly.
|
||||
func ValidateDateAt(date, now time.Time) error {
|
||||
if date.After(now.Add(timeExpiration)) {
|
||||
return iamerr.SignatureDoesNotMatchNotYetCurrent(date, now, timeExpiration)
|
||||
}
|
||||
if date.Before(now.Add(-timeExpiration)) {
|
||||
return iamerr.SignatureDoesNotMatchExpired(date, now, timeExpiration)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapIAMSigV4Error(err error, authorization ...string) error {
|
||||
var queryErr *sigv4auth.QueryError
|
||||
if errors.As(err, &queryErr) {
|
||||
return mapIAMQueryError(queryErr)
|
||||
}
|
||||
|
||||
var parseErr *sigv4auth.ParseError
|
||||
if errors.As(err, &parseErr) {
|
||||
authHeader := ""
|
||||
if len(authorization) > 0 {
|
||||
authHeader = authorization[0]
|
||||
}
|
||||
return mapIAMParseError(parseErr, authHeader)
|
||||
}
|
||||
|
||||
var headersErr *sigv4auth.HeadersNotSignedError
|
||||
if errors.As(err, &headersErr) {
|
||||
if len(headersErr.Headers) == 1 && headersErr.Headers[0] == "host" {
|
||||
return iamerr.GetAPIError(iamerr.ErrMissingHostSignedHeader)
|
||||
}
|
||||
return iamerr.IncompleteSignatureHeadersNotSigned(headersErr.Headers)
|
||||
}
|
||||
|
||||
var sigErr *sigv4auth.SignatureMismatchError
|
||||
if errors.As(err, &sigErr) {
|
||||
return iamerr.GetAPIError(iamerr.ErrSignatureDoesNotMatch)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func mapIAMQueryError(err *sigv4auth.QueryError) error {
|
||||
switch err.Kind {
|
||||
case sigv4auth.ErrQueryMissingRequiredParams:
|
||||
switch err.Value {
|
||||
case sigv4auth.QueryAlgorithm:
|
||||
return iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken)
|
||||
case sigv4auth.QueryCredential, sigv4auth.QueryDate, sigv4auth.QuerySignedHeaders, sigv4auth.QuerySignature:
|
||||
return iamerr.IncompleteSignatureMissingQueryParameter(err.Value)
|
||||
default:
|
||||
return iamerr.GetAPIError(iamerr.ErrIncompleteSignature)
|
||||
}
|
||||
case sigv4auth.ErrQueryUnsupportedAlgorithm, sigv4auth.ErrQueryUnsupportedECDSA:
|
||||
return iamerr.GetAPIError(iamerr.ErrUnsupportedQueryAlgorithm)
|
||||
case sigv4auth.ErrQueryInvalidDateFormat:
|
||||
return iamerr.IncompleteSignatureInvalidXAmzDate(err.Value)
|
||||
case sigv4auth.ErrQueryDateMismatch:
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate)
|
||||
case sigv4auth.ErrQueryIncorrectRegion:
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidRegion)
|
||||
case sigv4auth.ErrQuerySecurityToken:
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidClientTokenID)
|
||||
default:
|
||||
return iamerr.GetAPIError(iamerr.ErrIncompleteSignature)
|
||||
}
|
||||
}
|
||||
|
||||
func mapIAMParseError(err *sigv4auth.ParseError, authorization string) error {
|
||||
if authorization == "" {
|
||||
authorization = err.Input
|
||||
}
|
||||
|
||||
switch err.Kind {
|
||||
case sigv4auth.ErrInvalidAuthorizationHeader:
|
||||
return iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken)
|
||||
case sigv4auth.ErrUnsupportedAuthorizationVersion:
|
||||
return iamerr.GetAPIError(iamerr.ErrUnsupportedSignatureVersion)
|
||||
case sigv4auth.ErrInvalidAuthorizationType:
|
||||
return iamerr.GetAPIError(iamerr.ErrMissingAuthenticationToken)
|
||||
case sigv4auth.ErrMissingComponents:
|
||||
return iamerr.GetAPIError(iamerr.ErrMissingAuthorizationComponents)
|
||||
case sigv4auth.ErrMissingCredential:
|
||||
return iamerr.IncompleteSignatureMissingAuthorizationComponent("Credential", authorization)
|
||||
case sigv4auth.ErrMissingSignedHeaders:
|
||||
return iamerr.IncompleteSignatureMissingAuthorizationComponent("SignedHeaders", authorization)
|
||||
case sigv4auth.ErrMissingSignature:
|
||||
return iamerr.IncompleteSignatureMissingAuthorizationComponent("Signature", authorization)
|
||||
case sigv4auth.ErrMalformedComponent:
|
||||
return iamerr.IncompleteSignatureMalformedComponent(err.Value)
|
||||
case sigv4auth.ErrMalformedCredential:
|
||||
return iamerr.IncompleteSignatureMalformedCredential(err.Input)
|
||||
case sigv4auth.ErrIncorrectService:
|
||||
return iamerr.GetAPIError(iamerr.ErrIncorrectService)
|
||||
case sigv4auth.ErrIncorrectTerminal:
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidTerminal)
|
||||
case sigv4auth.ErrInvalidDateFormat:
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidCredentialDate)
|
||||
default:
|
||||
return iamerr.GetAPIError(iamerr.ErrIncompleteSignature)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// 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 iammiddleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
// DebugLogger returns a middleware that logs full request and response details
|
||||
// when debug logging is enabled.
|
||||
func DebugLogger() fiber.Handler {
|
||||
return func(ctx fiber.Ctx) error {
|
||||
debuglogger.LogFiberRequestDetails(ctx)
|
||||
err := ctx.Next()
|
||||
debuglogger.LogFiberResponseDetails(ctx)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// StackTraceHandler stores the panic value in the request context so that the
|
||||
// global error handler can distinguish panics from regular errors.
|
||||
func StackTraceHandler(ctx fiber.Ctx, e any) {
|
||||
httpctx.ContextKeyStack.Set(ctx, e)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// 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 iammiddleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
// GlobalErrorHandler is the fiber error handler for the IAM API server. It
|
||||
// translates APIError values into XML responses and logs unexpected errors.
|
||||
func GlobalErrorHandler(ctx fiber.Ctx, er error) error {
|
||||
requestID := EnsureRequestID(ctx)
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
|
||||
var apiErr iamerr.APIError
|
||||
if errors.As(er, &apiErr) {
|
||||
return ctx.Status(apiErr.StatusCode()).Send(apiErr.XMLBody(requestID))
|
||||
}
|
||||
|
||||
if httpctx.ContextKeyStack.IsSet(ctx) {
|
||||
debuglogger.Panic(er)
|
||||
} else {
|
||||
debuglogger.InternalError(er)
|
||||
}
|
||||
|
||||
err := iamerr.GetAPIError(iamerr.ErrInternalFailure)
|
||||
return ctx.Status(err.StatusCode()).Send(err.XMLBody(requestID))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// 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 iammiddleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"golang.org/x/sync/semaphore"
|
||||
)
|
||||
|
||||
// RateLimiter returns a middleware that limits concurrent in-flight requests to
|
||||
// limit. Excess requests receive a Throttling error response immediately.
|
||||
func RateLimiter(limit int) fiber.Handler {
|
||||
sem := semaphore.NewWeighted(int64(limit))
|
||||
|
||||
return func(ctx fiber.Ctx) error {
|
||||
requestID := EnsureRequestID(ctx)
|
||||
|
||||
if !sem.TryAcquire(1) {
|
||||
err := iamerr.GetAPIError(iamerr.ErrThrottling)
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
return ctx.Status(err.StatusCode()).Send(err.XMLBody(requestID))
|
||||
}
|
||||
defer sem.Release(1)
|
||||
return ctx.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// 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 iammiddleware
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
const HeaderAmznRequestID = "x-amzn-RequestId"
|
||||
|
||||
// RequestIDs is a middleware that ensures every request has a request ID set
|
||||
// and returned in the response header.
|
||||
func RequestIDs() fiber.Handler {
|
||||
return func(ctx fiber.Ctx) error {
|
||||
EnsureRequestID(ctx)
|
||||
return ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// EnsureRequestID returns the existing request ID from the context, or
|
||||
// generates and stores a new one if none exists. It always sets the
|
||||
// x-amzn-RequestId response header.
|
||||
func EnsureRequestID(ctx fiber.Ctx) string {
|
||||
requestID, _ := httpctx.ContextKeyRequestID.Get(ctx).(string)
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewString()
|
||||
httpctx.ContextKeyRequestID.Set(ctx, requestID)
|
||||
}
|
||||
|
||||
ctx.Response().Header.Set(HeaderAmznRequestID, requestID)
|
||||
return requestID
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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 (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
// MatchQueryOrFormArgs matches AWS Query-style requests that contain all
|
||||
// provided parameters in either the URL query string or a form body.
|
||||
func MatchQueryOrFormArgs(args ...string) fiber.Handler {
|
||||
return func(ctx fiber.Ctx) error {
|
||||
if httpctx.ContextKeySkip.IsSet(ctx) {
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
queryArgs := ctx.Request().URI().QueryArgs()
|
||||
formArgs := ctx.Request().PostArgs()
|
||||
for _, arg := range args {
|
||||
if !queryArgs.Has(arg) && !formArgs.Has(arg) {
|
||||
httpctx.ContextKeySkip.Set(ctx, true)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// 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 (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
func TestMatchQueryOrFormArgs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
target string
|
||||
body string
|
||||
contentType string
|
||||
want string
|
||||
}{
|
||||
{name: "query", method: http.MethodGet, target: "/any?Action=ListUsers", want: "matched"},
|
||||
{name: "empty query value is present", method: http.MethodGet, target: "/any?Action=", want: "matched"},
|
||||
{name: "form", method: http.MethodPost, target: "/any", body: "Action=ListUsers", contentType: fiber.MIMEApplicationForm, want: "matched"},
|
||||
{name: "missing", method: http.MethodGet, target: "/any", want: "fallback"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := fiber.New()
|
||||
app.Add([]string{http.MethodGet, http.MethodPost}, "/*",
|
||||
MatchQueryOrFormArgs("Action"),
|
||||
func(ctx fiber.Ctx) error {
|
||||
if httpctx.ContextKeySkip.IsSet(ctx) {
|
||||
httpctx.ContextKeySkip.Delete(ctx)
|
||||
return ctx.Next()
|
||||
}
|
||||
return ctx.SendString("matched")
|
||||
},
|
||||
)
|
||||
app.All("*", func(ctx fiber.Ctx) error { return ctx.SendString("fallback") })
|
||||
|
||||
req := httptest.NewRequest(tt.method, tt.target, bytes.NewBufferString(tt.body))
|
||||
if tt.contentType != "" {
|
||||
req.Header.Set("Content-Type", tt.contentType)
|
||||
}
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if string(body) != tt.want {
|
||||
t.Fatalf("body = %q, want %q", string(body), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// 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"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultAccountID = "000000000000"
|
||||
DefaultUserPath = "/"
|
||||
DefaultMaxItems = 100
|
||||
MaxListItems = 1000
|
||||
MaxUserNameLen = 64
|
||||
MaxUserLookupLen = 128
|
||||
MaxPathLen = 512
|
||||
userIDPrefix = "AIDA"
|
||||
userIDRandomLen = 17
|
||||
userIDAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
maxTagKeyLen = 128
|
||||
maxTagValLen = 256
|
||||
)
|
||||
|
||||
var (
|
||||
userNamePattern = regexp.MustCompile(`^[A-Za-z0-9+=,.@_-]+$`)
|
||||
tagKeyPattern = regexp.MustCompile(`^[\p{L}\p{Z}\p{N}_.:/=+\-@]+$`)
|
||||
tagValPattern = regexp.MustCompile(`^[\p{L}\p{Z}\p{N}_.:/=+\-@]*$`)
|
||||
)
|
||||
|
||||
// RequestParam looks up key first in URL query args, then in the POST body.
|
||||
func RequestParam(ctx fiber.Ctx, key string) (string, bool) {
|
||||
queryArgs := ctx.Request().URI().QueryArgs()
|
||||
if queryArgs.Has(key) {
|
||||
return string(queryArgs.Peek(key)), true
|
||||
}
|
||||
|
||||
postArgs := ctx.Request().PostArgs()
|
||||
if postArgs.Has(key) {
|
||||
return string(postArgs.Peek(key)), true
|
||||
}
|
||||
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ParseTags reads IAM tag members from the request (up to 50), validates each, and returns the list.
|
||||
func ParseTags(ctx fiber.Ctx) ([]types.Tag, error) {
|
||||
var tags []types.Tag
|
||||
seen := map[string]struct{}{}
|
||||
|
||||
for i := 1; ; i++ {
|
||||
keyName := fmt.Sprintf("Tags.member.%d.Key", i)
|
||||
valueName := fmt.Sprintf("Tags.member.%d.Value", i)
|
||||
|
||||
key, hasKey := RequestParam(ctx, keyName)
|
||||
value, hasValue := RequestParam(ctx, valueName)
|
||||
if !hasKey && !hasValue {
|
||||
break
|
||||
}
|
||||
if len(tags) >= 50 {
|
||||
debuglogger.Logf("IAM user tag count exceeds maximum: max=%d", 50)
|
||||
return nil, iamerr.GetAPIError(iamerr.ErrTooManyTags)
|
||||
}
|
||||
if !hasKey {
|
||||
debuglogger.Logf("missing required IAM tag parameter: %s", keyName)
|
||||
return nil, iamerr.MissingParameter(keyName)
|
||||
}
|
||||
if !hasValue {
|
||||
debuglogger.Logf("missing required IAM tag parameter: %s", valueName)
|
||||
return nil, iamerr.MissingParameter(valueName)
|
||||
}
|
||||
if err := validateTag(i, key, value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
normalizedKey := strings.ToLower(key)
|
||||
if _, ok := seen[normalizedKey]; ok {
|
||||
debuglogger.Logf("duplicate IAM tag key: %q", key)
|
||||
return nil, iamerr.GetAPIError(iamerr.ErrDuplicateTagKeys)
|
||||
}
|
||||
seen[normalizedKey] = struct{}{}
|
||||
|
||||
tags = append(tags, types.Tag{Key: key, Value: value})
|
||||
}
|
||||
|
||||
return tags, nil
|
||||
}
|
||||
|
||||
// ValidateUserName checks that userName is non-empty, matches the allowed character set, and fits within maxLength.
|
||||
func ValidateUserName(field, userName string, maxLength int) error {
|
||||
if len(userName) > maxLength {
|
||||
debuglogger.Logf("IAM user name exceeds maximum length: field=%s length=%d max=%d", field, len(userName), maxLength)
|
||||
return iamerr.UserNameTooLong(field, maxLength)
|
||||
}
|
||||
if userName == "" || !userNamePattern.MatchString(userName) {
|
||||
debuglogger.Logf("invalid IAM user name: field=%s value=%q", field, userName)
|
||||
return iamerr.InvalidUserName(field)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidatePath checks that path is a valid IAM path (must start and end with '/') within MaxPathLen.
|
||||
func ValidatePath(field, path string) error {
|
||||
if len(path) > MaxPathLen {
|
||||
debuglogger.Logf("IAM path exceeds maximum length: field=%s length=%d max=%d", field, len(path), MaxPathLen)
|
||||
return iamerr.PathTooLong(field, MaxPathLen)
|
||||
}
|
||||
if !isValidIAMPath(path) {
|
||||
debuglogger.Logf("invalid IAM path: field=%s value=%q", field, path)
|
||||
return iamerr.InvalidPath(field)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidatePathPrefix checks that pathPrefix is a non-empty printable ASCII string starting with '/'.
|
||||
func ValidatePathPrefix(pathPrefix string) error {
|
||||
if pathPrefix == "" || len(pathPrefix) > MaxPathLen || pathPrefix[0] != '/' || !isPrintableASCII(pathPrefix[1:]) {
|
||||
debuglogger.Logf("invalid IAM path prefix: %q", pathPrefix)
|
||||
return iamerr.GetAPIError(iamerr.ErrInvalidPathPrefix)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// BuildUserArn constructs the ARN for an IAM user.
|
||||
func BuildUserArn(accountID, path, userName string) string {
|
||||
return fmt.Sprintf("arn:aws:iam::%s:user%s%s", accountID, path, userName)
|
||||
}
|
||||
|
||||
// GenerateUserID returns a new cryptographically random IAM user ID in the AIDA… format.
|
||||
func GenerateUserID() (string, error) {
|
||||
var b strings.Builder
|
||||
b.Grow(len(userIDPrefix) + userIDRandomLen)
|
||||
b.WriteString(userIDPrefix)
|
||||
|
||||
max := big.NewInt(int64(len(userIDAlphabet)))
|
||||
for range userIDRandomLen {
|
||||
n, err := rand.Int(rand.Reader, max)
|
||||
if err != nil {
|
||||
debuglogger.Logf("failed to generate IAM user ID: %v", err)
|
||||
return "", err
|
||||
}
|
||||
b.WriteByte(userIDAlphabet[n.Int64()])
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func validateTag(index int, key, value string) error {
|
||||
if len(key) > maxTagKeyLen {
|
||||
debuglogger.Logf("IAM tag key exceeds maximum length: index=%d length=%d max=%d", index, len(key), maxTagKeyLen)
|
||||
return iamerr.TagKeyTooLong(index)
|
||||
}
|
||||
if key == "" || !tagKeyPattern.MatchString(key) {
|
||||
debuglogger.Logf("invalid IAM tag key: index=%d value=%q", index, key)
|
||||
return iamerr.InvalidTagKey(index)
|
||||
}
|
||||
if len(value) > maxTagValLen {
|
||||
debuglogger.Logf("IAM tag value exceeds maximum length: index=%d length=%d max=%d", index, len(value), maxTagValLen)
|
||||
return iamerr.TagValueTooLong(index)
|
||||
}
|
||||
if !tagValPattern.MatchString(value) {
|
||||
debuglogger.Logf("invalid IAM tag value: index=%d value=%q", index, value)
|
||||
return iamerr.InvalidTagValue(index)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isValidIAMPath(path string) bool {
|
||||
if path == "" || len(path) > MaxPathLen {
|
||||
return false
|
||||
}
|
||||
if path == "/" {
|
||||
return true
|
||||
}
|
||||
if path[0] != '/' || path[len(path)-1] != '/' {
|
||||
return false
|
||||
}
|
||||
|
||||
return isPrintableASCII(path[1 : len(path)-1])
|
||||
}
|
||||
|
||||
func isPrintableASCII(value string) bool {
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] < 0x21 || value[i] > 0x7e {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
"github.com/versity/versitygw/internal/httpctx"
|
||||
)
|
||||
|
||||
var xmlhdr = []byte(xml.Header)
|
||||
|
||||
const (
|
||||
// HeaderAmznRequestID is the response header that carries the request ID.
|
||||
// Re-exported from iammiddleware so callers only need to import iamapi.
|
||||
HeaderAmznRequestID = iammiddleware.HeaderAmznRequestID
|
||||
maxXMLBodyLen = 4 * 1024 * 1024
|
||||
)
|
||||
|
||||
type Response struct {
|
||||
Data types.ActionResponse
|
||||
Headers map[string]*string
|
||||
Status int
|
||||
}
|
||||
|
||||
type ActionHandler func(ctx fiber.Ctx) (*Response, error)
|
||||
|
||||
func ProcessHandlers(controller ActionHandler, handlers ...fiber.Handler) fiber.Handler {
|
||||
return func(ctx fiber.Ctx) error {
|
||||
if httpctx.ContextKeySkip.IsSet(ctx) {
|
||||
httpctx.ContextKeySkip.Delete(ctx)
|
||||
return ctx.Next()
|
||||
}
|
||||
|
||||
for _, handler := range handlers {
|
||||
if err := handler(ctx); err != nil {
|
||||
return ProcessController(ctx, func(ctx fiber.Ctx) (*Response, error) {
|
||||
return &Response{}, err
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return ProcessController(ctx, controller)
|
||||
}
|
||||
}
|
||||
|
||||
func ProcessController(ctx fiber.Ctx, controller ActionHandler) error {
|
||||
response, err := controller(ctx)
|
||||
if response == nil {
|
||||
response = &Response{}
|
||||
}
|
||||
|
||||
SetResponseHeaders(ctx, response.Headers)
|
||||
requestID := iammiddleware.EnsureRequestID(ctx)
|
||||
|
||||
if err != nil {
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
|
||||
if apiErr, ok := err.(iamerr.APIError); ok {
|
||||
return ctx.Status(apiErr.StatusCode()).Send(apiErr.XMLBody(requestID))
|
||||
}
|
||||
|
||||
debuglogger.InternalError(err)
|
||||
internalErr := iamerr.GetAPIError(iamerr.ErrInternalFailure)
|
||||
return ctx.Status(internalErr.StatusCode()).Send(internalErr.XMLBody(requestID))
|
||||
}
|
||||
|
||||
status := response.Status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
if response.Data == nil {
|
||||
ctx.Status(status)
|
||||
return nil
|
||||
}
|
||||
|
||||
response.Data.SetRequestID(requestID)
|
||||
|
||||
responseBytes, err := xml.Marshal(response.Data)
|
||||
if err != nil {
|
||||
debuglogger.InternalError(err)
|
||||
internalErr := iamerr.GetAPIError(iamerr.ErrInternalFailure)
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
return ctx.Status(internalErr.StatusCode()).Send(internalErr.XMLBody(requestID))
|
||||
}
|
||||
|
||||
msglen := len(xmlhdr) + len(responseBytes)
|
||||
if msglen > maxXMLBodyLen {
|
||||
debuglogger.Logf("XML encoded body len %v exceeds max len %v", msglen, maxXMLBodyLen)
|
||||
internalErr := iamerr.GetAPIError(iamerr.ErrInternalFailure)
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
return ctx.Status(internalErr.StatusCode()).Send(internalErr.XMLBody(requestID))
|
||||
}
|
||||
|
||||
res := make([]byte, 0, msglen)
|
||||
res = append(res, xmlhdr...)
|
||||
res = append(res, responseBytes...)
|
||||
|
||||
ctx.Response().Header.SetContentType(fiber.MIMEApplicationXML)
|
||||
ctx.Response().Header.SetContentLength(msglen)
|
||||
|
||||
return ctx.Status(status).Send(res)
|
||||
}
|
||||
|
||||
func SetResponseHeaders(ctx fiber.Ctx, headers map[string]*string) {
|
||||
if headers == nil {
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Response().Header.DisableNormalizing()
|
||||
for key, val := range headers {
|
||||
if val == nil || *val == "" {
|
||||
continue
|
||||
}
|
||||
ctx.Response().Header.Add(key, *val)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
"github.com/versity/versitygw/iamapi/internal/iamutil"
|
||||
"github.com/versity/versitygw/iamapi/storage"
|
||||
)
|
||||
|
||||
const (
|
||||
iamAPIVersion = "2010-05-08"
|
||||
noVersionSpecified = "NO_VERSION_SPECIFIED"
|
||||
productURL = "https://www.versity.com/products/versitygw/"
|
||||
)
|
||||
|
||||
var unknownOperationBody = []byte("<UnknownOperationException/>\n")
|
||||
|
||||
type IAMApiRouter struct {
|
||||
app *fiber.App
|
||||
store storage.Storer
|
||||
Ctrl IAMApiController
|
||||
actions map[string]ActionHandler
|
||||
rootCreds *RootCredentials
|
||||
}
|
||||
|
||||
func (r *IAMApiRouter) Init() {
|
||||
ctrl := NewController(r.store)
|
||||
r.Ctrl = ctrl
|
||||
|
||||
r.actions = map[string]ActionHandler{
|
||||
"CreateUser": ctrl.CreateUser,
|
||||
"DeleteUser": ctrl.DeleteUser,
|
||||
"GetUser": ctrl.GetUser,
|
||||
"ListUsers": ctrl.ListUsers,
|
||||
"UpdateUser": ctrl.UpdateUser,
|
||||
}
|
||||
|
||||
actionRoute := ProcessHandlers(r.routeAction, iammiddleware.VerifyIAMAuth(r.rootCreds))
|
||||
r.app.Get("/*", iamutil.MatchQueryOrFormArgs("Action"), actionRoute)
|
||||
r.app.Post("/*", iamutil.MatchQueryOrFormArgs("Action"), actionRoute)
|
||||
|
||||
r.app.All("/", r.redirectRoot)
|
||||
r.app.All("*", r.unknownOperation)
|
||||
}
|
||||
|
||||
func (r *IAMApiRouter) routeAction(ctx fiber.Ctx) (*Response, error) {
|
||||
action, _ := iamutil.RequestParam(ctx, "Action")
|
||||
version, versionSpecified := iamutil.RequestParam(ctx, "Version")
|
||||
if !versionSpecified {
|
||||
version = noVersionSpecified
|
||||
}
|
||||
if version != iamAPIVersion {
|
||||
return &Response{}, iamerr.InvalidAction(action, version)
|
||||
}
|
||||
|
||||
handler, ok := r.actions[action]
|
||||
if !ok {
|
||||
return &Response{}, iamerr.InvalidAction(action, version)
|
||||
}
|
||||
|
||||
return handler(ctx)
|
||||
}
|
||||
|
||||
func (r *IAMApiRouter) redirectRoot(ctx fiber.Ctx) error {
|
||||
iammiddleware.EnsureRequestID(ctx)
|
||||
ctx.Set(fiber.HeaderLocation, productURL)
|
||||
ctx.Status(http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *IAMApiRouter) unknownOperation(ctx fiber.Ctx) error {
|
||||
iammiddleware.EnsureRequestID(ctx)
|
||||
return ctx.Status(http.StatusNotFound).Send(unknownOperationBody)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
)
|
||||
|
||||
func TestIAMApiRouter_InitRegistersGetAndPostActionRoutesForAnyPath(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{app: app}
|
||||
router.Init()
|
||||
|
||||
methodCounts := map[string]int{}
|
||||
for _, routes := range app.Stack() {
|
||||
for _, route := range routes {
|
||||
if route.Path != "/*" {
|
||||
continue
|
||||
}
|
||||
methodCounts[route.Method]++
|
||||
}
|
||||
}
|
||||
|
||||
// GET and POST each have an action route plus the all-method fallback;
|
||||
// other methods have only the fallback.
|
||||
if methodCounts[http.MethodGet] != 2 || methodCounts[http.MethodPost] != 2 || methodCounts[http.MethodPut] != 1 {
|
||||
t.Fatalf("wildcard route method counts = %v", methodCounts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_RouteActionDetectsQueryAction(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{
|
||||
actions: map[string]ActionHandler{
|
||||
"GetUser": func(ctx fiber.Ctx) (*Response, error) {
|
||||
return &Response{Status: http.StatusAccepted}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
app.Get("/", ProcessHandlers(router.routeAction))
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/?Action=GetUser&Version="+iamAPIVersion, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusAccepted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_RouteActionDetectsFormAction(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{
|
||||
actions: map[string]ActionHandler{
|
||||
"CreateUser": func(ctx fiber.Ctx) (*Response, error) {
|
||||
return &Response{Status: http.StatusCreated}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
app.Post("/", ProcessHandlers(router.routeAction))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString("Action=CreateUser&Version="+iamAPIVersion))
|
||||
req.Header.Set("Content-Type", fiber.MIMEApplicationForm)
|
||||
resp, err := app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusCreated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_RouteActionValidatesVersionBeforeAction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
target string
|
||||
message string
|
||||
}{
|
||||
{
|
||||
name: "missing version",
|
||||
target: "/?Action=ListUsers",
|
||||
message: "Could not find operation ListUsers for version NO_VERSION_SPECIFIED",
|
||||
},
|
||||
{
|
||||
name: "invalid version",
|
||||
target: "/?Action=ListUsers&Version=this-is-custom-invalid-version",
|
||||
message: "Could not find operation ListUsers for version this-is-custom-invalid-version",
|
||||
},
|
||||
{
|
||||
name: "unknown action",
|
||||
target: "/?Action=ListUserssssss&Version=" + iamAPIVersion,
|
||||
message: "Could not find operation ListUserssssss for version 2010-05-08",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{actions: map[string]ActionHandler{}}
|
||||
app.Get("/", ProcessHandlers(router.routeAction))
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, tt.target, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
requireIAMError(t, resp, http.StatusBadRequest, "Sender", "InvalidAction", tt.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_ActionRoutesMatchAnyPath(t *testing.T) {
|
||||
app := fiber.New(fiber.Config{ErrorHandler: iammiddleware.GlobalErrorHandler})
|
||||
router := &IAMApiRouter{app: app, rootCreds: &testRoot}
|
||||
router.Init()
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/any/nested/path?Action=ListUsers&Version="+iamAPIVersion, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("GET app.Test: %v", err)
|
||||
}
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "MissingAuthenticationToken", "Request is missing Authentication Token")
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/another/path", bytes.NewBufferString("Action=ListUsers&Version="+iamAPIVersion))
|
||||
req.Header.Set("Content-Type", fiber.MIMEApplicationForm)
|
||||
resp, err = app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatalf("POST app.Test: %v", err)
|
||||
}
|
||||
requireIAMError(t, resp, http.StatusForbidden, "Sender", "MissingAuthenticationToken", "Request is missing Authentication Token")
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_RootWithoutActionRedirects(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{app: app}
|
||||
router.Init()
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusFound {
|
||||
t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusFound)
|
||||
}
|
||||
if got := resp.Header.Get("Location"); got != productURL {
|
||||
t.Fatalf("Location = %q, want %q", got, productURL)
|
||||
}
|
||||
if got := resp.Header.Get(HeaderAmznRequestID); got == "" {
|
||||
t.Fatal("missing x-amzn-RequestId")
|
||||
}
|
||||
if got := resp.Header.Get("Content-Length"); got != "0" {
|
||||
t.Fatalf("Content-Length = %q, want 0", got)
|
||||
}
|
||||
if len(body) != 0 {
|
||||
t.Fatalf("body = %q, want empty", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIAMApiRouter_UnmatchedRouteReturnsUnknownOperation(t *testing.T) {
|
||||
app := fiber.New()
|
||||
router := &IAMApiRouter{app: app}
|
||||
router.Init()
|
||||
|
||||
resp, err := app.Test(httptest.NewRequest(http.MethodGet, "/not-an-action-route", nil))
|
||||
if err != nil {
|
||||
t.Fatalf("app.Test: %v", err)
|
||||
}
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", resp.StatusCode, http.StatusNotFound)
|
||||
}
|
||||
if string(body) != string(unknownOperationBody) {
|
||||
t.Fatalf("body = %q, want %q", string(body), string(unknownOperationBody))
|
||||
}
|
||||
if got := resp.Header.Get("Content-Length"); got != strconv.Itoa(len(unknownOperationBody)) {
|
||||
t.Fatalf("Content-Length = %q, want %d", got, len(unknownOperationBody))
|
||||
}
|
||||
if got := resp.Header.Get(HeaderAmznRequestID); got == "" {
|
||||
t.Fatal("missing x-amzn-RequestId")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// 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 iamapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/logger"
|
||||
"github.com/gofiber/fiber/v3/middleware/recover"
|
||||
"github.com/versity/versitygw/debuglogger"
|
||||
"github.com/versity/versitygw/iamapi/internal/iammiddleware"
|
||||
"github.com/versity/versitygw/iamapi/storage"
|
||||
"github.com/versity/versitygw/internal/netutil"
|
||||
)
|
||||
|
||||
const (
|
||||
shutDownDuration = time.Second * 10
|
||||
requestHeaderMaxSize = 8 * 1024
|
||||
)
|
||||
|
||||
// RootCredentials re-exports the type from iammiddleware so callers only need
|
||||
// to import iamapi.
|
||||
type RootCredentials = iammiddleware.RootCredentials
|
||||
|
||||
type CertStorage = netutil.CertStorage
|
||||
|
||||
func NewCertStorage() *CertStorage {
|
||||
return netutil.NewCertStorage()
|
||||
}
|
||||
|
||||
type IAMApiServer struct {
|
||||
Router *IAMApiRouter
|
||||
app *fiber.App
|
||||
store storage.Storer
|
||||
rootCreds *RootCredentials
|
||||
CertStorage *CertStorage
|
||||
quiet bool
|
||||
keepAlive bool
|
||||
health string
|
||||
maxConnections int
|
||||
maxRequests int
|
||||
socketPerm os.FileMode
|
||||
onListen func()
|
||||
}
|
||||
|
||||
func New(store storage.Storer, opts ...Option) (*IAMApiServer, error) {
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("iamapi: storer is required")
|
||||
}
|
||||
|
||||
server := &IAMApiServer{
|
||||
store: store,
|
||||
Router: &IAMApiRouter{
|
||||
store: store,
|
||||
},
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(server)
|
||||
}
|
||||
|
||||
app := fiber.New(fiber.Config{
|
||||
AppName: "versitygw-iam",
|
||||
ServerHeader: "VERSITYGW",
|
||||
DisableKeepalive: !server.keepAlive,
|
||||
ErrorHandler: iammiddleware.GlobalErrorHandler,
|
||||
Concurrency: server.maxConnections,
|
||||
ReadBufferSize: requestHeaderMaxSize,
|
||||
StreamRequestBody: false,
|
||||
})
|
||||
|
||||
server.app = app
|
||||
server.Router.app = app
|
||||
server.Router.rootCreds = server.rootCreds
|
||||
|
||||
app.Use("*", recover.New(recover.Config{
|
||||
EnableStackTrace: true,
|
||||
StackTraceHandler: iammiddleware.StackTraceHandler,
|
||||
}))
|
||||
|
||||
if !server.quiet {
|
||||
app.Use("*", logger.New(logger.Config{
|
||||
Format: "${time} | vgw-iam | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error} | ${queryParams}\n",
|
||||
}))
|
||||
}
|
||||
|
||||
app.Use("*", iammiddleware.RequestIDs())
|
||||
|
||||
if server.health != "" {
|
||||
app.Get(server.health, func(ctx fiber.Ctx) error {
|
||||
return ctx.SendStatus(http.StatusOK)
|
||||
})
|
||||
}
|
||||
|
||||
if server.maxRequests > 0 {
|
||||
app.Use("*", iammiddleware.RateLimiter(server.maxRequests))
|
||||
}
|
||||
|
||||
if debuglogger.IsDebugEnabled() {
|
||||
app.Use("*", iammiddleware.DebugLogger())
|
||||
}
|
||||
|
||||
server.Router.Init()
|
||||
|
||||
return server, nil
|
||||
}
|
||||
|
||||
type Option func(*IAMApiServer)
|
||||
|
||||
func WithTLS(cs *CertStorage) Option {
|
||||
return func(s *IAMApiServer) { s.CertStorage = cs }
|
||||
}
|
||||
|
||||
func WithQuiet() Option {
|
||||
return func(s *IAMApiServer) { s.quiet = true }
|
||||
}
|
||||
|
||||
func WithHealth(health string) Option {
|
||||
return func(s *IAMApiServer) { s.health = health }
|
||||
}
|
||||
|
||||
func WithKeepAlive() Option {
|
||||
return func(s *IAMApiServer) { s.keepAlive = true }
|
||||
}
|
||||
|
||||
func WithConcurrencyLimiter(maxConnections, maxRequests int) Option {
|
||||
return func(s *IAMApiServer) {
|
||||
s.maxConnections = maxConnections
|
||||
s.maxRequests = maxRequests
|
||||
}
|
||||
}
|
||||
|
||||
func WithSocketPerm(perm os.FileMode) Option {
|
||||
return func(s *IAMApiServer) { s.socketPerm = perm }
|
||||
}
|
||||
|
||||
func WithOnListen(fn func()) Option {
|
||||
return func(s *IAMApiServer) { s.onListen = fn }
|
||||
}
|
||||
|
||||
func WithRootUserCreds(root RootCredentials) Option {
|
||||
return func(s *IAMApiServer) {
|
||||
s.rootCreds = &root
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IAMApiServer) ServeMultiPort(ports []string) error {
|
||||
if len(ports) == 0 {
|
||||
return fmt.Errorf("no ports specified")
|
||||
}
|
||||
|
||||
var listeners []net.Listener
|
||||
for _, portSpec := range ports {
|
||||
var ln net.Listener
|
||||
var err error
|
||||
|
||||
if s.CertStorage != nil {
|
||||
ln, err = netutil.NewMultiAddrTLSListener(fiber.NetworkTCP, portSpec, s.CertStorage.GetCertificate, netutil.ListenerOptions{SocketPerm: s.socketPerm})
|
||||
} else {
|
||||
ln, err = netutil.NewMultiAddrListener(fiber.NetworkTCP, portSpec, netutil.ListenerOptions{SocketPerm: s.socketPerm})
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to bind iam listener %s: %w", portSpec, err)
|
||||
}
|
||||
|
||||
listeners = append(listeners, ln)
|
||||
}
|
||||
|
||||
if len(listeners) == 0 {
|
||||
return fmt.Errorf("failed to create any iam listeners")
|
||||
}
|
||||
|
||||
finalListener := netutil.NewMultiListener(listeners...)
|
||||
|
||||
if s.onListen != nil {
|
||||
fn := s.onListen
|
||||
s.app.Hooks().OnListen(func(fiber.ListenData) error {
|
||||
fn()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
return s.app.Listener(finalListener, fiber.ListenConfig{
|
||||
DisableStartupMessage: true,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *IAMApiServer) Shutdown() error {
|
||||
return s.app.ShutdownWithTimeout(shutDownDuration)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// 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 (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
"github.com/versity/versitygw/internal/iamstore"
|
||||
)
|
||||
|
||||
const (
|
||||
iamFile = "iam.json"
|
||||
iamBackupFile = "iam.json.backup"
|
||||
)
|
||||
|
||||
type InternalStore struct {
|
||||
sync.RWMutex
|
||||
engine *iamstore.Engine[iamConfig]
|
||||
}
|
||||
|
||||
var _ Storer = (*InternalStore)(nil)
|
||||
|
||||
func NewInternal(dir string) (Storer, error) {
|
||||
engine, err := iamstore.New(dir, iamFile, iamBackupFile, defaultIAMConfig(), normalizeIAMConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &InternalStore{engine: engine}, nil
|
||||
}
|
||||
|
||||
type iamConfig struct {
|
||||
Users map[string]types.User `json:"users"`
|
||||
}
|
||||
|
||||
func defaultIAMConfig() iamConfig {
|
||||
return iamConfig{Users: map[string]types.User{}}
|
||||
}
|
||||
|
||||
func normalizeIAMConfig(conf *iamConfig) {
|
||||
if conf.Users == nil {
|
||||
conf.Users = make(map[string]types.User)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *InternalStore) CreateUser(_ context.Context, user types.User) (*types.User, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if err := s.engine.StoreIAM(func(data []byte) ([]byte, error) {
|
||||
conf, err := s.engine.ParseIAM(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, ok := conf.Users[user.UserName]; ok {
|
||||
return nil, iamerr.EntityAlreadyExistsUser(user.UserName)
|
||||
}
|
||||
for _, existing := range conf.Users {
|
||||
if existing.UserID == user.UserID {
|
||||
return nil, ErrUserIDAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
conf.Users[user.UserName] = user
|
||||
return json.Marshal(conf)
|
||||
}); err != nil {
|
||||
return nil, unwrapAPIError(err)
|
||||
}
|
||||
|
||||
return cloneUser(user), nil
|
||||
}
|
||||
|
||||
func (s *InternalStore) DeleteUser(_ context.Context, username string) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
err := s.engine.StoreIAM(func(data []byte) ([]byte, error) {
|
||||
conf, err := s.engine.ParseIAM(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, ok := conf.Users[username]; !ok {
|
||||
return nil, iamerr.NoSuchEntityUser(username)
|
||||
}
|
||||
|
||||
delete(conf.Users, username)
|
||||
return json.Marshal(conf)
|
||||
})
|
||||
return unwrapAPIError(err)
|
||||
}
|
||||
|
||||
func (s *InternalStore) GetUser(_ context.Context, username string) (*types.User, error) {
|
||||
s.RLock()
|
||||
defer s.RUnlock()
|
||||
|
||||
conf, err := s.engine.GetIAM()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, ok := conf.Users[username]
|
||||
if !ok {
|
||||
return nil, iamerr.NoSuchEntityUser(username)
|
||||
}
|
||||
|
||||
return cloneUser(user), nil
|
||||
}
|
||||
|
||||
func (s *InternalStore) ListUsers(_ context.Context, input ListUsersInput) (*ListUsersOutput, error) {
|
||||
s.RLock()
|
||||
defer s.RUnlock()
|
||||
|
||||
conf, err := s.engine.GetIAM()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
users := make([]types.User, 0, len(conf.Users))
|
||||
for _, user := range conf.Users {
|
||||
if input.PathPrefix != "" && !strings.HasPrefix(user.Path, input.PathPrefix) {
|
||||
continue
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
sort.Slice(users, func(i, j int) bool {
|
||||
return users[i].UserName < users[j].UserName
|
||||
})
|
||||
|
||||
start := 0
|
||||
if input.Marker != "" {
|
||||
start = len(users)
|
||||
for i, user := range users {
|
||||
if user.UserName == input.Marker {
|
||||
start = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
users = users[start:]
|
||||
|
||||
limit := len(users)
|
||||
if input.MaxItems > 0 && int(input.MaxItems) < limit {
|
||||
limit = int(input.MaxItems)
|
||||
}
|
||||
|
||||
out := &ListUsersOutput{
|
||||
Users: make([]types.User, limit),
|
||||
}
|
||||
copy(out.Users, users[:limit])
|
||||
if limit < len(users) {
|
||||
out.IsTruncated = true
|
||||
out.Marker = out.Users[limit-1].UserName
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *InternalStore) UpdateUser(_ context.Context, input UpdateUserInput) (*types.User, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
var updated types.User
|
||||
if err := s.engine.StoreIAM(func(data []byte) ([]byte, error) {
|
||||
conf, err := s.engine.ParseIAM(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
user, ok := conf.Users[input.UserName]
|
||||
if !ok {
|
||||
return nil, iamerr.NoSuchEntityUser(input.UserName)
|
||||
}
|
||||
|
||||
finalName := user.UserName
|
||||
if input.NewUserName != "" {
|
||||
finalName = input.NewUserName
|
||||
}
|
||||
if finalName != input.UserName {
|
||||
if _, ok := conf.Users[finalName]; ok {
|
||||
return nil, iamerr.EntityAlreadyExistsUser(finalName)
|
||||
}
|
||||
}
|
||||
|
||||
if input.NewPath != "" {
|
||||
user.Path = input.NewPath
|
||||
}
|
||||
if input.NewUserName != "" {
|
||||
user.UserName = input.NewUserName
|
||||
}
|
||||
if input.NewArn != "" {
|
||||
user.Arn = input.NewArn
|
||||
}
|
||||
|
||||
if user.UserName != input.UserName {
|
||||
delete(conf.Users, input.UserName)
|
||||
}
|
||||
conf.Users[user.UserName] = user
|
||||
updated = user
|
||||
|
||||
return json.Marshal(conf)
|
||||
}); err != nil {
|
||||
return nil, unwrapAPIError(err)
|
||||
}
|
||||
|
||||
return cloneUser(updated), nil
|
||||
}
|
||||
|
||||
func cloneUser(user types.User) *types.User {
|
||||
cloned := user
|
||||
cloned.Tags = slices.Clone(user.Tags)
|
||||
return &cloned
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// 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 (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUserIDAlreadyExists = errors.New("iamapi: user id already exists")
|
||||
)
|
||||
|
||||
type ListUsersInput struct {
|
||||
PathPrefix string
|
||||
Marker string
|
||||
MaxItems int32
|
||||
}
|
||||
|
||||
type ListUsersOutput struct {
|
||||
Users []types.User
|
||||
IsTruncated bool
|
||||
Marker string
|
||||
}
|
||||
|
||||
type UpdateUserInput struct {
|
||||
UserName string
|
||||
NewPath string
|
||||
NewUserName string
|
||||
NewArn string
|
||||
}
|
||||
|
||||
// Storer is the IAM API storage backend contract.
|
||||
type Storer interface {
|
||||
CreateUser(ctx context.Context, user types.User) (*types.User, error)
|
||||
DeleteUser(ctx context.Context, username string) error
|
||||
GetUser(ctx context.Context, username string) (*types.User, error)
|
||||
ListUsers(ctx context.Context, input ListUsersInput) (*ListUsersOutput, error)
|
||||
UpdateUser(ctx context.Context, input UpdateUserInput) (*types.User, error)
|
||||
}
|
||||
|
||||
func unwrapAPIError(err error) error {
|
||||
var apiErr iamerr.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
return apiErr
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Dir string
|
||||
Vault VaultConfig
|
||||
}
|
||||
|
||||
func New(cfg Config) (Storer, error) {
|
||||
dir := strings.TrimSpace(cfg.Dir)
|
||||
vaultEndpoint := strings.TrimSpace(cfg.Vault.EndpointURL)
|
||||
|
||||
selected := make([]string, 0, 2)
|
||||
if dir != "" {
|
||||
selected = append(selected, "dir")
|
||||
}
|
||||
if vaultEndpoint != "" {
|
||||
selected = append(selected, "vault")
|
||||
}
|
||||
|
||||
switch len(selected) {
|
||||
case 0:
|
||||
return nil, fmt.Errorf("no IAM storer config specified")
|
||||
case 1:
|
||||
default:
|
||||
return nil, fmt.Errorf("multiple IAM storer configs specified: %s", strings.Join(selected, ", "))
|
||||
}
|
||||
|
||||
switch {
|
||||
case dir != "":
|
||||
store, err := NewInternal(dir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init internal IAM storer: %w", err)
|
||||
}
|
||||
return store, nil
|
||||
case vaultEndpoint != "":
|
||||
store, err := NewVault(cfg.Vault)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init vault IAM storer: %w", err)
|
||||
}
|
||||
return store, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("no IAM storer config specified")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// 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 (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
func TestNewRequiresConfig(t *testing.T) {
|
||||
_, err := New(Config{})
|
||||
if err == nil {
|
||||
t.Fatal("New returned nil error without a storer config")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "no IAM storer config specified") {
|
||||
t.Fatalf("error = %q, want missing storer config", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCreatesInternalStore(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
_, err := New(Config{Dir: dir})
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(dir, "iam.json")); err != nil {
|
||||
t.Fatalf("stat initialized IAM file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRejectsMultipleConfigs(t *testing.T) {
|
||||
_, err := New(Config{
|
||||
Dir: t.TempDir(),
|
||||
Vault: VaultConfig{
|
||||
EndpointURL: "https://vault.example.test",
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("New returned nil error with multiple storer configs")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "multiple IAM storer configs specified") {
|
||||
t.Fatalf("error = %q, want multiple storer configs", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewVaultRequiresAuth(t *testing.T) {
|
||||
_, err := New(Config{
|
||||
Vault: VaultConfig{
|
||||
EndpointURL: "https://vault.example.test",
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("New returned nil error for vault storer without auth credentials")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "vault authentication requires either roleid/rolesecret or root token") {
|
||||
t.Fatalf("error = %q, want auth required error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternalStoreUserCRUDAndPagination(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
store, err := NewInternal(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewInternal: %v", err)
|
||||
}
|
||||
|
||||
created := time.Date(2026, 6, 23, 18, 0, 0, 0, time.UTC)
|
||||
users := []types.User{
|
||||
{
|
||||
Path: "/engineering/",
|
||||
UserName: "alice",
|
||||
UserID: "AIDA22222222222222222",
|
||||
Arn: "arn:aws:iam::000000000000:user/engineering/alice",
|
||||
CreateDate: created,
|
||||
Tags: []types.Tag{
|
||||
{Key: "env", Value: "test"},
|
||||
{Key: "empty", Value: ""},
|
||||
},
|
||||
},
|
||||
{
|
||||
Path: "/engineering/platform/",
|
||||
UserName: "bob",
|
||||
UserID: "AIDA33333333333333333",
|
||||
Arn: "arn:aws:iam::000000000000:user/engineering/platform/bob",
|
||||
CreateDate: created.Add(time.Second),
|
||||
},
|
||||
{
|
||||
Path: "/ops/",
|
||||
UserName: "carol",
|
||||
UserID: "AIDA44444444444444444",
|
||||
Arn: "arn:aws:iam::000000000000:user/ops/carol",
|
||||
CreateDate: created.Add(2 * time.Second),
|
||||
},
|
||||
}
|
||||
for _, user := range users {
|
||||
if _, err := store.CreateUser(ctx, user); err != nil {
|
||||
t.Fatalf("CreateUser(%s): %v", user.UserName, err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := store.CreateUser(ctx, users[0]); !errors.Is(err, iamerr.EntityAlreadyExistsUser("alice")) {
|
||||
t.Fatalf("CreateUser duplicate err = %v, want EntityAlreadyExists", err)
|
||||
}
|
||||
duplicateID := users[2]
|
||||
duplicateID.UserName = "dave"
|
||||
if _, err := store.CreateUser(ctx, duplicateID); !errors.Is(err, ErrUserIDAlreadyExists) {
|
||||
t.Fatalf("CreateUser duplicate id err = %v, want ErrUserIDAlreadyExists", err)
|
||||
}
|
||||
|
||||
got, err := store.GetUser(ctx, "alice")
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser: %v", err)
|
||||
}
|
||||
if got.UserName != "alice" || got.UserID != users[0].UserID {
|
||||
t.Fatalf("GetUser = %#v, want alice with stable id", got)
|
||||
}
|
||||
if !reflect.DeepEqual(got.Tags, users[0].Tags) {
|
||||
t.Fatalf("GetUser tags = %#v, want %#v", got.Tags, users[0].Tags)
|
||||
}
|
||||
|
||||
page1, err := store.ListUsers(ctx, ListUsersInput{PathPrefix: "/engineering/", MaxItems: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("ListUsers page1: %v", err)
|
||||
}
|
||||
if len(page1.Users) != 1 || page1.Users[0].UserName != "alice" || !page1.IsTruncated || page1.Marker != "alice" {
|
||||
t.Fatalf("page1 = %#v, want truncated alice page", page1)
|
||||
}
|
||||
if !reflect.DeepEqual(page1.Users[0].Tags, users[0].Tags) {
|
||||
t.Fatalf("ListUsers tags = %#v, want %#v", page1.Users[0].Tags, users[0].Tags)
|
||||
}
|
||||
|
||||
page2, err := store.ListUsers(ctx, ListUsersInput{PathPrefix: "/engineering/", Marker: page1.Marker, MaxItems: 10})
|
||||
if err != nil {
|
||||
t.Fatalf("ListUsers page2: %v", err)
|
||||
}
|
||||
if len(page2.Users) != 1 || page2.Users[0].UserName != "bob" || page2.IsTruncated {
|
||||
t.Fatalf("page2 = %#v, want final bob page", page2)
|
||||
}
|
||||
|
||||
updated, err := store.UpdateUser(ctx, UpdateUserInput{
|
||||
UserName: "alice",
|
||||
NewPath: "/ops/",
|
||||
NewUserName: "zoe",
|
||||
NewArn: "arn:aws:iam::000000000000:user/ops/zoe",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateUser: %v", err)
|
||||
}
|
||||
if updated.UserName != "zoe" || updated.Path != "/ops/" || updated.Arn != "arn:aws:iam::000000000000:user/ops/zoe" {
|
||||
t.Fatalf("updated = %#v, want renamed/path-updated user", updated)
|
||||
}
|
||||
if updated.UserID != users[0].UserID || !updated.CreateDate.Equal(users[0].CreateDate) {
|
||||
t.Fatalf("updated identity changed: %#v", updated)
|
||||
}
|
||||
if !reflect.DeepEqual(updated.Tags, users[0].Tags) {
|
||||
t.Fatalf("updated tags = %#v, want %#v", updated.Tags, users[0].Tags)
|
||||
}
|
||||
if _, err := store.GetUser(ctx, "alice"); !errors.Is(err, iamerr.NoSuchEntityUser("alice")) {
|
||||
t.Fatalf("GetUser old name err = %v, want NoSuchEntity", err)
|
||||
}
|
||||
if _, err := store.UpdateUser(ctx, UpdateUserInput{UserName: "zoe", NewUserName: "bob"}); !errors.Is(err, iamerr.EntityAlreadyExistsUser("bob")) {
|
||||
t.Fatalf("UpdateUser duplicate err = %v, want EntityAlreadyExists", err)
|
||||
}
|
||||
|
||||
reopened, err := NewInternal(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen NewInternal: %v", err)
|
||||
}
|
||||
reopenedUser, err := reopened.GetUser(ctx, "zoe")
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser after reopen: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(reopenedUser.Tags, users[0].Tags) {
|
||||
t.Fatalf("reopened tags = %#v, want %#v", reopenedUser.Tags, users[0].Tags)
|
||||
}
|
||||
|
||||
if err := reopened.DeleteUser(ctx, "zoe"); err != nil {
|
||||
t.Fatalf("DeleteUser: %v", err)
|
||||
}
|
||||
if err := reopened.DeleteUser(ctx, "zoe"); !errors.Is(err, iamerr.NoSuchEntityUser("zoe")) {
|
||||
t.Fatalf("DeleteUser missing err = %v, want NoSuchEntity", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
// 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 (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
vault "github.com/hashicorp/vault-client-go"
|
||||
"github.com/hashicorp/vault-client-go/schema"
|
||||
"github.com/versity/versitygw/iamapi/iamerr"
|
||||
"github.com/versity/versitygw/iamapi/types"
|
||||
)
|
||||
|
||||
const vaultRequestTimeout = 10 * time.Second
|
||||
|
||||
// VaultConfig holds all configuration options for the Vault-backed IAM storer.
|
||||
type VaultConfig struct {
|
||||
EndpointURL string
|
||||
Namespace string
|
||||
SecretStoragePath string
|
||||
SecretStorageNamespace string
|
||||
AuthMethod string
|
||||
AuthNamespace string
|
||||
MountPath string
|
||||
RootToken string
|
||||
RoleID string
|
||||
RoleSecret string
|
||||
ServerCert string
|
||||
ClientCert string
|
||||
ClientCertKey string
|
||||
}
|
||||
|
||||
// VaultStore is a Vault KV v2-backed implementation of Storer.
|
||||
type VaultStore struct {
|
||||
client *vault.Client
|
||||
authReqOpts []vault.RequestOption
|
||||
kvReqOpts []vault.RequestOption
|
||||
secretStoragePath string
|
||||
creds schema.AppRoleLoginRequest
|
||||
}
|
||||
|
||||
var _ Storer = (*VaultStore)(nil)
|
||||
|
||||
func NewVault(cfg VaultConfig) (Storer, error) {
|
||||
opts := []vault.ClientOption{
|
||||
vault.WithAddress(strings.TrimSpace(cfg.EndpointURL)),
|
||||
vault.WithRequestTimeout(vaultRequestTimeout),
|
||||
}
|
||||
|
||||
serverCert := strings.TrimSpace(cfg.ServerCert)
|
||||
clientCert := strings.TrimSpace(cfg.ClientCert)
|
||||
clientCertKey := strings.TrimSpace(cfg.ClientCertKey)
|
||||
|
||||
if serverCert != "" {
|
||||
tls := vault.TLSConfiguration{}
|
||||
tls.ServerCertificate.FromBytes = []byte(serverCert)
|
||||
if clientCert != "" {
|
||||
if clientCertKey == "" {
|
||||
return nil, fmt.Errorf("client certificate and client certificate key should both be specified")
|
||||
}
|
||||
tls.ClientCertificate.FromBytes = []byte(clientCert)
|
||||
tls.ClientCertificateKey.FromBytes = []byte(clientCertKey)
|
||||
}
|
||||
opts = append(opts, vault.WithTLS(tls))
|
||||
}
|
||||
|
||||
client, err := vault.New(opts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("init vault client: %w", err)
|
||||
}
|
||||
|
||||
authMethod := strings.TrimSpace(cfg.AuthMethod)
|
||||
mountPath := strings.TrimSpace(cfg.MountPath)
|
||||
|
||||
authReqOpts := []vault.RequestOption{}
|
||||
if authMethod != "" {
|
||||
authReqOpts = append(authReqOpts, vault.WithMountPath(authMethod))
|
||||
}
|
||||
|
||||
kvReqOpts := []vault.RequestOption{}
|
||||
if mountPath != "" {
|
||||
kvReqOpts = append(kvReqOpts, vault.WithMountPath(mountPath))
|
||||
}
|
||||
|
||||
// Resolve namespaces: specific namespace overrides the generic fallback.
|
||||
authNS := strings.TrimSpace(cfg.AuthNamespace)
|
||||
secretNS := strings.TrimSpace(cfg.SecretStorageNamespace)
|
||||
fallback := strings.TrimSpace(cfg.Namespace)
|
||||
if authNS == "" {
|
||||
authNS = fallback
|
||||
}
|
||||
if secretNS == "" {
|
||||
secretNS = fallback
|
||||
}
|
||||
|
||||
rootToken := strings.TrimSpace(cfg.RootToken)
|
||||
roleID := strings.TrimSpace(cfg.RoleID)
|
||||
roleSecret := strings.TrimSpace(cfg.RoleSecret)
|
||||
|
||||
// AppRole tokens are namespace-scoped; cross-namespace use requires a root token.
|
||||
if rootToken == "" && authNS != "" && secretNS != "" && authNS != secretNS {
|
||||
return nil, fmt.Errorf(
|
||||
"approle tokens are namespace scoped. auth namespace %q and secret storage namespace %q differ. "+
|
||||
"use the same namespace or authenticate with a root token",
|
||||
authNS, secretNS,
|
||||
)
|
||||
}
|
||||
|
||||
if rootToken == "" && authNS != "" {
|
||||
authReqOpts = append(authReqOpts, vault.WithNamespace(authNS))
|
||||
}
|
||||
if secretNS != "" {
|
||||
kvReqOpts = append(kvReqOpts, vault.WithNamespace(secretNS))
|
||||
}
|
||||
|
||||
creds := schema.AppRoleLoginRequest{
|
||||
RoleId: roleID,
|
||||
SecretId: roleSecret,
|
||||
}
|
||||
|
||||
switch {
|
||||
case rootToken != "":
|
||||
if err := client.SetToken(rootToken); err != nil {
|
||||
return nil, fmt.Errorf("root token authentication failure: %w", err)
|
||||
}
|
||||
case roleID != "":
|
||||
if roleSecret == "" {
|
||||
return nil, fmt.Errorf("role id and role secret must both be specified")
|
||||
}
|
||||
resp, err := client.Auth.AppRoleLogin(context.Background(), creds, authReqOpts...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("approle authentication failure: %w", err)
|
||||
}
|
||||
if err := client.SetToken(resp.Auth.ClientToken); err != nil {
|
||||
return nil, fmt.Errorf("approle authentication set token failure: %w", err)
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("vault authentication requires either roleid/rolesecret or root token")
|
||||
}
|
||||
|
||||
secretStoragePath := strings.TrimSpace(cfg.SecretStoragePath)
|
||||
if secretStoragePath == "" {
|
||||
secretStoragePath = "iam"
|
||||
}
|
||||
|
||||
return &VaultStore{
|
||||
client: client,
|
||||
authReqOpts: authReqOpts,
|
||||
kvReqOpts: kvReqOpts,
|
||||
secretStoragePath: secretStoragePath,
|
||||
creds: creds,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// reAuthIfNeeded attempts AppRole re-authentication when vault returns 403.
|
||||
// It returns nil only when the original error was nil or re-auth succeeded.
|
||||
func (s *VaultStore) reAuthIfNeeded(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !vault.IsErrorStatus(err, http.StatusForbidden) {
|
||||
return err
|
||||
}
|
||||
resp, authErr := s.client.Auth.AppRoleLogin(context.Background(), s.creds, s.authReqOpts...)
|
||||
if authErr != nil {
|
||||
return fmt.Errorf("vault re-authentication failure: %w", authErr)
|
||||
}
|
||||
if err := s.client.SetToken(resp.Auth.ClientToken); err != nil {
|
||||
return fmt.Errorf("vault re-authentication set token failure: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *VaultStore) CreateUser(_ context.Context, user types.User) (*types.User, error) {
|
||||
userMap, err := userToVaultMap(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize user: %w", err)
|
||||
}
|
||||
|
||||
path := s.secretStoragePath + "/" + user.UserName
|
||||
req := schema.KvV2WriteRequest{
|
||||
Data: map[string]any{user.UserName: userMap},
|
||||
Options: map[string]any{
|
||||
"cas": 0,
|
||||
},
|
||||
}
|
||||
|
||||
_, err = s.client.Secrets.KvV2Write(context.Background(), path, req, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "check-and-set") {
|
||||
return nil, iamerr.EntityAlreadyExistsUser(user.UserName)
|
||||
}
|
||||
if reauthErr := s.reAuthIfNeeded(err); reauthErr != nil {
|
||||
return nil, reauthErr
|
||||
}
|
||||
// retry once after re-auth
|
||||
_, err = s.client.Secrets.KvV2Write(context.Background(), path, req, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "check-and-set") {
|
||||
return nil, iamerr.EntityAlreadyExistsUser(user.UserName)
|
||||
}
|
||||
if vault.IsErrorStatus(err, http.StatusForbidden) {
|
||||
return nil, fmt.Errorf("vault 403 permission denied on path %q. check KV mount path and policy. original: %w", path, err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return cloneUser(user), nil
|
||||
}
|
||||
|
||||
func (s *VaultStore) DeleteUser(ctx context.Context, username string) error {
|
||||
if _, err := s.GetUser(ctx, username); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.deleteByPath(username)
|
||||
}
|
||||
|
||||
func (s *VaultStore) GetUser(_ context.Context, username string) (*types.User, error) {
|
||||
path := s.secretStoragePath + "/" + username
|
||||
resp, err := s.client.Secrets.KvV2Read(context.Background(), path, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
||||
return nil, iamerr.NoSuchEntityUser(username)
|
||||
}
|
||||
if reauthErr := s.reAuthIfNeeded(err); reauthErr != nil {
|
||||
return nil, reauthErr
|
||||
}
|
||||
resp, err = s.client.Secrets.KvV2Read(context.Background(), path, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
||||
return nil, iamerr.NoSuchEntityUser(username)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
user, err := parseVaultUser(resp.Data.Data, username)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cloneUser(user), nil
|
||||
}
|
||||
|
||||
func (s *VaultStore) ListUsers(ctx context.Context, input ListUsersInput) (*ListUsersOutput, error) {
|
||||
resp, err := s.client.Secrets.KvV2List(context.Background(), s.secretStoragePath, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
||||
return &ListUsersOutput{Users: []types.User{}}, nil
|
||||
}
|
||||
reauthErr := s.reAuthIfNeeded(err)
|
||||
if reauthErr != nil {
|
||||
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
||||
return &ListUsersOutput{Users: []types.User{}}, nil
|
||||
}
|
||||
return nil, reauthErr
|
||||
}
|
||||
resp, err = s.client.Secrets.KvV2List(context.Background(), s.secretStoragePath, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if vault.IsErrorStatus(err, http.StatusNotFound) {
|
||||
return &ListUsersOutput{Users: []types.User{}}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
users := make([]types.User, 0, len(resp.Data.Keys))
|
||||
for _, key := range resp.Data.Keys {
|
||||
user, err := s.GetUser(ctx, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.PathPrefix != "" && !strings.HasPrefix(user.Path, input.PathPrefix) {
|
||||
continue
|
||||
}
|
||||
users = append(users, *user)
|
||||
}
|
||||
|
||||
sort.Slice(users, func(i, j int) bool {
|
||||
return users[i].UserName < users[j].UserName
|
||||
})
|
||||
|
||||
start := 0
|
||||
if input.Marker != "" {
|
||||
start = len(users)
|
||||
for i, user := range users {
|
||||
if user.UserName == input.Marker {
|
||||
start = i + 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
users = users[start:]
|
||||
|
||||
limit := len(users)
|
||||
if input.MaxItems > 0 && int(input.MaxItems) < limit {
|
||||
limit = int(input.MaxItems)
|
||||
}
|
||||
|
||||
out := &ListUsersOutput{
|
||||
Users: make([]types.User, limit),
|
||||
}
|
||||
copy(out.Users, users[:limit])
|
||||
if limit < len(users) {
|
||||
out.IsTruncated = true
|
||||
out.Marker = out.Users[limit-1].UserName
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *VaultStore) UpdateUser(ctx context.Context, input UpdateUserInput) (*types.User, error) {
|
||||
user, err := s.GetUser(ctx, input.UserName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
finalName := user.UserName
|
||||
if input.NewUserName != "" {
|
||||
finalName = input.NewUserName
|
||||
}
|
||||
|
||||
if finalName != input.UserName {
|
||||
existing, err := s.GetUser(ctx, finalName)
|
||||
if err != nil && !errors.Is(err, iamerr.NoSuchEntityUser(finalName)) {
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
return nil, iamerr.EntityAlreadyExistsUser(finalName)
|
||||
}
|
||||
}
|
||||
|
||||
if input.NewPath != "" {
|
||||
user.Path = input.NewPath
|
||||
}
|
||||
if input.NewUserName != "" {
|
||||
user.UserName = input.NewUserName
|
||||
}
|
||||
if input.NewArn != "" {
|
||||
user.Arn = input.NewArn
|
||||
}
|
||||
|
||||
if user.UserName != input.UserName {
|
||||
// Create at new path first to detect conflicts before deleting the old entry.
|
||||
if _, err := s.CreateUser(ctx, *user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.deleteByPath(input.UserName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// Delete all versions then re-create so CAS=0 succeeds.
|
||||
if err := s.deleteByPath(input.UserName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.CreateUser(ctx, *user); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return cloneUser(*user), nil
|
||||
}
|
||||
|
||||
// deleteByPath permanently removes a secret and all its versions without
|
||||
// checking for existence first.
|
||||
func (s *VaultStore) deleteByPath(username string) error {
|
||||
path := s.secretStoragePath + "/" + username
|
||||
_, err := s.client.Secrets.KvV2DeleteMetadataAndAllVersions(context.Background(), path, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
if reauthErr := s.reAuthIfNeeded(err); reauthErr != nil {
|
||||
return reauthErr
|
||||
}
|
||||
_, err = s.client.Secrets.KvV2DeleteMetadataAndAllVersions(context.Background(), path, s.kvReqOpts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var errInvalidVaultUser = errors.New("invalid user entry in vault secrets engine")
|
||||
|
||||
// userToVaultMap round-trips User through JSON to produce a map[string]any
|
||||
// that vault can store without losing type information on read-back.
|
||||
func userToVaultMap(user types.User) (map[string]any, error) {
|
||||
b, err := json.Marshal(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// parseVaultUser reconstructs a User from the raw map[string]any that vault
|
||||
// returns. The outer key is the username.
|
||||
func parseVaultUser(data map[string]any, username string) (types.User, error) {
|
||||
raw, ok := data[username]
|
||||
if !ok {
|
||||
return types.User{}, errInvalidVaultUser
|
||||
}
|
||||
userMap, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return types.User{}, errInvalidVaultUser
|
||||
}
|
||||
b, err := json.Marshal(userMap)
|
||||
if err != nil {
|
||||
return types.User{}, fmt.Errorf("re-marshal vault user: %w", err)
|
||||
}
|
||||
var user types.User
|
||||
if err := json.Unmarshal(b, &user); err != nil {
|
||||
return types.User{}, fmt.Errorf("unmarshal vault user: %w", err)
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// 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 types
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ActionResponse interface {
|
||||
SetRequestID(string)
|
||||
}
|
||||
|
||||
type ResponseMetadata struct {
|
||||
RequestID string `xml:"RequestId"`
|
||||
}
|
||||
|
||||
type CreateUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ CreateUserResponse"`
|
||||
Result CreateUserResult `xml:"CreateUserResult"`
|
||||
ResponseMetadata ResponseMetadata
|
||||
}
|
||||
|
||||
func (r *CreateUserResponse) SetRequestID(requestID string) {
|
||||
r.ResponseMetadata.RequestID = requestID
|
||||
}
|
||||
|
||||
type CreateUserResult struct {
|
||||
User User
|
||||
}
|
||||
|
||||
type GetUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ GetUserResponse"`
|
||||
Result GetUserResult `xml:"GetUserResult"`
|
||||
ResponseMetadata ResponseMetadata
|
||||
}
|
||||
|
||||
func (r *GetUserResponse) SetRequestID(requestID string) {
|
||||
r.ResponseMetadata.RequestID = requestID
|
||||
}
|
||||
|
||||
type GetUserResult struct {
|
||||
User User
|
||||
}
|
||||
|
||||
type ListUsersResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ ListUsersResponse"`
|
||||
Result ListUsersResult `xml:"ListUsersResult"`
|
||||
ResponseMetadata ResponseMetadata
|
||||
}
|
||||
|
||||
func (r *ListUsersResponse) SetRequestID(requestID string) {
|
||||
r.ResponseMetadata.RequestID = requestID
|
||||
}
|
||||
|
||||
type ListUsersResult struct {
|
||||
Users Users
|
||||
IsTruncated bool
|
||||
Marker string `xml:",omitempty"`
|
||||
}
|
||||
|
||||
type Users struct {
|
||||
Members []User `xml:"member"`
|
||||
}
|
||||
|
||||
type UpdateUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ UpdateUserResponse"`
|
||||
Result UpdateUserResult `xml:"UpdateUserResult"`
|
||||
ResponseMetadata ResponseMetadata
|
||||
}
|
||||
|
||||
func (r *UpdateUserResponse) SetRequestID(requestID string) {
|
||||
r.ResponseMetadata.RequestID = requestID
|
||||
}
|
||||
|
||||
type UpdateUserResult struct {
|
||||
User *User
|
||||
}
|
||||
|
||||
type DeleteUserResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ DeleteUserResponse"`
|
||||
ResponseMetadata ResponseMetadata
|
||||
}
|
||||
|
||||
func (r *DeleteUserResponse) SetRequestID(requestID string) {
|
||||
r.ResponseMetadata.RequestID = requestID
|
||||
}
|
||||
|
||||
type User struct {
|
||||
Path string `xml:",omitempty"`
|
||||
UserName string `xml:",omitempty"`
|
||||
UserID string `xml:"UserId"`
|
||||
Arn string `xml:"Arn"`
|
||||
CreateDate time.Time `xml:"CreateDate"`
|
||||
Tags []Tag `xml:"Tags>member,omitempty"`
|
||||
}
|
||||
|
||||
type Tag struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
Reference in New Issue
Block a user