File: process_arn_resource.go

package info (click to toggle)
golang-github-aws-aws-sdk-go-v2 1.24.1-2~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 554,032 kB
  • sloc: java: 15,941; makefile: 419; sh: 175
file content (568 lines) | stat: -rw-r--r-- 17,368 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package customizations

import (
	"context"
	"fmt"
	"net/url"
	"strings"

	"github.com/aws/smithy-go/middleware"
	"github.com/aws/smithy-go/transport/http"

	"github.com/aws/aws-sdk-go-v2/aws"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/internal/v4a"
	"github.com/aws/aws-sdk-go-v2/service/internal/s3shared"
	"github.com/aws/aws-sdk-go-v2/service/internal/s3shared/arn"
	s3arn "github.com/aws/aws-sdk-go-v2/service/s3/internal/arn"
	"github.com/aws/aws-sdk-go-v2/service/s3/internal/endpoints"
)

const (
	s3AccessPoint  = "s3-accesspoint"
	s3ObjectLambda = "s3-object-lambda"
)

// processARNResource is used to process an ARN resource.
type processARNResource struct {

	// UseARNRegion indicates if region parsed from an ARN should be used.
	UseARNRegion bool

	// UseAccelerate indicates if s3 transfer acceleration is enabled
	UseAccelerate bool

	// EndpointResolver used to resolve endpoints. This may be a custom endpoint resolver
	EndpointResolver EndpointResolver

	// EndpointResolverOptions used by endpoint resolver
	EndpointResolverOptions EndpointResolverOptions

	// DisableMultiRegionAccessPoints indicates multi-region access point support is disabled
	DisableMultiRegionAccessPoints bool
}

// ID returns the middleware ID.
func (*processARNResource) ID() string { return "S3:ProcessARNResource" }

