1 package Net
::Amazon
::S3
::Policy
;
5 use version
; our $VERSION = qv
('0.1.5');
8 use English
qw( -no_match_vars );
11 use MIME
::Base64 qw
< decode_base64
>;
14 our @ISA = qw( Exporter );
15 our @EXPORT_OK = qw( exact starts_with range );
16 our %EXPORT_TAGS = (all
=> \
@EXPORT_OK,);
18 # Module implementation here
21 my %args = ref($_[0]) ?
%{$_[0]} : @_;
22 my $self = bless {}, $class;
25 $self->parse($args{json
});
28 $self->expiration($args{expiration
}) if defined $args{expiration
};
29 $self->conditions([]);
30 $self->add($_) for @
{$args{conditions
} || []};
39 my $previous = $self->{expiration
};
42 if ($time && $time =~ /\A \d+ \z/mxs) {
43 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
45 $time = sprintf "%04d-%02d-%02dT%02d:%02d:%02d.000Z",
47 $mon + 1, $mday, $hour, $min, $sec;
48 } ## end if ($time && $time =~ ...
49 $time ?
($self->{expiration
} = $time) : delete $self->{expiration
};
52 } ## end sub expiration
56 my $previous = $self->{conditions
};
59 $self->{conditions
} = (scalar(@_) == 1) ?
shift : [@_];
63 } ## end sub conditions
65 { # try to understand rules
68 return substr($_[0], 0, 1) eq '$' ?
$_[0] : '$' . $_[0];
71 qr{\A\s* (\S+?) \s* \* \s*\z}mxs => sub {
72 my $target = _prepend_dollar
(shift);
73 return starts_with
($target, '');
75 qr{\A\s* (\S+) \s+ eq \s+ (.*?) \s*\z}mxs => sub{
76 my $target = _prepend_dollar
(shift);
78 return $value eq '*' ? starts_with
($target, '') : exact
($target, $value);
80 qr{\A\s* (\S+) \s+ (?: ^ | starts[_-]?with) \s+ (.*?) \s*\z}mxs => sub {
81 my $target = _prepend_dollar
(shift);
83 return starts_with
($target, $prefix);
85 qr{\A\s* (\d+) \s*<=\s* (\S+) \s*<=\s* (\d+) \s*\z}mxs => sub {
86 my ($min, $value, $max) = @_;
87 s{_}{}g for $min, $max;
89 # no "_prepend_dollar" for range conditions
90 return range
($value, $min, $max);
97 for my $i (0 .. (@DWIMs - 1) / 2) {
98 my ($regex, $callback) = @DWIMs[$i * 2, $i * 2 + 1];
99 if (my @captures = $string =~ /$regex/) {
100 my $result = $callback->(@captures);
101 return $result if defined $result;
105 croak
"could not understand '$_', bailing out";
106 } ## end sub _resolve_rule
110 my ($self, $condition) = @_;
111 push @
{$self->conditions()},
112 ref($condition) ?
$condition : _resolve_rule
($condition);
117 my ($self, $condition) = @_;
118 $condition = _resolve_rule
($condition) unless ref $condition;
119 my $conditions = $self->conditions();
120 my @filtered = grep {
122 if (@
$condition != @
$_) { # different lengths => different
126 for my $i (0 .. $#$condition) {
127 last if $keep = $condition->[$i] ne $_->[$i];
132 $self->conditions(\
@filtered);
138 my ($target, $value) = @_;
139 return ['eq', $target, $value];
144 my ($target, $value) = @_;
145 return ['starts-with', $target, $value];
150 my ($target, $min, $max) = @_;
151 return [$target, $min, $max];
155 my ($self, $args) = @_;
157 delete $params{expiration
} unless defined $params{expiration
};
158 return to_json
(\
%params, $args);
163 return encode_base64
(Encode
::encode
('utf-8', $self->json(@_)));
169 *json_base64
= \
&base64
;
170 *stringify_base64
= \
&base64
;
174 my ($self, $json) = @_;
176 $json = decode_base64
($json)
177 unless substr($json, 0, 1) eq '{';
179 my %decoded = %{from_json
($json)};
180 $self->{conditions
} = [
182 if (ref($_) eq 'ARRAY') { $_; }
184 my ($name, $value) = %$_;
185 ['eq', '$' . $name, $value];
187 } @
{$decoded{conditions
}}
189 $self->{expiration
} = $decoded{expiration
};
195 my ($self, $key) = @_;
196 require Digest
::HMAC_SHA1
;
197 return Digest
::HMAC_SHA1
::hmac_sha1
($self->base64(), $key);
200 sub signature_base64
{
201 my ($self, $key) = @_;
202 return encode_base64
($self->signature($key));
205 # Wrapper around base64 encoder, ensuring that there's no newline
206 # to make AWS S3 happy
208 return MIME
::Base64
::encode_base64
($_[0], '');
211 1; # Magic true value required at end of module
218 Net::Amazon::S3::Policy - manage Amazon S3 policies for HTTP POST forms
222 This document describes Net::Amazon::S3::Policy version 0.1.3. Most likely,
223 this version number here is outdate, and you should peek the source.
228 use Net::Amazon::S3::Policy;
231 my $policy = Net::Amazon::S3::Policy->new(expiration => time() + 3600);
233 # Do What I Mean handling of conditions
234 # Note: single quotes, $key is not a Perl variable in this example!
235 $policy->add('$key eq path/to/somewhere');
236 # In DWIM mode, '$' are pre-pended automatically where necessary
237 $policy->add('key eq path/to/somewhere');
238 $policy->add('x-some-field starts-with some-prefix');
239 $policy->add(' 0 <= content-length-range <= 1_000_000 ');
240 $policy->add('whatever *'); # any value admitted for field 'whatever'
242 # NON-DWIM interface for conditions
243 use Net::Amazon::S3::Policy qw( :all ); # OR
244 use Net::Amazon::S3::Policy qw( exact starts_with range );
245 $policy->add(exact('$field', 'whatever spaced value ');
246 $policy->add(starts_with('$other-field', ' yadda ');
247 $policy->add(range('percentual', 0, 100));
250 print $policy->stringify(), "\n"; # OR
251 print $policy->json(), "\n";
253 # Where the stuff is really needed: HTML FORMs for HTTP POSTs
254 my $policy_for_form = $policy->base64();
255 my $signature_for_form = $policy->signature_base64($key);
257 # If you ever receive a policy...
258 my $received = Net::Amazon::S3::Policy->new(json => $json_text);
259 my $rec2 = Net::Amazon::S3::Policy->new();
260 $rec2->parse($json_base64); # either JSON or its Base64 encoding
265 Net::Amazon::S3::Policy gives you an object-oriented interface to
266 manage policies for Amazon S3 HTTP POST uploads.
268 Amazon S3 relies upon either a REST interface (see L<Net::Amazon::S3>)
269 or a SOAP one; as an added service, it is possible to give access to
270 the upload of resources using HTTP POSTs that do not involve using
271 any of these two interfaces, but a single HTML FORM. The rules you
272 have to follow are explained in the Amazon S3 Developer Guide.
274 More or less, it boils down to the following:
280 if the target bucket is not writeable by the anonymous group, you'll need
281 to set an access policy;
285 almost every field in the HTML FORM that will be used to build up the HTTP POST
286 message by the browser needs to be included into a I<policy>, and the policy
287 has to be sent along within the HTTP POST
291 together with the I<policy>, also the bucket owner's AWS ID (the public one) has to
292 be sent, together with a digital signature of the policy that has to be created
293 using the bucket owner's AWS secret key.
297 So, you'll have to add three fields to the HTTP POST in order for it to comply
298 with Amazon's requirement when the bucket is not publicly writeable:
302 =item C<AWSAccessKeyId>
304 given "as-is", i.e. as you copied from your account in Amazon Web Services;
308 given as a JSON document that is Base64 encoded;
312 calculated as a SHA1-HMAC of the Base64-encoded policy, using your secret
313 key as the signature key, and then encoded with Base64.
317 This module lets you manage the build-up of a policy document, providing you
318 with tools to get the Base64 encoding of the resulting JSON policy document,
319 and to calculate the Base64 encoding of the signature. See L</Example> for
320 a complete example of how to do this.
322 In addition to I<policy synthesis>, the module is also capable of parsing
323 some policy (base64-encoded or not, but in JSON format). This shouldn't
324 be a need in general... possibly for debug reasons.
328 For example, suppose that you have the following HTML FORM to allow selected
329 uploads to the C<somebucket> bucket (see the Amazon S3 Developer Guide for
330 details about writing the HTML FORM):
332 <form action="http://somebucket.s3.amazonaws.com/" method="post"
333 enctype="multipart/form-data">
334 <!-- inputs needed because bucket is not publicly writeable -->
335 <input type="hidden" name="AWSAccessKeyId" value="your-ID-here">
336 <input type="hidden" name="policy" value="base64-encoded-policy">
337 <input type="hidden" name="signature" value="base64-encoded-signature">
339 <!-- input needed by AWS-S3 logic: there MUST be a key -->
340 <input type="hidden" name="key" value="/restricted/${filename}">
342 <!-- inputs that you want to include in your form -->
343 <input type="hidden" name="Content-Type" value="image/jpeg">
344 <label for="colour">Colour</label>
345 <input type="text" id="colour" name="x-amz-meta-colour" value="green">
347 <!-- input needed to have something to upload. LAST IN FORM! -->
348 <input type="file" id="file" name="file">
351 You need to include the following elements in your policy:
369 Your policy can then be built like this:
371 my $policy = Net::Amazon::S3::Policy->new(
372 expiration => time() + 60 * 60, # one-hour policy
374 '$key starts-with /restricted/', # restrict to here
375 '$Content-Type starts-with image/', # accept any image format
376 '$x-amz-meta-colour *', # accept any colour
377 'bucket eq somebucket',
381 # Put this as the value for "policy",
382 # instead of "base64-encoded-policy"
383 my $policy_for_form = $policy->base64();
385 # Put this as the value for "signature",
386 # instead of "base64-encoded-signature"
387 my $signature_for_form = $policy->signature_base64($key);
391 =begin PrivateMethods
397 =head2 Module Interface
401 =item B<< new (%args) >>
403 =item B<< new (\%args) >>
405 constructor to create a new Net::Amazon::S3::Policy object.
407 Arguments can be passed either as a single hash reference, or
408 as a hash. Choose whatever you like most.
416 the expiration date for this policy.
420 a list of conditions to initialise the object. This should
421 point to an array with the conditions, that will be passed through
426 a piece of JSON text to parse the configuration from. The presence
427 of this parameter overrides the other two.
431 =item B<< expiration () >>
433 =item B<< expiration ($time) >>
435 get/set the expiration time for the condition. Set to a false value
436 to remove the expiration time from the policy.
438 You should either pass an ISO8601 datetime string, or an epoch value.
439 You'll always get an ISO8601 string back.
441 =item B<< conditions () >>
443 =item B<< conditions (@conditions) >>
445 =item B<< conditions (\@conditions) >>
447 get/set the conditions in the policy. You should never need to use this
448 method, because the L</add> and L</remove> are there for you to interact
449 with this member. If you want to use this, anyway, be sure to take
450 a look to the functions in L</Convenience Condition Functions>.
452 =item B<< add ($spec) >>
454 add a specification to the list of conditions.
456 A specification can be either an ARRAY reference, or a textual one:
462 if you pass an ARRAY reference, it should be something like the one
463 returned by any of the functions in L</Convenience Condition Functions>;
467 othewise, it can be a string with a single condition, like the following
470 some-field eq some-value
471 $some-other-field starts-with /path/to/somewhere/
472 10 <= numeric-value <= 1000
474 Note that the string specification is less "strict" in checking its
475 parameters; in particular, you should stick to the ARRAY reference if
476 your parameters have a space inside. You can use the following formats:
480 =item C<< <name> eq <value> >>
482 set a name to have a given value, exactly;
484 =item C<< <name> starts-with <prefix> >>
486 =item C<< <name> starts_with <prefix> >>
488 =item C<< <name> ^ <prefix> >>
490 set the prefix that has to be matched against the value
491 for the field with the given name. If the prefix is left
492 empty, every possible value will be admitted;
494 =item C<< <name> * >>
496 admit any value for the given field, just like setting an empty
497 value for a C<starts-with> rule;
499 =item C<< <min> <= <name> <= <max> >>
501 set an allowable range for the given field.
505 Policies for exact or starts-with matching usually refer to the form's
506 field, thus requiring to refer them as "variables" with a prepended
507 dollar sign, just like Perl scalars (more or less). Thus, if you forget
508 to put it, it will be automatically added for you. Hence, the following
509 conditions are equivalent:
514 because both yield the following condition in JSON:
516 ["eq","$field","blah"]
520 =item B<< remove ($spec) >>
522 remove a condition in the list of conditions. The parameter is
523 regarded exactly as in L</add>; once it is found, the list of
524 conditions will be filtered to exclude that particular
529 =item B<< stringify () >>
531 get a textual version of the object, in JSON format. This is the
532 base format used to interact with Amazon S3.
534 =item B<< base64 () >>
536 =item B<< json_base64 () >>
538 =item B<< stringify_base64 () >>
540 get a textual version of the object, as a Base64 encoding of the
541 JSON representation (see L</json>). This is what should to be put
542 as C<policy> field in the POST form.
545 =item B<< parse ($json_text) >>
547 parse a JSON representation of a policy and fill in the object. This
548 is the opposite of L</json>.
551 =item B<< signature ($key) >>
553 get the signature for the Base 64 encoding of the JSON representation of
554 the policy. The signature is the SHA1-HMAC digital signature, with the
558 =item B<< signature_base64 ($key) >>
560 get the Base64 encoding of the signature, as given by L</signature>. This
561 is the value that should be put in the C<signature> field in the POST
566 =head2 Convenience Condition Functions
568 The following functions can be optionally imported from the
569 module, and can be used indifferently as class/instance
570 methods or as functions.
574 =item B<< exact ($target, $value) >>
576 produce an I<exact value> condition. This condition is an array
577 reference with the following elements:
587 the I<name> of the field;
591 the I<value> that the field should match exactly.
595 =item B<< starts_with ($target, $value) >>
597 produce a I<starts-with> condition. This condition is an array
598 reference with the following elements:
604 the C<starts-with> string;
608 the I<name> of the field;
612 the I<prefix> that has to be matched by the field's value
616 =item B<< range ($target, $min, $max) >>
618 produce a I<value range> condition. This condition is an array
619 reference with the following elements:
625 the I<name> of the field;
629 the I<minimum> value allowed for the field's value;
633 the I<maximum> value allowed for the field's value;
644 =item C<< could not understand '%s', bailing out >>
646 The L</add> and L</remove> function try their best to understand
647 a condition when given in string form... but you should really
648 stick to the format given in the documentation!
653 =head1 CONFIGURATION AND ENVIRONMENT
655 Net::Amazon::S3::Policy requires no configuration files or environment variables.
660 The C<version> pragma (which has been included in Perl 5.10) and the
664 =head1 INCOMPATIBILITIES
669 =head1 BUGS AND LIMITATIONS
671 No bugs have been reported.
673 Please report any bugs or feature requests through http://rt.cpan.org/
678 Flavio Poletti C<< <flavio [at] polettix [dot] it> >>
681 =head1 LICENCE AND COPYRIGHT
683 Copyright (c) 2008, Flavio Poletti C<< <flavio [at] polettix [dot] it> >>. All rights reserved.
685 This module is free software; you can redistribute it and/or
686 modify it under the same terms as Perl 5.8.x itself. See L<perlartistic>
689 Questo modulo è software libero: potete ridistribuirlo e/o
690 modificarlo negli stessi termini di Perl 5.8.x stesso. Vedete anche
691 L<perlartistic> e L<perlgpl>.
694 =head1 DISCLAIMER OF WARRANTY
696 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
697 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
698 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
699 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
700 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
701 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
702 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
703 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
704 NECESSARY SERVICING, REPAIR, OR CORRECTION.
706 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
707 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
708 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
709 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
710 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
711 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
712 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
713 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
714 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
717 =head1 NEGAZIONE DELLA GARANZIA
719 Poiché questo software viene dato con una licenza gratuita, non
720 c'è alcuna garanzia associata ad esso, ai fini e per quanto permesso
721 dalle leggi applicabili. A meno di quanto possa essere specificato
722 altrove, il proprietario e detentore del copyright fornisce questo
723 software "così com'è" senza garanzia di alcun tipo, sia essa espressa
724 o implicita, includendo fra l'altro (senza però limitarsi a questo)
725 eventuali garanzie implicite di commerciabilità e adeguatezza per
726 uno scopo particolare. L'intero rischio riguardo alla qualità ed
727 alle prestazioni di questo software rimane a voi. Se il software
728 dovesse dimostrarsi difettoso, vi assumete tutte le responsabilità
729 ed i costi per tutti i necessari servizi, riparazioni o correzioni.
731 In nessun caso, a meno che ciò non sia richiesto dalle leggi vigenti
732 o sia regolato da un accordo scritto, alcuno dei detentori del diritto
733 di copyright, o qualunque altra parte che possa modificare, o redistribuire
734 questo software così come consentito dalla licenza di cui sopra, potrà
735 essere considerato responsabile nei vostri confronti per danni, ivi
736 inclusi danni generali, speciali, incidentali o conseguenziali, derivanti
737 dall'utilizzo o dall'incapacità di utilizzo di questo software. Ciò
738 include, a puro titolo di esempio e senza limitarsi ad essi, la perdita
739 di dati, l'alterazione involontaria o indesiderata di dati, le perdite
740 sostenute da voi o da terze parti o un fallimento del software ad
741 operare con un qualsivoglia altro software. Tale negazione di garanzia
742 rimane in essere anche se i dententori del copyright, o qualsiasi altra
743 parte, è stata avvisata della possibilità di tali danneggiamenti.
745 Se decidete di utilizzare questo software, lo fate a vostro rischio
746 e pericolo. Se pensate che i termini di questa negazione di garanzia
747 non si confacciano alle vostre esigenze, o al vostro modo di
748 considerare un software, o ancora al modo in cui avete sempre trattato
749 software di terze parti, non usatelo. Se lo usate, accettate espressamente
750 questa negazione di garanzia e la piena responsabilità per qualsiasi
751 tipo di danno, di qualsiasi natura, possa derivarne.