Lite.pm

filter: Statementstmt 96.0% 49 / 51 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 17 / 17 Podpod n/a totaltotal 97.0% 66 / 68 CC 1 SCAR 0.2
CC
1
Cov
96%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Lite/Policies.pm ↑ Summary Lite/Constants.pm »
1 package Amazon::S3::Lite;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use Amazon::Signature4::Lite;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Amazon::S3::Lite::Credentials;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use Amazon::S3::Lite::Logger;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use Amazon::S3::Lite::Constants qw(:booleans);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Digest::MD5 qw(md5_base64 md5);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 3 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 3 ▶use List::Util qw(pairs);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use MIME::Base64 qw(encode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use Scalar::Util qw(blessed openhandle reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use URI::Escape qw(uri_escape_utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 0 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
21 use JSON::PP;
22  
23 use Role::Tiny::With;
24 with 'Amazon::S3::Lite::Policies';
25  
26 our $VERSION = '1.3.3';
27  
28 ########################################################################
29 sub new {
30 ########################################################################
31 my ( $class, @args ) = @_;
32  
33 my $options = ref $args[0] ? $args[0] : {@args};
34  
35 my $self = bless $options, $class;
36  
37 $self->{host} //= 's3.amazonaws.com';
38 $self->{secure} //= $TRUE;
39 $self->{timeout} //= 30;
40 $self->{region} //= 'us-east-1';
41 $self->{last_status} = q{};
42  
43 $self->_init_logger;
44 $self->_init_credentials;
45 $self->_init_ua;
46  
47 return $self;
48 }
49  
50 ########################################################################
51 # Logger setup
52 # Priority: caller-supplied object -> Log::Log4perl (if available) ->
53 # minimal STDERR logger
54 ########################################################################
55 sub _init_logger {
56 ########################################################################
57 my ($self) = @_;
58  
59 my $logger = $self->{logger};
60  
61 if ( $logger && blessed $logger ) {
62 # Validate it quacks like a logger
63 for my $method (qw(trace debug info warn error)) {
64 croak "logger object must implement '$method'"
65 if !$logger->can($method);
66 }
67  
68 return;
69 }
70  
71 my $log4perl = eval {
72 require Log::Log4perl;
73 1;
74 };
75  
76 my $log_level = $self->{log_level} // 'warn';
77 $self->{log_level} = $log_level;
78  
79 if ($log4perl) {
80 if ( !Log::Log4perl->initialized ) {
81 Log::Log4perl->easy_init( { level => uc $log_level } );
82 }
83  
84 $self->{logger} = Log::Log4perl->get_logger(__PACKAGE__);
85 return;
86 }
87  
88 # Fall back to minimal STDERR logger
89 $self->{logger} = Amazon::S3::Lite::Logger->new( log_level => $log_level );
90  
91 return;
92 }
93  
94 ########################################################################
95 # Credential resolution
96 # Priority: explicit credentials object -> constructor args ->
97 # environment variables -> Amazon::Credentials (if available)
98 ########################################################################
99 sub _init_credentials {
100 ########################################################################
101 my ($self) = @_;
102  
103 # 1. Caller-supplied credentials object (duck-typed)
104 if ( my $creds = $self->{credentials} ) {
105 croak "credential object is not blessed.\n"
106 if !blessed $creds;
107  
108 foreach (qw(aws_access_key_id aws_secret_access_key token)) {
109 my $sub = $creds->can($_) // $creds->can("get_$_");
110  
111 croak "credentials object must implement $_ or get_$_\n"
112 if !$sub;
113 }
114  
115 $self->{credentials} = $creds;
116  
117 return;
118 }
119  
120 # 2. Explicit constructor args
121 if ( $self->{aws_access_key_id} && $self->{aws_secret_access_key} ) {
122 $self->{credentials} = Amazon::S3::Lite::Credentials->new(
123 aws_access_key_id => delete $self->{aws_access_key_id},
124 aws_secret_access_key => delete $self->{aws_secret_access_key},
125 token => delete $self->{token},
126 );
127 return;
128 }
129  
130 # 3. Environment variables
131 if ( $ENV{AWS_ACCESS_KEY_ID} && $ENV{AWS_SECRET_ACCESS_KEY} ) {
132 $self->{credentials} = Amazon::S3::Lite::Credentials->new(
133 aws_access_key_id => $ENV{AWS_ACCESS_KEY_ID},
134 aws_secret_access_key => $ENV{AWS_SECRET_ACCESS_KEY},
135 token => $ENV{AWS_SESSION_TOKEN},
136 );
137 return;
138 }
139  
140 # 4. Amazon::Credentials (covers IAM roles, ECS task roles,
141 # ~/.aws/credentials, etc.)
142 if ( eval { require Amazon::Credentials; 1 } ) {
143 $self->{credentials} = Amazon::Credentials->new;
144 return;
145 }
146  
147 croak 'No AWS credentials found. Supply aws_access_key_id/'
148 . 'aws_secret_access_key, set AWS_ACCESS_KEY_ID/'
149 . 'AWS_SECRET_ACCESS_KEY environment variables, '
150 . 'or install Amazon::Credentials for IAM role support.';
151 }
152  
153 ########################################################################
154 # HTTP::Tiny instance - one per object, keep-alive enabled
155 ########################################################################
156 sub _init_ua {
157 ########################################################################
158 my ($self) = @_;
159  
160 $self->{ua} = HTTP::Tiny->new(
161 timeout => $self->{timeout},
162 verify_SSL => $self->{secure},
163 );
164  
165 return;
166 }
167  
168 ########################################################################
169 # Accessors
170 ########################################################################
171 sub logger { return $_[0]->{logger} }
172 sub log_level { return $_[0]->{log_level}; }
173 sub ua { return $_[0]->{ua} }
174 sub region { return $_[0]->{region} }
175 sub host { return $_[0]->{host} }
176 sub credentials { return $_[0]->{credentials} }
177 sub last_status { return $_[0]->{last_status} }
178  
179 ########################################################################
180 # Build a fresh signer from current credentials.
181 # Called per-request so that rotating credentials (Lambda IAM roles)
182 # are always current.
183 ########################################################################
184 sub _signer {
185 ########################################################################
186 my ( $self, $region ) = @_;
187  
188 my $creds = $self->credentials;
189  
190 my $access_key
191 = $creds->can('get_aws_access_key_id')
192 ? $creds->get_aws_access_key_id
193 : $creds->aws_access_key_id;
194  
195 my $secret_key
196 = $creds->can('get_aws_secret_access_key')
197 ? $creds->get_aws_secret_access_key
198 : $creds->aws_secret_access_key;
199  
200 my $token_sub = $creds->can('get_token') // $creds->can('token');
201 my $token = $token_sub ? $token_sub->($creds) : undef;
202  
203 return Amazon::Signature4::Lite->new(
204 access_key => $access_key,
205 secret_key => $secret_key,
206 session_token => $token,
207 region => $region // $self->region,
208 service => 's3',
209 );
210 }
211  
212 ########################################################################
213 # Build the endpoint URL for a bucket/key
214 ########################################################################
215 sub _endpoint {
216 ########################################################################
217 my ( $self, $bucket, $key ) = @_;
218  
219 my $scheme = $self->{secure} ? 'https' : 'http';
220 my $host = $self->host;
221  
222 # Path-style URL: https://s3.amazonaws.com/bucket/key
223 # (virtual-hosted style omitted for simplicity; path-style works
224 # everywhere and avoids SSL cert issues with dotted bucket names)
225 my $url = "$scheme://$host";
226  
227 if ( defined $bucket && length $bucket ) {
228 $url .= "/$bucket";
229 }
230  
231 if ( defined $key && length $key ) {
232 $url .= q{/} . _encode_key($key);
233 }
234  
235 return $url;
236 }
237  
238 ########################################################################
239 # URI-encode an S3 key, preserving '/' separators
240 ########################################################################
241 sub _encode_key {
242 ########################################################################
243 my ($key) = @_;
244  
245 return join q{/}, map { uri_escape_utf8( $_, '^A-Za-z0-9\-._~' ) }
246 split m{/}, $key, -1;
247 }
248  
249 ########################################################################
250 sub _request {
251 ########################################################################
252 my ( $self, $method, $url, $headers, $content, $extra, $region ) = @_;
253  
254 $region //= $self->region;
255 $headers //= {};
256 $content //= q{};
257 $extra //= {};
258  
259 $self->{last_status} = q{};
260  
261 my $content_is_coderef = ref $content eq 'CODE';
262  
263 # sign — returns merged headers ready for HTTP::Tiny
264 my $signed = $self->_signer($region)->sign(
265 method => $method,
266 url => $url,
267 headers => $headers,
268 payload => $content_is_coderef ? q{} : $content,
269 payload_hash => $extra->{payload_hash},
270 );
271  
272 # HTTP::Tiny sets Host itself — remove to avoid duplicate header error
273 delete $signed->{host};
274  
275 $self->logger->debug("$method $url");
276  
277 my $options = { headers => $signed };
278  
279 if ( length $content || $content_is_coderef ) {
280 $options->{content} = $content;
281 }
282  
283 if ( $extra->{data_callback} ) {
284 $options->{data_callback} = $extra->{data_callback};
285 }
286  
287 my $response = $self->ua->request( $method, $url, $options );
288  
289 $self->logger->debug( sprintf 'Response: %s %s', $response->{status}, $response->{reason} );
290  
291 $self->{last_status} = $response->{status};
292  
293 return $response;
294 }
295  
296 ########################################################################
297 # head_object( $bucket, $key )
298 #
299 # Fetches metadata for an object without retrieving the body.
300 # Returns undef if the key does not exist (404).
301 # Returns a hashref with content_type, content_length, etag,
302 # last_modified, and metadata (x-amz-meta-* headers).
303 ########################################################################
304 sub head_object {
305 ########################################################################
306 my ( $self, $bucket, $key ) = @_;
307  
308 croak 'bucket is required'
309 if !defined $bucket || !length $bucket;
310  
311 croak 'key is required'
312 if !defined $key || !length $key;
313  
314 my $url = $self->_endpoint( $bucket, $key );
315 my $response = $self->_request( 'HEAD', $url );
316  
317 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
318 if _is_not_found($response);
319  
320 $self->_croak_on_error( $response, 'head_object' );
321  
322 return $self->_extract_object_metadata( $response->{headers} );
323 }
324  
325 ########################################################################
326 # Extract the standard object metadata hashref from a response headers
327 # hash. Used by both head_object and get_object.
328 ########################################################################
329 sub _extract_object_metadata {
330 ########################################################################
331 my ( $self, $headers ) = @_;
332  
333 my $etag = $headers->{etag};
334  
335 if ( defined $etag ) {
336 $etag =~ s/\A"|"\z//gxsm;
337 }
338  
339 # Collect x-amz-meta-* headers, stripping the prefix from the key
340 my %metadata;
341 for my $name ( keys %{$headers} ) {
342 if ( $name =~ /^x-amz-meta-(.+)$/xsm ) {
343 $metadata{$1} = $headers->{$name};
344 }
345 }
346  
347 return {
348 content_type => $headers->{'content-type'},
349 content_length => $headers->{'content-length'} + 0,
350 etag => $etag,
351 last_modified => $headers->{'last-modified'},
352 metadata => \%metadata,
353 };
354 }
355  
356 ########################################################################
357 # get_object( $bucket, $key, %options )
358 #
359 # Fetches an object from S3. Options:
360 # range => 'bytes=0-1023' partial fetch
361 # filename => '/tmp/foo' stream body to disk; omits content key
362 #
363 # Returns undef on 404.
364 # Returns a hashref with content_type, content_length, etag,
365 # last_modified, metadata, and content (unless filename is used).
366 ########################################################################
367 sub get_object {
368 ########################################################################
369 my ( $self, $bucket, $key, %options ) = @_;
370  
371 croak 'bucket is required'
372 if !defined $bucket || !length $bucket;
373  
374 croak 'key is required'
375 if !defined $key || !length $key;
376  
377 my $url = $self->_endpoint( $bucket, $key );
378  
379 my %headers;
380  
381 if ( defined $options{range} ) {
382 $headers{Range} = $options{range};
383 }
384  
385 my $filename = $options{filename};
386 my $extra = {};
387  
388 if ( defined $filename ) {
389 # Open the destination file before making the request so we catch
390 # permission errors early, before network round-trip
391 open my $fh, '>', $filename
392 or croak "cannot open '$filename' for writing: $OS_ERROR";
393  
394 $extra->{data_callback} = sub {
395 my ($data) = @_;
396 print {$fh} $data
397 or croak "write to '$filename' failed: $!";
398 };
399  
400 my $response = $self->_request( 'GET', $url, \%headers, q{}, $extra );
401  
402 close $fh
403 or croak "close of '$filename' failed: $!";
404  
405 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
406 if _is_not_found($response);
407  
408 $self->_croak_on_error( $response, 'get_object' );
409  
410 # Return metadata only — content is on disk
411 return $self->_extract_object_metadata( $response->{headers} );
412 }
413  
414 # In-memory path
415 my $response = $self->_request( 'GET', $url, \%headers );
416  
417 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
418 if _is_not_found($response);
419  
420 $self->_croak_on_error( $response, 'get_object' );
421  
422 my $result = $self->_extract_object_metadata( $response->{headers} );
423 $result->{content} = $response->{content};
424  
425 return $result;
426 }
427  
428 ########################################################################
429 # delete_object( $bucket, $key, %options )
430 #
431 # Deletes an object from S3. Options:
432 # version_id => $vid delete a specific version
433 #
434 # Returns true on success. Note S3 returns 204 for both successful
435 # deletes and deletes of non-existent keys — no distinction is made.
436 # Croaks on network or server errors.
437 ########################################################################
438 sub delete_object {
439 ########################################################################
440 my ( $self, $bucket, $key, %options ) = @_;
441  
442 croak 'bucket is required'
443 if !defined $bucket || !length $bucket;
444  
445 croak 'key is required'
446 if !defined $key || !length $key;
447  
448 my $url = $self->_endpoint( $bucket, $key );
449  
450 if ( defined $options{version_id} ) {
451 $url .= '?versionId=' . uri_escape_utf8( $options{version_id} );
452 }
453  
454 my $response = $self->_request( 'DELETE', $url, $options{headers} );
455  
456 $self->_croak_on_error( $response, 'delete_object' );
457  
458 return 1;
459 }
460  
461 ########################################################################
462 # create_bucket( $bucket, %options )
463 #
464 # Creates a new S3 bucket.
465 #
466 # us-east-1 is the S3 default region — the CreateBucketConfiguration
467 # body must NOT be sent for us-east-1 (S3 will error). All other regions
468 # require it with LocationConstraint set to the target region.
469 #
470 # Options: acl, region
471 #
472 # Returns true on success. Croaks on failure.
473 ########################################################################
474 sub create_bucket {
475 ########################################################################
476 my ( $self, $bucket, %options ) = @_;
477  
478 croak 'bucket is required'
479 if !defined $bucket || !length $bucket;
480  
481 my $region = $options{region} // $self->region;
482 my $url = $self->_endpoint($bucket);
483 my %headers;
484  
485 if ( $options{acl} ) {
486 $headers{'x-amz-acl'} = $options{acl};
487 }
488  
489 my $content = q{};
490  
491 # us-east-1 is the implicit default — sending LocationConstraint for it
492 # causes an error. All other regions require it.
493 if ( $region ne 'us-east-1' ) {
494 $content
495 = sprintf '<CreateBucketConfiguration '
496 . 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
497 . '<LocationConstraint>%s</LocationConstraint>'
498 . '</CreateBucketConfiguration>',
499 $region;
500 $headers{'Content-Type'} = 'application/xml';
501 $headers{'Content-Length'} = length $content;
502 }
503  
504 my $response = $self->_request( 'PUT', $url, \%headers, $content, {}, $region );
505  
506 $self->_croak_on_error( $response, 'create_bucket' );
507  
508 return 1;
509 }
510  
511 ########################################################################
512 sub delete_bucket {
513 ########################################################################
514 my ( $self, $bucket, %options ) = @_;
515  
516 croak 'bucket is required'
517 if !defined $bucket || !length $bucket;
518  
519 my $region = $options{region} // $self->region;
520 my $url = $self->_endpoint($bucket);
521  
522 my $response = $self->_request( 'DELETE', $url, {}, q{}, {}, $region );
523  
524 $self->_croak_on_error( $response, 'delete_bucket' );
525  
526 return $TRUE;
527 }
528  
529 ########################################################################
530 # list_buckets()
531 #
532 # Lists all buckets owned by the authenticated user.
533 #
534 # Note: ListBuckets is a global S3 operation and must always be signed
535 # against us-east-1 regardless of the region the object was constructed
536 # with. We pass the region override directly to the signer.
537 #
538 # Returns a hashref:
539 # {
540 # owner_id => '...',
541 # owner_name => '...',
542 # buckets => [
543 # { name => '...', creation_date => '...' },
544 # ...
545 # ],
546 # }
547 ########################################################################
548 sub list_buckets {
549 ########################################################################
550 my ($self) = @_;
551  
552 my $url = $self->_endpoint . q{/}; # ensure canonical URI is / not empty
553  
554 my $response = $self->_request( 'GET', $url, {}, q{}, {}, 'us-east-1' );
555  
556 $self->_croak_on_error( $response, 'list_buckets' );
557  
558 return $self->_parse_list_buckets( $response->{content} );
559 }
560  
561 ########################################################################
562 # Parse ListAllMyBucketsResult XML
563 ########################################################################
564 ########################################################################
565 sub _parse_list_buckets {
566 ########################################################################
567 my ( $self, $xml ) = @_;
568  
569 my ( @buckets, $owner_id, $owner_name );
570  
571 XML::Twig->new(
572 twig_handlers => {
573 'Bucket' => sub {
574 my ( $t, $node ) = @_;
575 push @buckets,
576 {
577 name => $node->first_child_text('Name'),
578 creation_date => $node->first_child_text('CreationDate'),
579 };
580 },
581 'Owner' => sub {
582 my ( $t, $node ) = @_;
583 $owner_id = $node->first_child_text('ID');
584 $owner_name = $node->first_child_text('DisplayName');
585 },
586 }
587 )->parse($xml);
588  
589 return {
590 owner_id => $owner_id,
591 owner_name => $owner_name,
592 buckets => \@buckets,
593 };
594 }
595  
596 ########################################################################
597 # copy_object( %args )
598 #
599 # Copies an object within or between buckets, entirely server-side.
600 # Required: src_bucket, src_key, dst_bucket, dst_key
601 #
602 # Note: S3 can return HTTP 200 with an XML error body for copy operations
603 # that fail mid-transfer. This method detects and croaks on that case.
604 #
605 # Returns a hashref: { etag => '...', last_modified => '...' }
606 ########################################################################
607 sub copy_object {
608 ########################################################################
609 my ( $self, %args ) = @_;
610  
611 for my $required (qw( src_bucket src_key dst_bucket dst_key )) {
612 croak "$required is required"
613 if !defined $args{$required} || !length $args{$required};
614 }
615  
616 my $url = $self->_endpoint( $args{dst_bucket}, $args{dst_key} );
617  
618 # x-amz-copy-source: /src-bucket/encoded-key
619 my $copy_source = '/' . $args{src_bucket} . '/' . _encode_key( $args{src_key} );
620  
621 my %headers = (
622 'x-amz-copy-source' => $copy_source,
623 'x-amz-tagging-directive' => 'COPY',
624 'Content-Length' => 0,
625 );
626  
627 my $response = $self->_request( 'PUT', $url, \%headers );
628  
629 $self->_croak_on_error( $response, 'copy_object' );
630  
631 # S3 can return HTTP 200 with an XML error body for copies that fail
632 # after the headers have been sent. Detect this by checking the root
633 # element — a success response has <CopyObjectResult>, an error has <Error>.
634 return $self->_parse_copy_response( $response->{content}, 'copy_object' );
635 }
636  
637 ########################################################################
638 # Parse CopyObjectResult XML, detecting the 200-with-error edge case
639 ########################################################################
640 ########################################################################
641 sub _parse_copy_response {
642 ########################################################################
643 my ( $self, $xml, $context ) = @_;
644  
645 my $twig = XML::Twig->new->parse($xml);
646 my $root = $twig->root->tag;
647  
648 if ( $root eq 'Error' ) {
649 my $code = $twig->root->first_child_text('Code');
650 my $msg = $twig->root->first_child_text('Message');
651 croak sprintf '%s failed: %s - %s', $context, $code, $msg;
652 }
653  
654 my $etag = $twig->root->first_child_text('ETag') // q{};
655 $etag =~ s/\A"|"\z//gxsm;
656  
657 return {
658 etag => $etag,
659 last_modified => $twig->root->first_child_text('LastModified'),
660 };
661 }
662  
663 ########################################################################
664 # put_object( $bucket, $key, $data, %options )
665 #
666 # Stores an object in S3. $data may be a scalar string, a reference to
667 # a scalar, or a seekable open filehandle / IO::File object.
668 #
669 # Options: content_type, content_length, metadata (hashref), acl
670 #
671 # Returns the ETag of the stored object. Croaks on failure.
672 ########################################################################
673 sub put_object {
674 ########################################################################
675 my ( $self, $bucket, $key, $data, %options ) = @_;
676  
677 croak 'bucket is required'
678 if !defined $bucket || !length $bucket;
679  
680 croak 'key is required'
681 if !defined $key || !length $key;
682  
683 croak 'data is required'
684 if !defined $data;
685  
686 my $url = $self->_endpoint( $bucket, $key );
687  
688 my %headers;
689 $headers{'Content-Type'} = $options{content_type} // 'application/octet-stream';
690  
691 # x-amz-acl header
692 if ( $options{acl} ) {
693 $headers{'x-amz-acl'} = $options{acl};
694 }
695  
696 # User metadata — prefix bare keys with x-amz-meta-
697 if ( my $meta = $options{metadata} ) {
698 for my $k ( keys %{$meta} ) {
699 my $header = $k =~ /^x-amz-meta-/xsm ? $k : "x-amz-meta-$k";
700 $headers{$header} = $meta->{$k};
701 }
702 }
703  
704 # support custom headers
705 if ( $options{headers} ) {
706 if ( reftype( $options{headers} ) eq 'HASH' ) {
707 %headers = ( %headers, %{ $options{headers} } );
708 }
709 else {
710 croak "ERROR: headers must be a hash ref\n";
711 }
712 }
713  
714 my $body;
715 my $payload_hash;
716  
717 if ( openhandle($data) || ( blessed($data) && $data->can('read') ) ) {
718 # --- Filehandle path ---
719 my $content_length = $options{content_length};
720  
721 # Try to stat the handle for real files; suppress warning on
722 # in-memory handles (IO::Scalar etc.) that have no underlying fd
723 my $position = tell $data;
724  
725 if ( !defined $content_length ) {
726 my $fd = eval { return fileno $data };
727  
728 if ( defined $fd && $fd >= 0 ) {
729 my @st = stat $data;
730  
731 if ( @st && defined $st[7] ) {
732 $content_length = $st[7] - $position;
733 }
734 }
735 }
736  
737 croak 'content_length is required for in-memory filehandles'
738 if !defined $content_length;
739  
740 $headers{'Content-Length'} = $content_length;
741  
742 croak 'filehandle must be seekable for streaming upload'
743 if !defined $position;
744  
745 my $sha256 = Digest::SHA->new(256);
746 $sha256->addfile($data);
747  
748 $payload_hash = $sha256->hexdigest;
749  
750 seek $data, $position, 0
751 or croak "could not rewind filehandle: $OS_ERROR";
752  
753 # Wrap filehandle in a code ref for HTTP::Tiny streaming
754 my $chunk_size = 1024 * 64; # 64KB chunks
755  
756 $body = sub {
757 my $buf;
758 my $n = read $data, $buf, $chunk_size;
759  
760 return $buf
761 if $n;
762  
763 return q{};
764 };
765 }
766 elsif ( ref $data eq 'SCALAR' ) {
767 # --- Scalar ref path ---
768 $body = ${$data};
769 $headers{'Content-Length'} = length $body;
770 $headers{'Content-MD5'} = encode_base64( md5($body), q{} );
771 }
772 else {
773 # --- Plain scalar path ---
774 $body = $data;
775 $headers{'Content-Length'} = length $body;
776 $headers{'Content-MD5'} = encode_base64( md5($body), q{} );
777 }
778  
779 my %extra = ( defined $payload_hash ? ( payload_hash => $payload_hash ) : () );
780  
781 my $response = $self->_request(
782 PUT => $url,
783 \%headers, $body, \%extra
784 );
785  
786 $self->_croak_on_error( $response, 'put_object' );
787  
788 my $etag = $response->{headers}{etag};
789  
790 if ( defined $etag ) {
791 $etag =~ s/\A"|"\z//gxsm;
792 }
793  
794 return $etag;
795 }
796  
797 ########################################################################
798 # list_objects_v2( $bucket, %options )
799 #
800 # Lists objects in a bucket using the S3 ListObjectsV2 API.
801 # Returns a hashref with keys: bucket, prefix, key_count, max_keys,
802 # is_truncated, next_continuation_token, objects, common_prefixes.
803 ########################################################################
804 sub list_objects_v2 {
805 ########################################################################
806 my ( $self, $bucket, %options ) = @_;
807  
808 croak 'bucket is required'
809 if !defined $bucket || !length $bucket;
810  
811 # Map our option names to S3 query parameter names
812 my %param_map = (
813 prefix => 'prefix',
814 delimiter => 'delimiter',
815 max_keys => 'max-keys',
816 continuation_token => 'continuation-token',
817 start_after => 'start-after',
818 );
819  
820 my %params = ( 'list-type' => '2' );
821  
822 for my $opt ( keys %param_map ) {
823 if ( defined $options{$opt} ) {
824 $params{ $param_map{$opt} } = $options{$opt};
825 }
826 }
827  
828 # Build query string
829 my $query = join q{&}, map { uri_escape_utf8($_) . q{=} . uri_escape_utf8( $params{$_} ) }
830 sort keys %params;
831  
832 my $url = $self->_endpoint($bucket) . q{?} . $query;
833  
834 my $response = $self->_request( 'GET', $url );
835  
836 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
837 if _is_not_found($response);
838  
839 $self->_croak_on_error( $response, 'list_objects_v2' );
840  
841 return $self->_parse_list_objects_v2( $response->{content} );
842 }
843  
844 ########################################################################
845 # Parse the XML body of a ListObjectsV2 response
846 ########################################################################
847 ########################################################################
848 sub _parse_list_objects_v2 {
849 ########################################################################
850 my ( $self, $xml ) = @_;
851  
852 my ( @objects, @common_prefixes );
853 my ( $bucket, $prefix, $key_count, $max_keys, $is_truncated, $next_token );
854  
855 XML::Twig->new(
856 twig_handlers => {
857 'Name' => sub { $bucket = $_[1]->text },
858 'ListBucketResult/Prefix' => sub { $prefix = $_[1]->text },
859 'KeyCount' => sub { $key_count = $_[1]->text + 0 },
860 'MaxKeys' => sub { $max_keys = $_[1]->text + 0 },
861 'IsTruncated' => sub { $is_truncated = $_[1]->text eq 'true' ? 1 : 0 },
862 'NextContinuationToken' => sub { $next_token = $_[1]->text },
863 'Contents' => sub {
864 my ( $t, $node ) = @_;
865 my $etag = $node->first_child_text('ETag') // q{};
866 $etag =~ s/\A"|"\z//gxsm;
867 push @objects,
868 {
869 key => $node->first_child_text('Key'),
870 size => $node->first_child_text('Size') + 0,
871 last_modified => $node->first_child_text('LastModified'),
872 etag => $etag,
873 storage_class => $node->first_child_text('StorageClass'),
874 };
875 $t->purge; # free memory as we go - important for large listings
876 },
877 'CommonPrefixes' => sub {
878 my ( $t, $node ) = @_;
879 push @common_prefixes, $node->first_child_text('Prefix');
880 },
881 }
882 )->parse($xml);
883  
884 return {
885 bucket => $bucket,
886 prefix => $prefix,
887 key_count => $key_count,
888 max_keys => $max_keys,
889 is_truncated => $is_truncated,
890 next_continuation_token => $next_token,
891 objects => \@objects,
892 common_prefixes => \@common_prefixes,
893 };
894 }
895  
896 ########################################################################
897 # list_all_objects_v2( $bucket, %options )
898 #
899 # Convenience wrapper that auto-paginates list_objects_v2 and returns
900 # a flat list of all matching object hashrefs.
901 # delimiter is ignored — use list_objects_v2 directly for that.
902 ########################################################################
903 sub list_all_objects_v2 {
904 ########################################################################
905 my ( $self, $bucket, %options ) = @_;
906  
907 # delimiter is meaningless here — silently remove it
908 delete $options{delimiter};
909  
910 my @all_objects;
911 my $continuation_token;
912  
913 while ($TRUE) {
914 if ( defined $continuation_token ) {
915 $options{continuation_token} = $continuation_token;
916 }
917  
918 my $result = $self->list_objects_v2( $bucket, %options );
919  
920 last if !$result; # 404 / empty bucket
921  
922 push @all_objects, @{ $result->{objects} };
923  
924 last if !$result->{is_truncated};
925  
926 $continuation_token = $result->{next_continuation_token};
927 }
928  
929 return @all_objects;
930 }
931  
932 ########################################################################
933 sub put_bucket_notification_configuration {
934 ########################################################################
935 my ( $self, $bucket, %options ) = @_;
936  
937 my $xml = $self->_create_notification_configuration( $bucket, %options );
938  
939 my $url = $self->_endpoint($bucket) . q{?notification=};
940  
941 my %headers = (
942 'Content-Type' => 'application/xml',
943 'Content-Length' => length $xml,
944 'Content-MD5' => encode_base64( md5($xml), q{} ),
945 );
946  
947 my $response = $self->_request( 'PUT', $url, \%headers, $xml );
948  
949 $self->_croak_on_error( $response, 'put_bucket_notification_configuration' );
950  
951 return $TRUE;
952 }
953 ########################################################################
954 sub put_public_access_block {
955 ########################################################################
956 my ( $self, $bucket, %options ) = @_;
957  
958 my $xml = $self->_create_public_access_block( $bucket, %options );
959  
960 my $url = $self->_endpoint($bucket) . q{?publicAccessBlock=};
961  
962 my %headers = (
963 'Content-Type' => 'application/xml',
964 'Content-Length' => length $xml,
965 'Content-MD5' => encode_base64( md5($xml), q{} ),
966 );
967  
968 my $response = $self->_request( 'PUT', $url, \%headers, $xml );
969  
970 $self->_croak_on_error( $response, 'put_public_access_block' );
971  
972 return $TRUE;
973 }
974  
975 ########################################################################
976 sub remove_bucket_notification_configuration {
977 ########################################################################
978 my ( $self, $bucket ) = @_;
979  
980 croak 'bucket is required'
981 if !defined $bucket || !length $bucket;
982  
983 my $xml = <<'END_XML';
984 <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"/>
985 END_XML
986  
987 my $url = $self->_endpoint($bucket) . q{?notification=};
988  
989 my %headers = (
990 'Content-Type' => 'application/xml',
991 'Content-Length' => length $xml,
992 'Content-MD5' => encode_base64( md5($xml), q{} ),
993 );
994  
995 my $response = $self->_request( 'PUT', $url, \%headers, $xml );
996  
997 $self->_croak_on_error( $response, 'remove_bucket_notification_configuration' );
998  
999 return $TRUE;
1000 }
1001  
1002 ########################################################################
1003 sub get_bucket_notification_configuration {
1004 ########################################################################
1005 my ( $self, $bucket ) = @_;
1006  
1007 croak 'bucket is required'
1008 if !defined $bucket || !length $bucket;
1009  
1010 my $url = $self->_endpoint($bucket) . q{?notification=};
1011  
1012 my $response = $self->_request( 'GET', $url );
1013  
1014 $self->_croak_on_error( $response, 'get_bucket_notification_configuration' );
1015  
1016 my $rsp = $self->_parse_notification_configuration( $response->{content} );
1017  
1018 $self->logger->debug(
1019 Dumper(
1020 [ response => $response,
1021 parsed_response => $rsp
1022 ]
1023 )
1024 );
1025  
1026 return $rsp;
1027 }
1028  
1029 ########################################################################
1030 sub _parse_notification_configuration {
1031 ########################################################################
1032 my ( $self, $xml ) = @_;
1033  
1034 my @configs;
1035  
1036 my $handler = sub {
1037 my ( $t, $node ) = @_;
1038  
1039 my @events = map { $_->text } $node->children('Event');
1040  
1041 my @filter_rules;
1042  
1043 if ( my $filter = $node->first_child('Filter') ) {
1044 if ( my $s3key = $filter->first_child('S3Key') ) {
1045 for my $rule ( $s3key->children('FilterRule') ) {
1046 push @filter_rules,
1047 {
1048 name => $rule->first_child_text('Name'),
1049 value => $rule->first_child_text('Value'),
1050 };
1051 }
1052 }
1053 }
1054  
1055 push @configs,
1056 {
1057 id => $node->first_child_text('Id'),
1058 lambda_arn => $node->first_child_text('CloudFunction'),
1059 queue_arn => $node->first_child_text('Queue'),
1060 topic_arn => $node->first_child_text('Topic'),
1061 events => \@events,
1062 filters => \@filter_rules,
1063 };
1064  
1065 $t->purge;
1066 };
1067  
1068 XML::Twig->new(
1069 twig_handlers => {
1070 CloudFunctionConfiguration => $handler,
1071 QueueConfiguration => $handler,
1072 TopicConfiguration => $handler,
1073 }
1074 )->parse($xml);
1075  
1076 return \@configs;
1077 }
1078  
1079 ########################################################################
1080 sub _create_notification_configuration {
1081 ########################################################################
1082 my ( $self, $bucket, %options ) = @_;
1083  
1084 croak 'ERROR: bucket is required'
1085 if !defined $bucket || !length $bucket;
1086  
1087 croak "ERROR: type is a required argument\n"
1088 if !$options{type};
1089  
1090 croak 'ERROR: lambda_arn is required'
1091 if $options{type} eq 'lambda' && !$options{lambda_arn};
1092  
1093 croak 'ERROR: queue_arn is required'
1094 if $options{type} eq 'sqs' && !$options{queue_arn};
1095  
1096 my $events = ref $options{events} ? $options{events} : [ $options{events} ];
1097  
1098 croak "ERROR: no events defined\n"
1099 if !$options{events} || !@{$events};
1100  
1101 my $templates = $self->_fetch_templates();
1102  
1103 my $id = $options{id} // 'notification-1';
1104  
1105 my @event_xml;
1106  
1107 foreach ( @{$events} ) {
1108 push @event_xml, $self->_resolve( $templates->{event}, event => $_ );
1109 }
1110  
1111 my @filter_rules;
1112  
1113 foreach my $p ( pairs %{ $options{filters} // {} } ) {
1114 my ( $name, $value ) = @{$p};
1115 push @filter_rules, $self->_resolve( $templates->{'filter-rule'}, filter_name => $name, filter => $value );
1116 }
1117  
1118 my $filters = @filter_rules ? $self->_resolve( $templates->{'filters'}, filter_rules => "@filter_rules" ) : q{};
1119  
1120 my $xml = $templates->{ $options{type} . '-event' };
1121  
1122 my $resolved_xml = $self->_resolve(
1123 $xml,
1124 id => $id,
1125 lambda_arn => $options{lambda_arn},
1126 queue_arn => $options{queue_arn},
1127 events => "@event_xml",
1128 filters => $filters,
1129 );
1130  
1131 $self->logger->debug( Dumper( [ resolved_xml => $resolved_xml ] ) );
1132  
1133 return $resolved_xml;
1134 }
1135  
1136 ########################################################################
1137 sub _create_public_access_block {
1138 ########################################################################
1139 my ( $self, $bucket, %permissions ) = @_;
1140  
1141 croak 'ERROR: bucket is required'
1142 if !defined $bucket || !length $bucket;
1143  
1144 foreach my $p (qw(block_public_acls ignore_public_acls block_public_policy restrict_public_buckets)) {
1145 $permissions{$p} = defined $permissions{$p} ? $permissions{$p} ? 'true' : 'false' : 'true';
1146 }
1147  
1148 my $templates = $self->_fetch_templates();
1149  
1150 my $xml = $self->_resolve( $templates->{'public_access_block'}, %permissions );
1151 $xml = qq{<?xml version="1.0" encoding="UTF-8"?>\n} . $xml;
1152  
1153 $self->logger->debug( Dumper( [ xml => $xml ] ) );
1154  
1155 return $xml;
1156 }
1157  
1158 ########################################################################
1159 sub put_bucket_website {
1160 ########################################################################
1161 my ( $self, $bucket, %options ) = @_;
1162  
1163 my $xml = $self->_create_website_configuration( $bucket, %options );
1164  
1165 my $url = $self->_endpoint($bucket) . q{?website=};
1166  
1167 my %headers = (
1168 'Content-Type' => 'application/xml',
1169 'Content-Length' => length $xml,
1170 'Content-MD5' => encode_base64( md5($xml), q{} ),
1171 );
1172  
1173 my $response = $self->_request( 'PUT', $url, \%headers, $xml );
1174  
1175 $self->_croak_on_error( $response, 'put_bucket_website' );
1176  
1177 return $TRUE;
1178 }
1179  
1180 ########################################################################
1181 # get_bucket_policy( $bucket )
1182 #
1183 # Returns undef if the bucket has no policy (404
1184 # NoSuchBucketPolicy). Otherwise returns the policy as a decoded
1185 # hashref; pass raw => 1 to get the JSON string instead.
1186 ########################################################################
1187 sub get_bucket_policy {
1188 ########################################################################
1189 my ( $self, $bucket, %options ) = @_;
1190  
1191 croak 'bucket is required'
1192 if !defined $bucket || !length $bucket;
1193  
1194 my $url = $self->_endpoint($bucket) . q{?policy=};
1195  
1196 my $response = $self->_request( 'GET', $url );
1197  
1198 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
1199 if _is_not_found($response);
1200  
1201 $self->_croak_on_error( $response, 'get_bucket_policy' );
1202  
1203 return $options{raw} ? $response->{content} : JSON::PP::decode_json( $response->{content} );
1204 }
1205  
1206 ########################################################################
1207 sub _create_website_configuration {
1208 ########################################################################
1209 my ( $self, $bucket, %options ) = @_;
1210  
1211 croak 'ERROR: bucket is required'
1212 if !defined $bucket || !length $bucket;
1213  
1214 my $index = $options{index} // 'index.html';
1215  
1216 my $templates = $self->_fetch_templates;
1217  
1218 my $error = q{};
1219  
1220 if ( defined $options{error} && length $options{error} ) {
1221 $error = $self->_resolve( $templates->{'website-error'}, error_key => $options{error} );
1222 }
1223  
1224 return $self->_resolve(
1225 $templates->{website},
1226 index => $index,
1227 error => $error,
1228 );
1229 }
1230  
1231 ########################################################################
1232 sub _parse_website_configuration {
1233 ########################################################################
1234 my ( $self, $xml ) = @_;
1235  
1236 my $root = XML::Twig->new->parse($xml)->root;
1237  
1238 my %config;
1239  
1240 if ( my $index = $root->first_child('IndexDocument') ) {
1241 $config{index_document} = $index->first_child_text('Suffix');
1242 }
1243  
1244 if ( my $error = $root->first_child('ErrorDocument') ) {
1245 $config{error_document} = $error->first_child_text('Key');
1246 }
1247  
1248 if ( my $redirect = $root->first_child('RedirectAllRequestsTo') ) {
1249 $config{redirect_all_requests_to} = $redirect->first_child_text('HostName');
1250 }
1251  
1252 return \%config;
1253 }
1254  
1255 ########################################################################
1256 # get_bucket_website( $bucket )
1257 #
1258 # Returns undef if the bucket has no website configuration (404).
1259 # Otherwise returns a hashref with index_document, error_document,
1260 # and (if present) redirect_all_requests_to.
1261 ########################################################################
1262 sub get_bucket_website {
1263 ########################################################################
1264 my ( $self, $bucket ) = @_;
1265  
1266 croak 'bucket is required'
1267 if !defined $bucket || !length $bucket;
1268  
1269 my $url = $self->_endpoint($bucket) . q{?website=};
1270  
1271 my $response = $self->_request( 'GET', $url );
1272  
1273 return undef ## no critic (Subroutines::ProhibitExplicitReturnUndef)
1274 if _is_not_found($response);
1275  
1276 $self->_croak_on_error( $response, 'get_bucket_website' );
1277  
1278 return $self->_parse_website_configuration( $response->{content} );
1279 }
1280  
1281 ########################################################################
1282 sub delete_bucket_website {
1283 ########################################################################
1284 my ( $self, $bucket ) = @_;
1285  
1286 croak 'bucket is required'
1287 if !defined $bucket || !length $bucket;
1288  
1289 my $url = $self->_endpoint($bucket) . q{?website=};
1290  
1291 my $response = $self->_request( 'DELETE', $url );
1292  
1293 $self->_croak_on_error( $response, 'delete_bucket_website' );
1294  
1295 return $TRUE;
1296 }
1297  
1298 ########################################################################
1299 sub put_bucket_policy {
1300 ########################################################################
1301 my ( $self, $bucket, $policy ) = @_;
1302  
1303 croak 'bucket is required'
1304 if !defined $bucket || !length $bucket;
1305  
1306 croak 'policy is required'
1307 if !defined $policy;
1308  
1309 require JSON::PP;
1310  
1311 my $json = ref $policy ? JSON::PP->new->canonical->encode($policy) : $policy;
1312  
1313 my $url = $self->_endpoint($bucket) . q{?policy=};
1314  
1315 my %headers = (
1316 'Content-Type' => 'application/json',
1317 'Content-Length' => length $json,
1318 'Content-MD5' => encode_base64( md5($json), q{} ),
1319 );
1320  
1321 my $response = $self->_request( 'PUT', $url, \%headers, $json );
1322  
1323 $self->_croak_on_error( $response, 'put_bucket_policy' );
1324  
1325 return $TRUE;
1326 }
1327  
1328 my %TEMPLATES;
1329  
1330 ########################################################################
1331 sub _fetch_templates {
1332 ########################################################################
1333 my ($self) = @_;
1334  
1335 return \%TEMPLATES
1336 if %TEMPLATES;
1337  
1338 local $RS = undef;
1339  
1340 my $data = <DATA>;
1341 $data =~ s/\A(.*?)^=pod.*\z/$1/xsm;
1342  
1343 my $t = q{};
1344 my $template_name = q{};
1345  
1346 foreach my $line ( split /\n/xsm, $data ) {
1347 if ( $line =~ /^:(.*)$/xsm ) {
1348 if ( $template_name && $t ) {
1349 $TEMPLATES{$template_name} = $t;
1350 }
1351 $t = q{};
1352 $template_name = $1;
1353 next;
1354 }
1355  
1356 $t .= "$line\n";
1357 }
1358  
1359 $TEMPLATES{$template_name} = $t;
1360  
1361 return \%TEMPLATES;
1362 }
1363  
1364 ########################################################################
1365 sub _resolve {
1366 ########################################################################
1367 my ( $self, $template, %data ) = @_;
1368  
1369 my $output = $template;
1370  
1371 foreach my $p ( pairs %data ) {
1372 my ( $k, $v ) = @{$p};
1373  
1374 $output =~ s/[@]\Q$k\E[@]/$v/xsmg;
1375 }
1376  
1377 return $output;
1378 }
1379  
1380 ########################################################################
1381 # Error checking helpers
1382 ########################################################################
1383 sub _is_success {
1384 ########################################################################
1385 return $_[0]->{status} =~ /\A2\d{2}\z/;
1386 }
1387  
1388 ########################################################################
1389 sub _is_not_found {
1390 ########################################################################
1391 return $_[0]->{status} == 404;
1392 }
1393  
1394 ########################################################################
1395 sub _croak_on_error {
1396 ########################################################################
1397 my ( $self, $response, $context ) = @_;
1398  
1399 return
1400 if _is_success($response);
1401  
1402 my ( $status, $reason ) = @{$response}{qw(status reason)};
1403  
1404 # Attempt to extract S3 error message from XML body
1405 my $detail = q{};
1406  
1407 if ( $response->{content} && $response->{content} =~ /<\?xml/xsm ) {
1408 my ($code) = $response->{content} =~ m{<Code>([^<]+)</Code>}xsm;
1409 my ($msg) = $response->{content} =~ m{<Message>([^<]+)</Message>}xsm;
1410  
1411 if ( $code || $msg ) {
1412 $detail = " - $code: $msg";
1413 }
1414 }
1415  
1416 croak sprintf '%s failed: HTTP %s %s%s', $context, $status, $reason, $detail;
1417 }
1418  
1419 1;
1420  
1421 ## no critic (RequirePodSections)
1422  
1423 __DATA__
« Lite/Policies.pm ↑ Summary Lite/Constants.pm »