func (m *processARNResource) HandleSerialize(
	ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler,
) (
	out middleware.SerializeOutput, metadata middleware.Metadata, err error,
) {
	if !awsmiddleware.GetRequiresLegacyEndpoints(ctx) {
		return next.HandleSerialize(ctx, in)
	}

	// check if arn was provided, if not skip this middleware
	arnValue, ok := s3shared.GetARNResourceFromContext(ctx)
	if !ok {
		return next.HandleSerialize(ctx, in)
	}

	req, ok := in.Request.(*http.Request)
	if !ok {
		return out, metadata, fmt.Errorf("unknown request type %T", req)
	}

	// parse arn into an endpoint arn wrt to service
	resource, err := s3arn.ParseEndpointARN(arnValue)
	if err != nil {
		return out, metadata, err
	}

	// build a resource request struct
	resourceRequest := s3shared.ResourceRequest{
		Resource:      resource,
		UseARNRegion:  m.UseARNRegion,
		UseFIPS:       m.EndpointResolverOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled,
		RequestRegion: awsmiddleware.GetRegion(ctx),
		SigningRegion: awsmiddleware.GetSigningRegion(ctx),
		PartitionID:   awsmiddleware.GetPartitionID(ctx),
	}

	// switch to correct endpoint updater
	switch tv := resource.(type) {
	case arn.AccessPointARN:
		// multi-region arns do not need to validate for cross partition request
		if len(tv.Region) != 0 {
			// validate resource request
			if err := validateRegionForResourceRequest(resourceRequest); err != nil {
				return out, metadata, err
			}
		}

		// Special handling for region-less ap-arns.
		if len(tv.Region) == 0 {
			// check if multi-region arn support is disabled
			if m.DisableMultiRegionAccessPoints {
				return out, metadata, fmt.Errorf("Invalid configuration, Multi-Region access point ARNs are disabled")
			}

			// Do not allow dual-stack configuration with multi-region arns.
			if m.EndpointResolverOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled {
				return out, metadata, s3shared.NewClientConfiguredForDualStackError(tv,
					resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
			}
		}

		// check if accelerate
		if m.UseAccelerate {
			return out, metadata, s3shared.NewClientConfiguredForAccelerateError(tv,
				resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		// fetch arn region to resolve request
		resolveRegion := tv.Region
		// check if request region is FIPS
		if resourceRequest.UseFIPS && len(resolveRegion) == 0 {
			// Do not allow Fips support within multi-region arns.
			return out, metadata, s3shared.NewClientConfiguredForFIPSError(
				tv, resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		var requestBuilder func(context.Context, accesspointOptions) (context.Context, error)
		if len(resolveRegion) == 0 {
			requestBuilder = buildMultiRegionAccessPointsRequest
		} else {
			requestBuilder = buildAccessPointRequest
		}

		// build request as per accesspoint builder
		ctx, err = requestBuilder(ctx, accesspointOptions{
			processARNResource: *m,
			request:            req,
			resource:           tv,
			resolveRegion:      resolveRegion,
			partitionID:        resourceRequest.PartitionID,
			requestRegion:      resourceRequest.RequestRegion,
		})
		if err != nil {
			return out, metadata, err
		}

	case arn.S3ObjectLambdaAccessPointARN:
		// validate region for resource request
		if err := validateRegionForResourceRequest(resourceRequest); err != nil {
			return out, metadata, err
		}

		// check if accelerate
		if m.UseAccelerate {
			return out, metadata, s3shared.NewClientConfiguredForAccelerateError(tv,
				resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		// check if dualstack
		if m.EndpointResolverOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled {
			return out, metadata, s3shared.NewClientConfiguredForDualStackError(tv,
				resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		// fetch arn region to resolve request
		resolveRegion := tv.Region

		// build access point request
		ctx, err = buildS3ObjectLambdaAccessPointRequest(ctx, accesspointOptions{
			processARNResource: *m,
			request:            req,
			resource:           tv.AccessPointARN,
			resolveRegion:      resolveRegion,
			partitionID:        resourceRequest.PartitionID,
			requestRegion:      resourceRequest.RequestRegion,
		})
		if err != nil {
			return out, metadata, err
		}

	// process outpost accesspoint ARN
	case arn.OutpostAccessPointARN:
		// validate region for resource request
		if err := validateRegionForResourceRequest(resourceRequest); err != nil {
			return out, metadata, err
		}

		// check if accelerate
		if m.UseAccelerate {
			return out, metadata, s3shared.NewClientConfiguredForAccelerateError(tv,
				resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		// check if dual stack
		if m.EndpointResolverOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled {
			return out, metadata, s3shared.NewClientConfiguredForDualStackError(tv,
				resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
		}

		// check if request region is FIPS
		if resourceRequest.UseFIPS {
			return out, metadata, s3shared.NewFIPSConfigurationError(tv, resourceRequest.PartitionID,
				resourceRequest.RequestRegion, nil)
		}

		// build outpost access point request
		ctx, err = buildOutpostAccessPointRequest(ctx, outpostAccessPointOptions{
			processARNResource: *m,
			resource:           tv,
			request:            req,
			partitionID:        resourceRequest.PartitionID,
			requestRegion:      resourceRequest.RequestRegion,
		})
		if err != nil {
			return out, metadata, err
		}

	default:
		return out, metadata, s3shared.NewInvalidARNError(resource, nil)
	}

	return next.HandleSerialize(ctx, in)
}

// validate if s3 resource and request region config is compatible.
func validateRegionForResourceRequest(resourceRequest s3shared.ResourceRequest) error {
	// check if resourceRequest leads to a cross partition error
	v, err := resourceRequest.IsCrossPartition()
	if err != nil {
		return err
	}
	if v {
		// if cross partition
		return s3shared.NewClientPartitionMismatchError(resourceRequest.Resource,
			resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
	}

	// check if resourceRequest leads to a cross region error
	if !resourceRequest.AllowCrossRegion() && resourceRequest.IsCrossRegion() {
		// if cross region, but not use ARN region is not enabled
		return s3shared.NewClientRegionMismatchError(resourceRequest.Resource,
			resourceRequest.PartitionID, resourceRequest.RequestRegion, nil)
	}

	return nil
}

// === Accesspoint ==========

type accesspointOptions struct {
	processARNResource
	request       *http.Request
	resource      arn.AccessPointARN
	resolveRegion string
	partitionID   string
	requestRegion string
}

func buildAccessPointRequest(ctx context.Context, options accesspointOptions) (context.Context, error) {
	tv := options.resource
	req := options.request
	resolveRegion := options.resolveRegion

	resolveService := tv.Service

	ero := options.EndpointResolverOptions
	ero.Logger = middleware.GetLogger(ctx)
	ero.ResolvedRegion = "" // clear endpoint option's resolved region so that we resolve using the passed in region

	// resolve endpoint
	endpoint, err := options.EndpointResolver.ResolveEndpoint(resolveRegion, ero)
	if err != nil {
		return ctx, s3shared.NewFailedToResolveEndpointError(
			tv,
			options.partitionID,
			options.requestRegion,
			err,
		)
	}

	// assign resolved endpoint url to request url
	req.URL, err = url.Parse(endpoint.URL)
	if err != nil {
		return ctx, fmt.Errorf("failed to parse endpoint URL: %w", err)
	}

	if len(endpoint.SigningName) != 0 && endpoint.Source == aws.EndpointSourceCustom {
		ctx = awsmiddleware.SetSigningName(ctx, endpoint.SigningName)
	} else {
		// Must sign with s3-object-lambda
		ctx = awsmiddleware.SetSigningName(ctx, resolveService)
	}

	if len(endpoint.SigningRegion) != 0 {
		ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion)
	} else {
		ctx = awsmiddleware.SetSigningRegion(ctx, resolveRegion)
	}

	// update serviceID to "s3-accesspoint"
	ctx = awsmiddleware.SetServiceID(ctx, s3AccessPoint)

	// disable host prefix behavior
	ctx = http.DisableEndpointHostPrefix(ctx, true)

	// remove the serialized arn in place of /{Bucket}
	ctx = setBucketToRemoveOnContext(ctx, tv.String())

	// skip arn processing, if arn region resolves to a immutable endpoint
	if endpoint.HostnameImmutable {
		return ctx, nil
	}

	updateS3HostForS3AccessPoint(req)

	ctx, err = buildAccessPointHostPrefix(ctx, req, tv)
	if err != nil {
		return ctx, err
	}

	return ctx, nil
}

func buildS3ObjectLambdaAccessPointRequest(ctx context.Context, options accesspointOptions) (context.Context, error) {
	tv := options.resource
	req := options.request
	resolveRegion := options.resolveRegion

	resolveService := tv.Service

	ero := options.EndpointResolverOptions
	ero.Logger = middleware.GetLogger(ctx)
	ero.ResolvedRegion = "" // clear endpoint options resolved region so we resolve the passed in region

	// resolve endpoint
	endpoint, err := options.EndpointResolver.ResolveEndpoint(resolveRegion, ero)
	if err != nil {
		return ctx, s3shared.NewFailedToResolveEndpointError(
			tv,
			options.partitionID,
			options.requestRegion,
			err,
		)
	}

	// assign resolved endpoint url to request url
	req.URL, err = url.Parse(endpoint.URL)
	if err != nil {
		return ctx, fmt.Errorf("failed to parse endpoint URL: %w", err)
	}

	if len(endpoint.SigningName) != 0 && endpoint.Source == aws.EndpointSourceCustom {
		ctx = awsmiddleware.SetSigningName(ctx, endpoint.SigningName)
	} else {
		// Must sign with s3-object-lambda
		ctx = awsmiddleware.SetSigningName(ctx, resolveService)
	}

	if len(endpoint.SigningRegion) != 0 {
		ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion)
	} else {
		ctx = awsmiddleware.SetSigningRegion(ctx, resolveRegion)
	}

	// update serviceID to "s3-object-lambda"
	ctx = awsmiddleware.SetServiceID(ctx, s3ObjectLambda)

	// disable host prefix behavior
	ctx = http.DisableEndpointHostPrefix(ctx, true)

	// remove the serialized arn in place of /{Bucket}
	ctx = setBucketToRemoveOnContext(ctx, tv.String())

	// skip arn processing, if arn region resolves to a immutable endpoint
	if endpoint.HostnameImmutable {
		return ctx, nil
	}

	if endpoint.Source == aws.EndpointSourceServiceMetadata {
		updateS3HostForS3ObjectLambda(req)
	}

	ctx, err = buildAccessPointHostPrefix(ctx, req, tv)
	if err != nil {
		return ctx, err
	}

	return ctx, nil
}

func buildMultiRegionAccessPointsRequest(ctx context.Context, options accesspointOptions) (context.Context, error) {
	const s3GlobalLabel = "s3-global."
	const accesspointLabel = "accesspoint."

	tv := options.resource
	req := options.request
	resolveService := tv.Service
	resolveRegion := options.requestRegion
	arnPartition := tv.Partition

	// resolve endpoint
	ero := options.EndpointResolverOptions
	ero.Logger = middleware.GetLogger(ctx)

	endpoint, err := options.EndpointResolver.ResolveEndpoint(resolveRegion, ero)
	if err != nil {
		return ctx, s3shared.NewFailedToResolveEndpointError(
			tv,
			options.partitionID,
			options.requestRegion,
			err,
		)
	}

	// set signing region and version for MRAP
	endpoint.SigningRegion = "*"
	ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion)
	ctx = SetSignerVersion(ctx, v4a.Version)

	if len(endpoint.SigningName) != 0 {
		ctx = awsmiddleware.SetSigningName(ctx, endpoint.SigningName)
	} else {
		ctx = awsmiddleware.SetSigningName(ctx, resolveService)
	}

	// skip arn processing, if arn region resolves to a immutable endpoint
	if endpoint.HostnameImmutable {
		return ctx, nil
	}

	// modify endpoint host to use s3-global host prefix
	scheme := strings.SplitN(endpoint.URL, "://", 2)
	dnsSuffix, err := endpoints.GetDNSSuffix(arnPartition, ero)
	if err != nil {
		return ctx, fmt.Errorf("Error determining dns suffix from arn partition, %w", err)
	}
	// set url as per partition
	endpoint.URL = scheme[0] + "://" + s3GlobalLabel + dnsSuffix

	// assign resolved endpoint url to request url
	req.URL, err = url.Parse(endpoint.URL)
	if err != nil {
		return ctx, fmt.Errorf("failed to parse endpoint URL: %w", err)
	}

	// build access point host prefix
	accessPointHostPrefix := tv.AccessPointName + "." + accesspointLabel

	// add host prefix to url
	req.URL.Host = accessPointHostPrefix + req.URL.Host
	if len(req.Host) > 0 {
		req.Host = accessPointHostPrefix + req.Host
	}

	// validate the endpoint host
	if err := http.ValidateEndpointHost(req.URL.Host); err != nil {
		return ctx, fmt.Errorf("endpoint validation error: %w, when using arn %v", err, tv)
	}

	// disable host prefix behavior
	ctx = http.DisableEndpointHostPrefix(ctx, true)

	// remove the serialized arn in place of /{Bucket}
	ctx = setBucketToRemoveOnContext(ctx, tv.String())

	return ctx, nil
}

func buildAccessPointHostPrefix(ctx context.Context, req *http.Request, tv arn.AccessPointARN) (context.Context, error) {
	// add host prefix for access point
	accessPointHostPrefix := tv.AccessPointName + "-" + tv.AccountID + "."
	req.URL.Host = accessPointHostPrefix + req.URL.Host
	if len(req.Host) > 0 {
		req.Host = accessPointHostPrefix + req.Host
	}

	// validate the endpoint host
	if err := http.ValidateEndpointHost(req.URL.Host); err != nil {
		return ctx, s3shared.NewInvalidARNError(tv, err)
	}

	return ctx, nil
}

// ====== Outpost Accesspoint ========

type outpostAccessPointOptions struct {
	processARNResource
	request       *http.Request
	resource      arn.OutpostAccessPointARN
	partitionID   string
	requestRegion string
}

func buildOutpostAccessPointRequest(ctx context.Context, options outpostAccessPointOptions) (context.Context, error) {
	tv := options.resource
	req := options.request

	resolveRegion := tv.Region
	resolveService := tv.Service
	endpointsID := resolveService
	if strings.EqualFold(resolveService, "s3-outposts") {
		// assign endpoints ID as "S3"
		endpointsID = "s3"
	}

	ero := options.EndpointResolverOptions
	ero.Logger = middleware.GetLogger(ctx)
	ero.ResolvedRegion = ""

	// resolve regional endpoint for resolved region.
	endpoint, err := options.EndpointResolver.ResolveEndpoint(resolveRegion, ero)
	if err != nil {
		return ctx, s3shared.NewFailedToResolveEndpointError(
			tv,
			options.partitionID,
			options.requestRegion,
			err,
		)
	}

	// assign resolved endpoint url to request url
	req.URL, err = url.Parse(endpoint.URL)
	if err != nil {
		return ctx, fmt.Errorf("failed to parse endpoint URL: %w", err)
	}

	// assign resolved service from arn as signing name
	if len(endpoint.SigningName) != 0 && endpoint.Source == aws.EndpointSourceCustom {
		ctx = awsmiddleware.SetSigningName(ctx, endpoint.SigningName)
	} else {
		ctx = awsmiddleware.SetSigningName(ctx, resolveService)
	}

	if len(endpoint.SigningRegion) != 0 {
		// redirect signer to use resolved endpoint signing name and region
		ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion)
	} else {
		ctx = awsmiddleware.SetSigningRegion(ctx, resolveRegion)
	}

	// update serviceID to resolved service id
	ctx = awsmiddleware.SetServiceID(ctx, resolveService)

	// disable host prefix behavior
	ctx = http.DisableEndpointHostPrefix(ctx, true)

	// remove the serialized arn in place of /{Bucket}
	ctx = setBucketToRemoveOnContext(ctx, tv.String())

	// skip further customizations, if arn region resolves to a immutable endpoint
	if endpoint.HostnameImmutable {
		return ctx, nil
	}

	updateHostPrefix(req, endpointsID, resolveService)

	// add host prefix for s3-outposts
	outpostAPHostPrefix := tv.AccessPointName + "-" + tv.AccountID + "." + tv.OutpostID + "."
	req.URL.Host = outpostAPHostPrefix + req.URL.Host
	if len(req.Host) > 0 {
		req.Host = outpostAPHostPrefix + req.Host
	}

	// validate the endpoint host
	if err := http.ValidateEndpointHost(req.URL.Host); err != nil {
		return ctx, s3shared.NewInvalidARNError(tv, err)
	}

	return ctx, nil
}