1package customizations
2
3import (
4	"context"
5	"fmt"
6
7	"github.com/aws/smithy-go/middleware"
8
9	"github.com/aws/aws-sdk-go-v2/service/internal/s3shared"
10)
11
12// BackfillInput validates and backfill's values from ARN into request serializable input.
13// This middleware must be executed after `ARNLookup` and before `inputValidationMiddleware`.
14type BackfillInput struct {
15
16	// CopyInput creates a copy of input to be modified, this ensures the original input is not modified.
17	CopyInput func(interface{}) (interface{}, error)
18
19	// BackfillAccountID points to a function that validates the input for accountID. If absent, it populates the
20	// accountID and returns a copy. If present, but different than passed in accountID value throws an error
21	BackfillAccountID func(interface{}, string) error
22}
23
24// ID representing the middleware
25func (m *BackfillInput) ID() string {
26	return "S3Control:BackfillInput"
27}
28
29// HandleInitialize handles the middleware behavior in an Initialize step.
30func (m *BackfillInput) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) (
31	out middleware.InitializeOutput, metadata middleware.Metadata, err error,
32) {
33	// fetch arn from context
34	av, ok := s3shared.GetARNResourceFromContext(ctx)
35	if !ok {
36		return next.HandleInitialize(ctx, in)
37	}
38
39	// if not supported, move to next
40	if m.BackfillAccountID == nil {
41		return next.HandleInitialize(ctx, in)
42	}
43
44	// check if input is already cloned
45	if !s3shared.IsClonedInput(ctx) {
46		// create a copy of input, and assign it on params
47		in.Parameters, err = m.CopyInput(in.Parameters)
48		if err != nil {
49			return out, metadata, fmt.Errorf("error creating a copy of input")
50		}
51		// set clone key on context
52		ctx = s3shared.SetClonedInputKey(ctx, true)
53	}
54
55	// backfill account id
56	err = m.BackfillAccountID(in.Parameters, av.AccountID)
57	if err != nil {
58		return out, metadata, fmt.Errorf("invalid ARN, %w", err)
59	}
60
61	return next.HandleInitialize(ctx, in)
62}
63