Digest/HTTP.pm

filter: Statementstmt 35.4% 74 / 209 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 16 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 46.8% 15 / 32 Podpod 100% 1 / 1 totaltotal 26.7% 90 / 336 CC 42 SCAR 56.0
CC
42
Cov
25%
respond
702.0
__ANON__
110.0
__ANON__
42.0
CRAP 269.5
↑ Summary Digest/Driver.pm »
1 package Store::Digest::HTTP;
2  
3 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use Plack::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Plack::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use HTTP::Negotiate;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use DateTime::Format::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 1 ▶use XML::LibXML::LazyBuilder qw(DOM F E P);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 1 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use URI::ni;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 # XXX put this in a role or something
24 1 my %DIGESTS = (
25 'md5' => 16,
26 # 'ripemd-160' => 20,
27 'sha-1' => 20,
28 'sha-256' => 32,
29 'sha-384' => 48,
30 'sha-512' => 64,
31 );
32  
33 =head1 NAME
34  
35 Store::Digest::HTTP - Map HTTP methods and URI space to Store::Digest
36  
37 =head1 VERSION
38  
39 Version 0.01
40  
41 =cut
42  
43 1 our $VERSION = '0.01';
44  
45 =head1 SYNOPSIS
46  
47 use Store::Digest::HTTP;
48  
49 my $sd = Store::Digest::HTTP->new(store => $store);
50  
51 # $request is a HTTP::Request, Plack::Request, Catalyst::Request
52 # or Apache2::RequestRec. $response is a Plack::Response.
53  
54 my $response = $sd->respond($request);
55  
56 =head1 DESCRIPTION
57  
58 This module provides a reference implementation for an HTTP interface
59 to L<Store::Digest>, a content-addressable storage system based on
60 L<RFC 6920|http://tools.ietf.org/html/rfc6920> and named information
61 (C<ni:>) URIs and their HTTP expansions. It is intended to provide a
62 generic, content-based storage mechanism for opaque data objects,
63 either uploaded by users, or the results of computations. The goal of
64 this system is to act as a holding tank for both permanent storage and
65 temporary caching, with its preservation/expiration policy handled out
66 of scope.
67  
68 This module is designed with only a robust set of essential
69 functionality, with the expectation that it will be used as a
70 foundation for far more elaborate systems. Indeed, this module is
71 conceived primarily as an internal Web service which is only
72 accessible by trusted clients, even though through use it may be found
73 to exhibit value as a public resource.
74  
75 =head1 SECURITY
76  
77 This module has I<no concept> of access control, authentication or
78 authorization. Those concepts have been intentionally left out of
79 scope. There are more than enough existing mechanisms available to
80 protect, for instance, writing to and deleting from the store.
81 Preventing unauthorized reads is a little bit trickier.
82  
83 The locations of the indexes can obviously be protected from
84 unauthorized reading through straight-forward authentication
85 rules. The contents of the store, however, will require an
86 authorization system which is considerably more sophisticated.
87  
88 =head2 Scanning/Trawling
89  
90 With the default SHA-256 digest algorithm, this (or any other)
91 implementation will keel over long before the distance between hash
92 values becomes short enough that a brute force scan will be
93 feasible. That won't stop people from trying. Likewise, by default,
94 L<Store::Digest> computes (and this module exposes) shorter digests
95 like MD5 for the express purpose of matching objects to hashes in the
96 event that that's all you've got. If you don't want this behaviour,
97 you can use external access control mechanisms to wall off entire
98 digest algorithms, or consider disabling the computation of those
99 algorithms altogether (since in that case they're only costing you).
100  
101 A persistent danger pertaining to the feasibility of scanning, and
102 this is untested, is if some algorithm or other I<peaks>,
103 statistically, around certain values. This would drastically reduce
104 the effort required to score arbitrary hits, though they I<would> be
105 arbitrary.
106  
107 For all other intents and purposes, the likelihood that an attacker
108 could correctly guess the location of a sensitive piece of data,
109 I<especially> without setting off alarm bells, is infinitesimal.
110  
111 =head2 I<Go Fish> attacks
112  
113 If an attacker has a particular data object, he/she can ask the system
114 if it has that object as well, simply by generating a digest and
115 crafting a C<GET> request for it. This scenario is obviously
116 completely inconsequential, I<except> for the rare case wherein you
117 need to be able to repudiate having some knowledge or other, at which
118 point it could be severely damaging.
119  
120 =head2 Locking down individual objects
121  
122 The objects in the store should be seen as I<representations>:
123 I<images> of information. It is entirely conceivable, if not expressly
124 anticipated, that two abstract resources, one public and one
125 confidential, could have I<identical> literal representations, with
126 identical cryptographic signatures. This would amount to I<one> object
127 being stored, presumably with I<two> (or more) references to it
128 inscribed in some higher-level system. The difference between what is
129 confidential, and what is public, is in the context. As such, access
130 control to concrete I<representations> should be mediated by access
131 control to abstract I<resources>, in some other part of the system.
132  
133 =cut
134  
135 1 my %DISPATCH;
136  
137 =head1 RESOURCE TYPES
138  
139 All resources respond to C<OPTIONS> requests, which list available
140 methods. Requests for resources for methods that have not been
141 specified will result in a L<405 Method Not Allowed> response.
142  
143 =head2 Store contents: opaque data objects
144  
145 These resources are identified by their full digest value. By default,
146 that means these URI paths:
147  
148 /.well-known/[dn]i/{algorithm}/{digest}
149 /{algorithm}/{digest}
150  
151 ...where C<{algorithm}> is an active digest algorithm in the store,
152 and C<{digest}> is a complete, C<base64url> I<or> hexadecimal-encoded
153 cryptographic digest. If the digest is hexadecimal, the request will
154 be redirected (C<301> for C<GET>/C<HEAD>, C<307> for the rest) to its
155 C<base64url> equivalent.
156  
157 =cut
158  
159 1 $DISPATCH{object} = {};
160  
161 =head3 C<GET>/C<HEAD>
162  
163 When successful, this method returns the content of the identified
164 object. If the object has been deleted from the store, the response
165 will be C<410 Gone>. If it was never there in the first place, C<404
166 Not Found>. If the C<Accept-*> headers explicitly reject any of the
167 properties of the object, the response will properly be C<406 Not
168 Acceptable>.
169  
170 Since these resources only have one representation which by definition
171 cannot be modified, the C<If-*> headers respond appropriately. The
172 ETag of the object is equivalent to its C<ni:> URI (in double quotes,
173 as per L<RFC 2616|http://tools.ietf.org/html/rfc2616>).
174  
175 If the request includes a C<Range> header, the appropriate range will
176 be returned via C<206 Partial Content>. Note however that at this
177 time, multiple or non-byte ranges are not implemented, and such
178 requests will be met with a C<501 Not Implemented> error.
179  
180 =cut
181  
182 # one pattern here is moving the path into the query
183  
184 0 ▶$DISPATCH{object}{GET} = sub {
Subroutine __ANON__: not called CC=10 SCAR=47.0
185 # we need the algo and the digest and the header set
186 0 my ($self, $header, $query) = @_;
187 # put the algo/digest into the query component
188  
189 0 my $get = URI->new(sprintf 'ni:///%s;%s', @{$query}{qw(algorithm digest)});
190  
191 0 my @obj = $self->store->get($get);
192  
193 #warn scalar @obj;
194  
195 # ain't nothin' hurr
196 0 ▶ return [404, [], []] if @obj == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @obj == 0 0 0 0
197  
198 # partial match
199 0 ▶ if (@obj > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@obj > 1) 0 0 0
200 0 warn scalar @obj;
201 0 return [501, [], []];
202 }
203  
204 # exactly one object
205 0 my $obj = $obj[0];
206 0 ▶ my $lm = $obj->mtime || $obj->ctime;
Condition0%0/3
$obj->mtime || $obj->ctime
l!l&&r!l&&!r
000
MC/DC0%0/2
$obj->mtime || $obj->ctime
$obj->mtime $obj->ctime
Truth table0%0/3
A || B
A= $obj->mtimeB= $obj->ctime
ABresult
1X1
011
000
207 0 my $pri = $self->store->_primary;
208 0 my $ni = $obj->digest($pri);
209  
210 # baleeted
211 0 ▶ return [410, [], []] if $obj->dtime;
Branch: 1 branch
BranchTrueFalseTotal
if $obj->dtime 0 0 0
212  
213 # check etag
214 0 ▶ if (my $inm = $header->header('If-None-Match')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $inm = $header->header("If-None-Match")) 0 0 0
215 # XXX what happens if this is malformed?
216 0 $inm =~ tr/"//d;
217 0 $inm = URI->new($inm);
218 0 ▶ if ($inm->isa('URI::ni')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inm->isa("URI::ni")) 0 0 0
219 # get the right digest for the algorithm given in the etag
220 0 my $match = $obj->digest($inm->algorithm);
221 0 ▶ return [304, [], []] if $inm->eq($match);
Branch: 1 branch
BranchTrueFalseTotal
if $inm->eq($match) 0 0 0
222 }
223 #warn "INM: $inm";
224 }
225  
226 # check if-modified-since
227 0 ▶ if (my $ims = $header->header('If-Modified-Since')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ims = $header->header("If-Modified-Since")) 0 0 0
228 # XXX what happens if this is malformed?
229 0 $ims = DateTime::Format::HTTP->parse_datetime($ims);
230 0 ▶ return [304, [], []] if $lm <= $ims;
Branch: 1 branch
BranchTrueFalseTotal
if $lm <= $ims 0 0 0
231 #warn "IMS: $ims";
232 }
233  
234 0 my $cl = sprintf
235 '/.well-known/ni/%s/%s', $ni->algorithm, $ni->b64digest(1);
236  
237 # return plack arrayref?
238 0 [200, ['Content-Length' => $obj->size,
239 'Content-Type' => $obj->type,
240 'Last-Modified' => DateTime::Format::HTTP->format_datetime($lm),
241 'ETag' => qq{"$ni"},
242 'Content-Location' => $cl,
243 ], $obj->content];
244 1 };
245  
246 =head3 C<PUT>
247  
248 A store object responds to C<PUT> requests, primarily for the purpose
249 of symmetry, but it is also applicable to verifying arbitrary data
250 objects against supplied digests. That is, the URI of the C<PUT>
251 request B<must> match the actual digest of the object's contents in
252 the given algorithm. A mismatch between digest and content is
253 interpreted as an attempt to C<PUT> the object in question in the
254 wrong place, and is treated as C<403 Forbidden>.
255  
256 If, however, the digest matches, the response will be either C<204 No
257 Content> or C<201 Created>, depending on whether or not the object was
258 already in the store. A C<PUT> request with a C<Range> header makes no
259 sense in this context and is therefore not implemented, and will
260 appropriately respond with C<501 Not Implemented>.
261  
262 Any C<Date> header supplied with the request will become the C<mtime>
263 of the stored object, and will be reflected in the C<Last-Modified>
264 header in subsequent requests.
265  
266 =cut
267  
268 0 ▶$DISPATCH{object}{PUT} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
269  
270 # we need the algo, the digest, the header set, and the request body
271 1 };
272  
273 =head3 C<DELETE>
274  
275 B<Note:> This module has I<no> concept of access control.
276  
277 This request, as expected, unquestioningly deletes a store object,
278 provided one is present at the requested URI. If it is, the response
279 is C<204 No Content>. If not, the response is either C<404 Not Found>
280 or C<410 Gone>, depending on whether or not there ever was an object
281 at that location.
282  
283 =cut
284  
285 0 ▶$DISPATCH{object}{DELETE} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
286  
287 # we need the algo, and the digest, and that's it.
288 1 };
289  
290 =head3 C<PROPFIND>
291  
292 A handler for the C<PROPFIND> request method is supplied to provide
293 direct access to the metadata of the objects in the store. Downstream
294 WebDAV applications can therefore use this module as a storage
295 back-end while only needing to interface at the level of HTTP and/or
296 WebDAV.
297  
298 =cut
299  
300 0 ▶$DISPATCH{object}{PROPFIND} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
301 # we need the algo, digest, header set
302  
303 # *and* we need the dav request body
304 1 };
305  
306 =head3 C<PROPPATCH>
307  
308 B<Note:> This module has I<no> concept of access control.
309  
310 The C<PROPPATCH> method is supplied, first for parity with the
311 C<PROPFIND> method, but also so that automated agents, such as syntax
312 validators, can directly update the objects' metadata with their
313 findings.
314  
315 Here are the DAV properties which are currently editable:
316  
317 =over 4
318  
319 =item C<creationdate>
320  
321 This property sets the C<mtime> of the stored object, I<not> the
322 C<ctime>. The C<ctime> of a L<Store::Digest::Object> is the time it
323 was I<added> to the store, I<not> the modification time of the object
324 supplied when it was uploaded. Furthermore, per L<RFC
325 4918|http://tools.ietf.org/html/rfc4918>, the C<getlastmodified>
326 property SHOULD be considered I<protected>. As such, the meanings of
327 the C<creationdate> and C<getlastmodified> properties are inverted
328 from their intuitive values.
329  
330 (XXX: is this dumb? Will I regret it?)
331  
332 =item C<getcontentlanguage>
333  
334 This property permits the data object to be annotated with one or more
335 L<RFC 3066 (5646)|http://tools.ietf.org/html/rfc5646> language tags.
336  
337 =item C<getcontenttype>
338  
339 This property permits automated agents to update the content type, and
340 when applicable, the character set of the object. This is useful for
341 providing an interface for storing the results of an asynchronous
342 verification of the store's contents through a trusted mechanism,
343 instead of relying on the claim of whoever uploaded the object that
344 these values match their contents.
345  
346 =back
347  
348 =cut
349  
350 0 ▶$DISPATCH{object}{PROPPATCH} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
351 # we need algo, digest, header set, request body
352 1 };
353  
354 =head2 Individual metadata
355  
356 This is a read-only hypertext resource intended primarily as the
357 response content to a C<POST> of a new storage object, such that the
358 caller can retrieve the digest value and other useful metadata. It
359 also doubles as a user interface for successive manual uploads, both
360 as interstitial feedback and as a control surface.
361  
362 =cut
363  
364 1 $DISPATCH{meta} = {};
365  
366 =head3 C<GET>/C<HEAD>
367  
368 .../{algorithm}/{digest}?meta=true # not sure which of these yet
369 .../{algorithm}/{digest};meta # ... can't decide
370  
371 Depending on the C<Accept> header, this resource will either return
372 RDFa-embedded (X)HTML, RDF/XML or Turtle (or JSON-LD, or whatever).
373 The HTML version includes a rudimentary interface to the
374 C<multipart/form-data> C<POST> target.
375  
376 =cut
377  
378 0 ▶$DISPATCH{meta}{GET} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
379 # we need algo, digest, header set
380 1 };
381  
382 # the content-type of these GET handlers must be overrideable by query
383 # parameter, no?
384  
385 # sure,
386  
387 =head2 Partial matches
388  
389 Partial matches are read-only resources that return a list of links to
390 stored objects. The purpose is to provide an interface for retrieving
391 an object from the store when only the first few characters of its
392 digest are known. These resources are mapped under the following URI
393 paths by default:
394  
395 /.well-known/[dn]i/{algorithm}/{partial-digest}
396 /.well-known/[dn]i/{partial-digest}
397 /{algorithm}/{partial-digest}
398 /{partial-digest}
399  
400 ...where C<{algorithm}> is an active digest algorithm in the store,
401 and C<{partial-digest}> is an I<in>complete, C<base64url> or
402 hexadecimal-encoded cryptographic digest, that is, one that is
403 I<shorter> than the appropriate length for the given algorithm. If the
404 path is given with no algorithm, the length of the digest content
405 doesn't matter, and all algorithms will be searched.
406  
407 =head3 C<GET>/C<HEAD>
408  
409 A C<GET> request will return a simple web page containing a list of
410 links to the matching objects. If exactly one object matches, the
411 response will be C<302 Found> (in case additional objects match in the
412 future). If no objects match, the response will be C<404 Not
413 Found>. If multiple objects match, this response will be returned with
414 a C<300 Multiple Choices> status, to reinforce the transient nature of
415 the resource.
416  
417 B<TODO>: find or make an appropriate collection vocab, then implement
418 RDFa, RDF/XML, N3/Turtle, and JSON-LD variants.
419  
420 =cut
421  
422 0 ▶$DISPATCH{partial}{GET} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
423 # we need (maybe) algo, non-zero partial digest, header set
424 # my ($self, $
425 1 };
426  
427 =head3 C<PROPFIND>
428  
429 B<TODO>: A C<PROPFIND> response, if it even makes sense to implement,
430 will almost certainly be contingent on whatever vocab I decide on.
431  
432 =cut
433  
434 0 ▶$DISPATCH{partial}{PROPFIND} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
435 # we need (maybe) algo, non-zero partial digest, header set
436  
437 # *and* we need the dav request body
438  
439 # another way to handle this is to compile the digests beforehand
440 1 };
441  
442 =head2 Resource collections
443  
444 These collections exist for diagnostic purposes, so that during
445 development we may examine the contents of the store without any
446 apparatus besides a web browser. By default, the collections are bound
447 to the following URI paths:
448  
449 /.well-known/[dn]i/{algorithm}/
450 /{algorithm}/
451  
452 The only significance of the C<{algorithm}> in the URI path is as a
453 residual sorting parameter, to be used only after the contents of the
454 store have been sorted by all other specified parameters. Otherwise
455 the results are the same for all digest algorithms. The default
456 sorting behaviour is to ascend lexically, first by type, then
457 modification time (then tiebreak by whatever other means remain).
458  
459 =cut
460  
461 1 $DISPATCH{collection} = {};
462  
463 =head3 C<GET>/C<HEAD>
464  
465 These resources are bona fide collections and will reflect the
466 convention by redirecting via C<301 Moved Permanently> to a path with
467 a trailing slash C</>. (Maybe?)
468  
469 This is gonna have to respond to filtering, sort order and pagination.
470  
471 (optional application/atom+xml variant?)
472  
473 Here are the available parameters:
474  
475 =over 4
476  
477 =item C<tz> (ISO 8601 time zone)
478  
479 Resolve date parameters against this time zone rather than the default
480 (UTC).
481  
482 tz=-0800
483  
484 (XXX: use Olson rather than ISO-8601 so we don't have to screw around
485 with daylight savings? whynotboth.gif?)
486  
487 =item C<boundary>
488  
489 Absolute offset of bounding record, starting with 1. One value present
490 sets the upper bound; two values define an absolute range:
491  
492 boundary=100 # 1-100
493 boundary=1&boundary=100 # same thing
494 boundary=101&boundary=200 # 101-200
495  
496 =item C<sort> (Filter parameter name)
497  
498 One or more instances of this parameter, in the order given, override
499 the default sorting criterion, which is this:
500  
501 sort=type&sort=mtime
502  
503 =item C<reverse> (Boolean)
504  
505 Flag for specifying a reverse sort order:
506  
507 reverse=true
508  
509 =item C<complement> (Filter parameter name)
510  
511 Use the complement of the specified filter criteria:
512  
513 type=text/html&complement=type # everything but text/html
514  
515 =back
516  
517 Here are the sorting/filtering criteria:
518  
519 =over 4
520  
521 =item C<size>
522  
523 The number of bytes, as a range. One for lower bound, two for a range:
524  
525 size=1048576 # at least a megabyte
526 size=0&size=1024 # no more than a kilobyte
527  
528 =item C<type>
529  
530 The C<Content-Type> of the object. Enumerable:
531  
532 type=text/html&type=text/plain&type=application/xml
533  
534 =item C<charset>
535  
536 The character set of the object. Enumerable:
537  
538 charset=utf-8&charset=iso-8859-1&charset=windows-1252
539  
540 =item C<encoding>
541  
542 The C<Content-Encoding> of the object. Enumerable:
543  
544 encoding=gzip&encoding=bzip2&encoding=identity
545  
546 =item C<ctime>
547  
548 The I<creation> time, as in the time the object was added to the
549 store. One for I<lower> bound, two for range:
550  
551 ctime=2012-01-01 # everything added since January 1, 2012
552 ctime=2012-01-01&ctime=2012-12-31 # only the year of 2012
553  
554 Applying C<complement> to this parameter turns the one-instance form
555 into an I<upper> bound, and the range to mean everything I<but> its
556 contents. This parameter takes ISO 8601 datetime strings or subsets
557 thereof, or epoch seconds.
558  
559 =item C<mtime>
560  
561 Same syntax as C<ctime>, except concerns the modification time
562 supplied by the I<user> when the object was inserted into the store.
563  
564 =item C<ptime>
565  
566 Same as above, except concerns the latest time at which only the
567 I<metadata> of the object was modified.
568  
569 =item C<dtime>
570  
571 Same as above, except concerns the latest time the object was
572 I<deleted>. As should be expected, if this parameter is used, objects
573 which are currently present in the store will be omitted. Only the
574 traces of deleted objects will be shown.
575  
576 =back
577  
578 =cut
579  
580 0 ▶$DISPATCH{collection}{GET} = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
581 0 my ($self, $header, $query) = @_;
582 # we need the algo, the header set, and all those other params
583  
584 #my @obj = $self->store->get('', $self->store->_primary);
585 0 my @obj = $self->store->get('', $query->{algorithm});
586  
587 0 my @lol;
588 0 for my $obj (@obj) {
589 #warn $obj->as_string;
590 0 my $ni = $obj->digest($query->{algorithm});
591 #warn $ni;
592 0 my $hex = $ni->hexdigest;
593 0 ▶ push @lol, E li => {},
Condition0%0/3
$obj->mtime || $obj->ctime
l!l&&r!l&&!r
000
MC/DC0%0/2
$obj->mtime || $obj->ctime
$obj->mtime $obj->ctime
Truth table0%0/3
A || B
A= $obj->mtimeB= $obj->ctime
ABresult
1X1
011
000
594 (E a => { href => $ni->b64digest(1) }, $hex), ' ',
595 (E span => {}, $obj->type), ' ',
596 (E span => {}, $obj->size), ' ',
597 (E span => {}, sprintf('%s', $obj->mtime||$obj->ctime));
598 }
599  
600 0 my $doc = DOM (E html => { xmlns => 'http://www.w3.org/1999/xhtml' },
601 (E head => {}, (E title => {}, 'lol')),
602 (E body => {},
603 (E ul => {}, @lol)));
604 0 my $foo = $doc->toString(1);
605  
606 0 [200, ['Content-Type' => 'application/xhtml+xml',
607 'Cache-Control' => 'no-cache'],
608 [$foo]];
609 1 };
610  
611 =head3 C<PROPFIND>
612  
613 B<TODO>: Again, C<PROPFIND> responses, not sure how to define 'em at
614 this time.
615  
616 =cut
617  
618 0 ▶$DISPATCH{collection}{PROPFIND} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
619 # we need the algo, the header set, and (maybe) all those other params
620  
621 # *and* we need the dav request body
622  
623 # are you ready for n-million-plus element xml documents?
624 1 };
625  
626 =head2 Summary and usage statistics
627  
628 This resource acts as the "home page" of this module. Here we can
629 observe the contents of L<Store::Digest::Stats>, such as number of
630 objects stored, global modification times, storage consumption ,
631 reclaimed, space, etc. We can also choose our preferred time zone and
632 digest algorithm for browsing the store's contents, as well as upload
633 a new file.
634  
635 =cut
636  
637 1 $DISPATCH{stats} = {};
638  
639 =head3 C<GET>/C<HEAD>
640  
641 Depending on the C<Accept> header, this handler returns a simple web
642 page or set of RDF triples.
643  
644 =cut
645  
646 0 ▶$DISPATCH{stats}{GET} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
647 0 my $self = shift;
648 # we just need the header set for conneg.
649  
650 0 my $stats = $self->store->stats->as_string;
651 0 utf8::downgrade($stats);
652 0 my $len = length $stats;
653  
654 0 return [200, ['Content-Type' => 'text/plain',
655 'Content-Length' => $len], [$stats]];
656 1 };
657  
658 =head3 C<PROPFIND>
659  
660 B<TODO>: Define RDF vocab before PROPFIND.
661  
662 =cut
663  
664 0 ▶$DISPATCH{stats}{PROPFIND} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
665 # we just need the header set for conneg.
666  
667 # *and* we need the dav request body
668 1 };
669  
670 =head2 C<POST> target, raw
671  
672 This is a URI that only handles POST requests, which enable a thin
673 (e.g., API) HTTP client to upload a data object without the effort or
674 apparatus needed to compute its digest. Headers of interest to the
675 request are naturally C<Content-Type>, and C<Date>. The path of this
676 URI is set in the constructor, and defaults to:
677  
678 /0c17e171-8cb1-4c60-9c58-f218075ae9a9
679  
680 =cut
681  
682 1 $DISPATCH{raw} = {};
683  
684 =head3 C<POST>
685  
686 This response accepts the request content and attempts to store it. If
687 unsuccessful, it will return either C<507 Insufficient Storage> or
688 C<500 Internal Server Error>. If successful, the response will
689 redirect via C<303 See Other> to the appropriate L</Individual
690 metadata> resource.
691  
692 This resource is intended to be used in a pipeline with other web
693 service code. C<POST>ed request entities to this location will be
694 inserted into the store I<as-is>. B<Do not> C<POST> to this location
695 from a Web form unless that's what you want to have happen. Use the
696 other target instead.
697  
698 The contents of the following request headers are stored along with
699 the content of the request body:
700  
701 =over 4
702  
703 =item *
704  
705 C<Content-Type>
706  
707 =item *
708  
709 C<Content-Language>
710  
711 =item *
712  
713 C<Content-Encoding>
714  
715 =item *
716  
717 C<Date>
718  
719 =back
720  
721 =cut
722  
723 0 ▶$DISPATCH{raw}{POST} = sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
724 0 my ($self, $header, $query, $content) = @_;
725  
726 # XXX there is probably a way more clever way of doing this but i
727 # don't care
728 0 my %p = (content => $content);
729 0 ▶ if (my $x = $header->content_type) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $x = $header->content_type) 0 0 0
730 0 $p{type} = $x;
731 }
732 0 ▶ if (my $x = $header->content_type_charset) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $x = $header->content_type_charset) 0 0 0
733 0 $p{charset} = $x;
734 }
735 0 ▶ if (my $x = $header->content_encoding) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $x = $header->content_encoding) 0 0 0
736 0 $p{encoding} = $x;
737 }
738 0 ▶ if (my $x = $header->content_language) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $x = $header->content_language) 0 0 0
739 0 $p{type} = $x;
740 }
741 0 ▶ if (my $x = $header->date) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $x = $header->date) 0 0 0
742 #warn $x;
743 0 $p{mtime} = $x; #DateTime->from_epoch(epoch => $x);
744 }
745  
746 0 my $store = $self->store;
747  
748 0 my $obj = $store->add(%p);
749 #eval { $store->add(%p) };
750 #if ($@
751 #return [500, [], []] if $@;
752 0 my $pri = $store->_primary;
753 0 my $ni = $obj->digest($pri);
754 0 my $cl = sprintf
755 '/.well-known/ni/%s/%s', $ni->algorithm, $ni->b64digest(1);
756  
757 # XXX is this in gross violation of HTTP semantics?
758 0 [204, ['Content-Location' => $cl, 'ETag' => qq{"$ni"}], []];
759 1 };
760  
761 # in the case of POST, we have a special location for
762 # multipart/form-data but otherwise take raw input directly to the
763 # POST location
764  
765 =head2 C<POST> target, multipart/form-data
766  
767 This resource behaves identically to the one above, except that takes
768 its data from C<multipart/form-data> fields rather than headers. This
769 resource is designed as part of a I<rudimentary> interface for adding
770 objects to the store. It is intended for use during development and
771 explicitly I<not> for production, outside the most basic requirements.
772 Its default URI path, also configurable in the constructor, is:
773  
774 /12d851b7-5f71-405c-bb44-bd97b318093a
775  
776 =cut
777  
778 1 $DISPATCH{form} = {};
779  
780 =head3 C<POST>
781  
782 This handler expects a C<POST> request with C<multipart/form-data>
783 content I<only>; any other content type will result in a C<409
784 Conflict>. The same response will occur if the request body does not
785 contain a file part. Malformed request content will be met with a
786 C<400 Bad Request>. The handler will process I<only> the I<first> file
787 part found in the request body; it will ignore the field name. If
788 there are C<Content-Type>, C<Date>, etc. headers in the MIME subpart,
789 those will be stored. The file's name, if supplied, is ignored, since
790 mapping names to content is deliberately out of scope for
791 L<Store::Digest>.
792  
793 =cut
794  
795 0 ▶$DISPATCH{form}{POST} = sub {
Subroutine __ANON__: not called CC=1 SCAR=0.0
796 1 };
797  
798 =head1 METHODS
799  
800 =head2 new
801  
802 my $sdh = Store::Digest::HTTP->new(store => $store);
803  
804 =over 4
805  
806 =item store
807  
808 This is a reference to a L<Store::Digest> object.
809  
810 =cut
811  
812 1 has store => (
813 is => 'ro',
814 isa => 'Store::Digest::Driver',
815 required => 1,
816 );
817  
818 =item base
819  
820 This is the base URI path, which defaults to C</.well-known/ni/>.
821  
822 =cut
823  
824 has base => (
825 is => 'ro',
826 isa => 'RegexpRef',
827 required => 0,
828 lazy => 1,
829 0 ▶ default => sub { qr!/\.well-known/[dn]i/+! },
Subroutine __ANON__: not called CC=1 SCAR=6.9
830 1 );
831  
832 =item post_raw
833  
834 This overrides the location of the raw C<POST> target, which defaults
835 to C</0c17e171-8cb1-4c60-9c58-f218075ae9a9>.
836  
837 =cut
838  
839 # XXX include some mechanism so this module can register the UUID URIs
840  
841 1 has post_raw => (
842 is => 'ro',
843 isa => 'Str',
844 required => 0,
845 lazy => 1,
846 default => '0c17e171-8cb1-4c60-9c58-f218075ae9a9',
847 );
848  
849 =item post_form
850  
851 This overrides the location of the form-interpreted C<POST> target,
852 which defaults to C</12d851b7-5f71-405c-bb44-bd97b318093a>.
853  
854 If the
855  
856 =cut
857  
858 1 has post_form => (
859 is => 'ro',
860 isa => 'Str',
861 required => 0,
862 lazy => 1,
863 default => '12d851b7-5f71-405c-bb44-bd97b318093a',
864 );
865  
866  
867 =item param_map
868  
869 Any of the URI query parameters used in this module can be remapped to
870 different literals using a HASH reference like so:
871  
872 # in case 'mtime' collides with some other parameter elsewhere
873 { modified => 'mtime' }
874  
875 =back
876  
877 =cut
878  
879 has param_map => (
880 is => 'ro',
881 isa => 'HashRef',
882 required => 0,
883 lazy => 1,
884 0 ▶ default => sub { { } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
885 1 );
886  
887 =head2 respond
888  
889 my $response = $sdh->respond($request);
890  
891 =cut
892  
893 # ok this thing should be able to handle a HTTP::Request,
894 # Plack::Request, Catalyst::Request, and Apache2::RequestRec
895  
896 # we only care about the method, request-uri, headers for just
897 # about everything except POST and PUT (and PROPFIND/PROPPATCH).
898  
899 # We should normalize all body input to an IO handle or duck type
900 # in the case of apache
901  
902 0 ▶sub respond {
Subroutine respond: not called CC=26 SCAR=65.5
Pod documented
903 0 my ($self, $req) = @_;
904 0 ▶ $req = Plack::Request->new($req) unless Scalar::Util::blessed($req);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($req) 0 0 0
905 # we'll start by doing this for Plack, and then we'll fill in the
906 # other HTTP drivers.
907  
908 # now that that's sorted out, here's the resolver:
909  
910 0 my $header = $req->headers;
911 0 my $body = $req->body;
912 0 my $uri = $req->uri;
913 0 my $path = $uri->path;
914 0 my $query = $uri->query_form_hash;
915 0 my $base = $self->base;
916  
917 # first we should clip off the prefix(es)
918  
919 0 $path =~ s!^$base!!;
920 0 $path =~ s!^/*!!;
921  
922 #warn $path;
923  
924 0 my @segments = split m!/+!, $path, -1;
925  
926 #warn join('/', @segments);
927  
928 # here's the all-important resource type
929 0 my $type;
930  
931 0 ▶ if (@segments == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@segments == 0) { } 0 0 0
932 # root
933 0 $type = 'stats';
934 }
935 else {
936 0 ▶ my @algorithms = @{$self->store->_algorithms || []};
Condition0%0/2
$self->store->_algorithms || []
l!l
00
MC/DC0%0/1
$self->store->_algorithms || []
$self->store->_algorithms
Truth table0%0/2
A
A= $self->store->_algorithms
Aresult
11
00
937 0 ▶ if (grep { $_ eq $segments[0] } @algorithms) {
Branch: 3 branches
BranchTrueFalseTotal
if (grep {$_ eq $segments[0];} @algorithms) { } 0 0 0
elsif ($segments[0] eq $self->post_raw) { } 0 0 0
elsif ($segments[0] eq $self->post_form) { } 0 0 0
938 # we know this is now an algorithm
939 0 my $algo = $query->{algorithm} = $segments[0];
940  
941 0 ▶ if (defined $segments[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $segments[1]) { } 0 0 0
942 0 ▶ if ($segments[1] ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($segments[1] ne '') { } 0 0 0
943 0 ▶ unless ($segments[1] =~ /^[0-9A-Za-z_-]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($segments[1] =~ /^[0-9A-Za-z_-]+$/) 0 0 0
944 # no matcho
945 0 return [404, [], []];
946 }
947 0 my $b64len = POSIX::ceil($DIGESTS{$algo} * 4/3);
948 0 my $hexlen = $DIGESTS{$algo} * 2;
949 0 my $seglen = length $segments[1];
950 #warn "$seglen $b64len";
951 # could be partial, could be full
952 0 ▶ if ($seglen == $b64len) {
Branch: 2 branches
BranchTrueFalseTotal
if ($seglen == $b64len) { } 0 0 0
elsif ($seglen =~ /^[0-9A-Fa-f]{$hexlen}$/) { } 0 0 0
953 0 $type = 'object';
954 }
955 elsif ($seglen =~ /^[0-9A-Fa-f]{$hexlen}$/) {
956 0 $type = 'object';
957 0 $query->{radix} = 16;
958 }
959 else {
960 0 $type = 'partial';
961 }
962  
963 0 $query->{digest} = $segments[1];
964 }
965 else {
966 # definitely a collection
967 0 $type = 'collection';
968 }
969 }
970 else {
971 # this is a collection; redirect 307 with trailing /
972  
973 # the base was a regex so we want to retrieve what was
974 # actually matched by subtracting the altered path
975 # from the original path.
976 0 my $fullpath = $uri->path;
977  
978 # pretty sure these are already done but whatev
979 0 utf8::downgrade($fullpath);
980 0 utf8::downgrade($path);
981  
982 # aaand the surgery:
983 0 my $pdiff = substr($fullpath, 0, - length $path);
984 0 warn $pdiff;
985 0 my $clone = $uri->clone;
986 0 ▶ my $new = ($pdiff =~ m!/$!) ? "$pdiff$algo/" : "$pdiff/$algo/";
Branch: 1 branch
BranchTrueFalseTotal
$pdiff =~ m[/$] ? : 0 0 0
987 0 $clone->path($new);
988  
989 0 return [307, [Location => $clone], []];
990 }
991 }
992 elsif ($segments[0] eq $self->post_raw) {
993 0 $type = 'raw';
994 }
995 elsif ($segments[0] eq $self->post_form) {
996 # only form-data plz
997 0 ▶ return [415, [], []]
Branch: 1 branch
BranchTrueFalseTotal
unless $header->content_type eq "multipart/form-data" 0 0 0
998 unless $header->content_type eq 'multipart/form-data';
999  
1000 0 ▶ if (my ($field) = $req->upload) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($field) = $req->upload) { } 0 0 0
1001 0 my ($upload) = $req->upload($field);
1002 # overwrite content file handle
1003 0 open $body, $upload->path;
1004 0 binmode $body;
1005  
1006 #my $x = do { local $/; <$body> };
1007 #warn $x;
1008  
1009 #seek($body, 0, 0);
1010  
1011 # overwrite headers
1012 0 my $h = $upload->headers;
1013  
1014 0 warn $header->as_string, $h->as_string;
1015  
1016 # override date header if one is not included
1017 0 ▶ $h->date($header->date) if $header->date and !$h->date;
Branch: 1 branch
BranchTrueFalseTotal
if $header->date and not $h->date 0 0 0
Condition0%0/3
$header->date and not $h->date
!ll&&!rl&&r
000
MC/DC0%0/2
$header->date and not $h->date
$header->date not $h->date
Truth table0%0/3
A and not(B)
A= $header->dateB= not $h->date
ABresult
0X0
100
111
1018 0 $header = $h;
1019  
1020 # duplicate raw type
1021 0 $type = 'raw';
1022 }
1023 else {
1024 0 warn 'no upload field';
1025 0 warn join(', ', $req->body_parameters->keys);
1026 0 warn $header->as_string;
1027  
1028 0 return [409, [], []];
1029 }
1030 }
1031 else {
1032 # definitely partial
1033 0 ▶ unless ($segments[0] =~ /^[0-9A-Za-z_-]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($segments[0] =~ /^[0-9A-Za-z_-]+$/) 0 0 0
1034 # no matcho
1035 0 return [404, [], []];
1036 }
1037 0 $type = 'partial';
1038 0 $query->{digest} = $segments[0];
1039 }
1040 }
1041  
1042 # find the correct resource type
1043 0 ▶ if (my $dispatch = $DISPATCH{$type || ''}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dispatch = $DISPATCH{$type or ''}) { } 0 0 0
Condition0%0/2
$type || ''
l!l
00
MC/DC0%0/1
$type || ''
$type
Truth table0%0/2
A
A= $type
Aresult
11
00
1044  
1045 # now check request method
1046 0 my $meth = $req->method;
1047 0 ▶ my $test = $meth eq 'HEAD' ? 'GET' : $meth;
Branch: 1 branch
BranchTrueFalseTotal
$meth eq 'HEAD' ? : 0 0 0
1048 0 ▶ if (my $sub = $dispatch->{$test}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sub = $dispatch->{$test}) { } 0 0 0
1049 #warn "$type $test";
1050 # eval the handler
1051 0 my $ret = eval { $sub->($self, $header, $query, $body) };
1052  
1053 # if the handler raises, return 500
1054 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1055 0 return [500, [], [$@]];
1056 }
1057  
1058 # the code hasn't been written yet, lulz
1059 0 ▶ unless ($ret && ref $ret eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ret and ref $ret eq "ARRAY") 0 0 0
Condition0%0/3
$ret and ref $ret eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$ret and ref $ret eq "ARRAY"
$ret ref $ret eq "ARRAY"
Truth table0%0/3
A and B
A= $retB= ref $ret eq "ARRAY"
ABresult
0X0
100
111
1060 0 return [501, [], []];
1061 }
1062  
1063 0 ▶ if ($meth eq 'HEAD') {
Branch: 1 branch
BranchTrueFalseTotal
if ($meth eq "HEAD") 0 0 0
1064 #warn 'lol';
1065 0 $ret->[2] = [];
1066 }
1067  
1068 # that's all folks
1069 0 return $ret;
1070 }
1071 else {
1072 # if the resource type does not have a handler for the
1073 # request method, return 405
1074 0 return [405, [], []];
1075 }
1076 }
1077 else {
1078 # if we don't positively identify a resource type, return 404
1079 0 return [404, [], []];
1080 }
1081 }
1082  
1083 =head1 TO DO
1084  
1085 I think diff coding/instance manipulation (L<RFC
1086 3229|http://tools.ietf.org/html/rfc3229> and L<RFC
1087 3284|http://tools.ietf.org/html/rfc3284>) would be pretty cool. Might
1088 be better handled by some other module,
1089  
1090 =head1 AUTHOR
1091  
1092 Dorian Taylor, C<< <dorian at cpan.org> >>
1093  
1094 =head1 LICENSE AND COPYRIGHT
1095  
1096 Copyright 2012 Dorian Taylor.
1097  
1098 Licensed under the Apache License, Version 2.0 (the "License"); you
1099 may not use this file except in compliance with the License. You may
1100 obtain a copy of the License at
1101 L<http://www.apache.org/licenses/LICENSE-2.0>.
1102  
1103 Unless required by applicable law or agreed to in writing, software
1104 distributed under the License is distributed on an "AS IS" BASIS,
1105 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
1106 implied. See the License for the specific language governing
1107 permissions and limitations under the License.
1108  
1109  
1110 =cut
1111  
1112 1 __PACKAGE__->meta->make_immutable;
1113  
1114 1 1; # End of Store::Digest::HTTP
↑ Summary Digest/Driver.pm »