Server.pm

filter: Statementstmt 66.6% 4 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 75.0% 6 / 8 CC 1 SCAR 1.4
CC
1
Cov
67%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
« Server/Authorization.pm ↑ Summary Server/PSGI.pm »
1 package Net::Blossom::Server;
2  
3 13 ▶use strictures 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 0 ▶use Net::Blossom ();
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Net::Blossom::BlobDescriptor;
7 use Net::Blossom::_ConstructorArgs ();
8 use Net::Blossom::Server::AuthorizationResult;
9 use Net::Blossom::Server::BlobResult;
10 use Net::Blossom::Server::Error;
11 use Net::Blossom::Server::Request;
12 use Net::Blossom::Server::Response;
13 use Net::Blossom::Server::Storage;
14 use Net::Blossom::Server::UploadResult;
15  
16 use Carp qw(croak);
17 use Class::Tiny qw(storage mirror_fetcher max_upload_bytes), {
18 chunk_size => 65536,
19 clock => sub { sub { time } },
20 max_list_limit => 100,
21 };
22 use Digest::SHA ();
23 use JSON ();
24 use Scalar::Util qw(blessed);
25 use URI ();
26  
27 our $VERSION = '0.001004';
28  
29 my $HEX64 = qr/\A[0-9a-f]{64}\z/;
30 my $JSON = JSON->new->utf8;
31 my $MAX_MIRROR_REQUEST_BYTES = 65536;
32 my $DEFAULT_MAX_LIST_LIMIT = 100;
33  
34 # Content types a browser renders as active content (can execute script) when
35 # served inline. Blobs are attacker-supplied, so these are sent as downloads
36 # rather than rendered in the origin's security context. Everything else
37 # (images, audio, video, PDF, plain text, octet-stream) is left inline, which
38 # BUD-01 relies on for blobs to be "correctly displayed by clients".
39 my %ATTACHMENT_ONLY_TYPES = map { $_ => 1 } qw(
40 text/html
41 application/xhtml+xml
42 image/svg+xml
43 application/xml
44 text/xml
45 );
46  
47 sub _blob_response_headers {
48 my ($descriptor) = @_;
49  
50 my %headers = (
51 'Content-Type' => $descriptor->type,
52 'Content-Length' => $descriptor->size,
53 'Accept-Ranges' => 'bytes',
54  
55 # Do not let the browser second-guess the declared type: a blob served
56 # as text/plain or application/octet-stream must not be sniffed into
57 # HTML and executed.
58 'X-Content-Type-Options' => 'nosniff',
59 );
60  
61 my $type = $descriptor->type;
62 if (defined $type) {
63 (my $base = lc $type) =~ s/;.*//s; # drop parameters like "; charset=utf-8"
64 $base =~ s/\s+//g;
65 $headers{'Content-Disposition'} = 'attachment' if $ATTACHMENT_ONLY_TYPES{$base};
66 }
67  
68 return \%headers;
69 }
70  
71 sub BUILDARGS {
72 my $class = shift;
73 my %args = Net::Blossom::_ConstructorArgs::normalize(@_);
74 my %known = map { $_ => 1 } qw(storage chunk_size clock mirror_fetcher max_upload_bytes max_list_limit);
75 my @unknown = grep { !exists $known{$_} } keys %args;
76 croak "unknown argument(s): " . join(', ', sort @unknown) if @unknown;
77  
78 return \%args;
79 }
80  
81 sub BUILD {
82 my ($self) = @_;
83 Net::Blossom::Server::Storage->assert_implements($self->storage);
84  
85 croak "max_upload_bytes must be a positive integer"
86 if defined $self->max_upload_bytes
87 && (ref($self->max_upload_bytes) || $self->max_upload_bytes !~ /\A[1-9][0-9]*\z/);
88  
89 $self->max_list_limit($DEFAULT_MAX_LIST_LIMIT) unless defined $self->max_list_limit;
90 croak "max_list_limit must be a positive integer"
91 if ref($self->max_list_limit) || $self->max_list_limit !~ /\A[1-9][0-9]*\z/;
92  
93 $self->chunk_size(65536) unless defined $self->chunk_size;
94 croak "chunk_size must be a positive integer"
95 unless !ref($self->chunk_size) && $self->chunk_size =~ /\A[1-9][0-9]*\z/;
96  
97 $self->clock(sub { time }) unless defined $self->clock;
98 croak "clock must be a code reference" unless ref($self->clock) eq 'CODE';
99  
100 croak "mirror_fetcher must be a code reference or object with fetch_blob"
101 if defined $self->mirror_fetcher
102 && !(ref($self->mirror_fetcher) eq 'CODE'
103 || (blessed($self->mirror_fetcher) && $self->mirror_fetcher->can('fetch_blob')));
104  
105 return;
106 }
107  
108 sub receive_blob {
109 my $self = shift;
110 my ($body, %opts) = @_;
111 my %known = map { $_ => 1 } qw(
112 type expected_sha256 allowed_sha256 content_length uploaded pubkey
113 sha256_mismatch_status sha256_mismatch_reason
114 content_length_mismatch_status content_length_mismatch_reason
115 );
116 my @unknown = grep { !exists $known{$_} } keys %opts;
117 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
118  
119 croak "body is required" unless defined $body;
120 _validate_body($body);
121  
122 my $type = defined $opts{type} ? $opts{type} : 'application/octet-stream';
123 croak "type must be a scalar" if ref($type);
124 croak "type is required" unless length $type;
125  
126 if (defined $opts{expected_sha256}) {
127 croak "expected_sha256 must be 64-char lowercase hex"
128 unless !ref($opts{expected_sha256}) && $opts{expected_sha256} =~ $HEX64;
129 }
130 _validate_allowed_sha256($opts{allowed_sha256}) if defined $opts{allowed_sha256};
131  
132 _validate_content_length($opts{content_length}) if defined $opts{content_length};
133 _validate_uploaded($opts{uploaded}) if defined $opts{uploaded};
134 _validate_pubkey($opts{pubkey}) if defined $opts{pubkey};
135 _validate_http_status($opts{sha256_mismatch_status}, 'sha256_mismatch_status')
136 if defined $opts{sha256_mismatch_status};
137 croak "sha256_mismatch_reason must be a scalar"
138 if defined $opts{sha256_mismatch_reason} && ref($opts{sha256_mismatch_reason});
139 _validate_http_status($opts{content_length_mismatch_status}, 'content_length_mismatch_status')
140 if defined $opts{content_length_mismatch_status};
141 croak "content_length_mismatch_reason must be a scalar"
142 if defined $opts{content_length_mismatch_reason} && ref($opts{content_length_mismatch_reason});
143  
144 my %upload_context = (type => $type);
145 $upload_context{expected_sha256} = $opts{expected_sha256} if defined $opts{expected_sha256};
146 $upload_context{allowed_sha256} = [@{$opts{allowed_sha256}}] if defined $opts{allowed_sha256};
147 $upload_context{content_length} = $opts{content_length} if defined $opts{content_length};
148 $upload_context{pubkey} = $opts{pubkey} if defined $opts{pubkey};
149  
150 my $upload = $self->storage->begin_upload(%upload_context);
151 Net::Blossom::Server::Storage->assert_upload($upload);
152  
153 my $sha = Digest::SHA->new(256);
154 my $size = 0;
155 my $ok = eval {
156 $size = $self->_copy_body_to_upload($body, $upload, $sha);
157 _content_length_mismatch(%opts)
158 if defined $opts{content_length} && $size != $opts{content_length};
159  
160 my $sha256 = $sha->hexdigest;
161 _sha256_mismatch(%opts)
162 if defined $opts{expected_sha256} && $sha256 ne $opts{expected_sha256};
163 _sha256_mismatch(%opts, default_reason => 'sha256 is not allowed')
164 if defined $opts{allowed_sha256}
165 && !grep { $_ eq $sha256 } @{$opts{allowed_sha256}};
166  
167 my $uploaded = defined $opts{uploaded} ? $opts{uploaded} : $self->clock->();
168 my %commit_metadata = (
169 sha256 => $sha256,
170 size => $size,
171 type => $type,
172 uploaded => $uploaded,
173 );
174 $commit_metadata{pubkey} = $opts{pubkey} if defined $opts{pubkey};
175  
176 my $result = _upload_result_from_commit($upload->commit(%commit_metadata));
177 _validate_committed_descriptor($result->descriptor, $sha256, $size, $type);
178 $result;
179 };
180  
181 if (!$ok) {
182 my $error = $@;
183 eval { $upload->abort };
184 die $error;
185 }
186  
187 return $ok;
188 }
189  
190 sub handle_upload {
191 my $self = shift;
192 my ($request, %opts) = @_;
193 my %known = map { $_ => 1 } qw(pubkey);
194 my @unknown = grep { !exists $known{$_} } keys %opts;
195 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
196  
197 croak "request must be a Net::Blossom::Server::Request"
198 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
199 croak "upload request method must be PUT" unless $request->method eq 'PUT';
200 croak "upload request path must be /upload" unless $request->path eq '/upload';
201 croak "upload request body is required" unless defined $request->body;
202  
203 my %upload_opts;
204 $upload_opts{type} = $request->content_type if defined $request->content_type;
205 if (defined $request->content_length) {
206 $upload_opts{content_length} = $request->content_length;
207 $upload_opts{content_length_mismatch_status} = 400;
208 $upload_opts{content_length_mismatch_reason} = 'content_length mismatch';
209 }
210 $upload_opts{pubkey} = $opts{pubkey} if defined $opts{pubkey};
211 if (defined(my $expected_sha256 = _optional_sha256_header($request))) {
212 $upload_opts{expected_sha256} = $expected_sha256;
213 $upload_opts{sha256_mismatch_status} = 409;
214 $upload_opts{sha256_mismatch_reason} = 'sha256 mismatch';
215 }
216  
217 my $result = $self->receive_blob($request->body, %upload_opts);
218 return Net::Blossom::Server::Response->json(
219 $result->descriptor->to_hash,
220 status => $result->created ? 201 : 200,
221 );
222 }
223  
224 sub handle_head_upload {
225 my $self = shift;
226 my ($request, %opts) = @_;
227 my @unknown = keys %opts;
228 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
229  
230 croak "request must be a Net::Blossom::Server::Request"
231 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
232 croak "upload preflight method must be HEAD" unless $request->method eq 'HEAD';
233 croak "upload preflight path must be /upload" unless $request->path eq '/upload';
234  
235 my $error = _preflight_error($request);
236 return $error if defined $error;
237 return Net::Blossom::Server::Response->empty(200);
238 }
239  
240 sub handle_get_blob {
241 my $self = shift;
242 my ($request, %opts) = @_;
243 my @unknown = keys %opts;
244 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
245  
246 croak "request must be a Net::Blossom::Server::Request"
247 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
248 croak "blob request method must be GET" unless $request->method eq 'GET';
249  
250 my $sha256 = _sha256_from_blob_path($request->path, allow_extension => 1);
251 my $range_spec = _byte_range_spec($request->header('range'));
252 return $self->_get_full_blob($sha256) unless defined $range_spec;
253  
254 my ($descriptor, $body);
255 my $native_range = $self->storage->can('head_blob')
256 && $self->storage->can('get_blob_range');
257  
258 if ($native_range) {
259 my $head = $self->storage->head_blob($sha256);
260 return Net::Blossom::Server::Response->empty(404) unless defined $head;
261 $descriptor = _descriptor_from_head_result($head);
262 }
263 else {
264 my $result = $self->storage->get_blob($sha256);
265 return Net::Blossom::Server::Response->empty(404) unless defined $result;
266 _validate_blob_result($result, $sha256);
267 $descriptor = $result->descriptor;
268 $body = $result->body;
269 }
270  
271 croak "storage returned descriptor sha256 mismatch" unless $descriptor->sha256 eq $sha256;
272 my $range = _resolve_byte_range($range_spec, $descriptor->size);
273 if (!defined $range) {
274 $body->close if blessed($body) && $body->can('close');
275 return _range_not_satisfiable($descriptor->size);
276 }
277  
278 if ($native_range) {
279 $body = $self->storage->get_blob_range(
280 $sha256,
281 offset => $range->{offset},
282 length => $range->{length},
283 );
284 return Net::Blossom::Server::Response->empty(404) unless defined $body;
285 $body = _bounded_range_body($body, 0, $range->{length}, $self->chunk_size);
286 }
287 else {
288 $body = _bounded_range_body(
289 $body,
290 $range->{offset},
291 $range->{length},
292 $self->chunk_size,
293 );
294 }
295  
296 my $headers = _blob_response_headers($descriptor);
297 $headers->{'Content-Length'} = $range->{length};
298 $headers->{'Content-Range'} = sprintf 'bytes %d-%d/%d',
299 $range->{offset},
300 $range->{offset} + $range->{length} - 1,
301 $descriptor->size;
302  
303 return Net::Blossom::Server::Response->new(
304 status => 206,
305 headers => $headers,
306 body => $body,
307 );
308 }
309  
310 sub _get_full_blob {
311 my ($self, $sha256) = @_;
312 my $result = $self->storage->get_blob($sha256);
313 return Net::Blossom::Server::Response->empty(404) unless defined $result;
314 _validate_blob_result($result, $sha256);
315  
316 return Net::Blossom::Server::Response->new(
317 status => 200,
318 headers => _blob_response_headers($result->descriptor),
319 body => $result->body,
320 );
321 }
322  
323 sub handle_head_blob {
324 my $self = shift;
325 my ($request, %opts) = @_;
326 my @unknown = keys %opts;
327 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
328  
329 croak "request must be a Net::Blossom::Server::Request"
330 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
331 croak "blob head request method must be HEAD" unless $request->method eq 'HEAD';
332  
333 my $sha256 = _sha256_from_blob_path($request->path, allow_extension => 1);
334 my $descriptor;
335 if ($self->storage->can('head_blob')) {
336 my $result = $self->storage->head_blob($sha256);
337 return Net::Blossom::Server::Response->empty(404) unless defined $result;
338 $descriptor = _descriptor_from_head_result($result);
339 }
340 else {
341 my $result = $self->storage->get_blob($sha256);
342 return Net::Blossom::Server::Response->empty(404) unless defined $result;
343 croak "storage get_blob must return a Net::Blossom::Server::BlobResult"
344 unless blessed($result) && $result->isa('Net::Blossom::Server::BlobResult');
345 $descriptor = $result->descriptor;
346 }
347  
348 croak "storage returned descriptor sha256 mismatch" unless $descriptor->sha256 eq $sha256;
349  
350 return Net::Blossom::Server::Response->new(
351 status => 200,
352 headers => _blob_response_headers($descriptor),
353 body => '',
354 );
355 }
356  
357 sub handle_media {
358 my $self = shift;
359 my ($request, %opts) = @_;
360 my %known = map { $_ => 1 } qw(pubkey);
361 my @unknown = grep { !exists $known{$_} } keys %opts;
362 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
363  
364 croak "request must be a Net::Blossom::Server::Request"
365 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
366 croak "media request method must be PUT" unless $request->method eq 'PUT';
367 croak "media request path must be /media" unless $request->path eq '/media';
368 croak "media request body is required" unless defined $request->body;
369  
370 my %upload_opts;
371 $upload_opts{type} = $request->content_type if defined $request->content_type;
372 if (defined $request->content_length) {
373 $upload_opts{content_length} = $request->content_length;
374 $upload_opts{content_length_mismatch_status} = 400;
375 $upload_opts{content_length_mismatch_reason} = 'content_length mismatch';
376 }
377 $upload_opts{pubkey} = $opts{pubkey} if defined $opts{pubkey};
378 if (defined(my $expected_sha256 = _optional_sha256_header($request))) {
379 $upload_opts{expected_sha256} = $expected_sha256;
380 $upload_opts{sha256_mismatch_status} = 409;
381 $upload_opts{sha256_mismatch_reason} = 'sha256 mismatch';
382 }
383  
384 my $result = $self->receive_blob($request->body, %upload_opts);
385 return Net::Blossom::Server::Response->json(
386 $result->descriptor->to_hash,
387 status => $result->created ? 201 : 200,
388 );
389 }
390  
391 sub handle_head_media {
392 my $self = shift;
393 my ($request, %opts) = @_;
394 my @unknown = keys %opts;
395 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
396  
397 croak "request must be a Net::Blossom::Server::Request"
398 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
399 croak "media preflight method must be HEAD" unless $request->method eq 'HEAD';
400 croak "media preflight path must be /media" unless $request->path eq '/media';
401  
402 my $error = _preflight_error($request);
403 return $error if defined $error;
404 return Net::Blossom::Server::Response->empty(200);
405 }
406  
407 sub handle_mirror {
408 my $self = shift;
409 my ($request, %opts) = @_;
410 my %known = map { $_ => 1 } qw(pubkey authorization);
411 my @unknown = grep { !exists $known{$_} } keys %opts;
412 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
413  
414 croak "request must be a Net::Blossom::Server::Request"
415 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
416 croak "mirror request method must be PUT" unless $request->method eq 'PUT';
417 croak "mirror request path must be /mirror" unless $request->path eq '/mirror';
418 croak "mirror request body is required" unless defined $request->body;
419 croak "authorization must be a Net::Blossom::Server::AuthorizationResult"
420 if defined $opts{authorization}
421 && !(blessed($opts{authorization}) && $opts{authorization}->isa('Net::Blossom::Server::AuthorizationResult'));
422  
423 return Net::Blossom::Server::Response->error(503, 'Mirror service unavailable')
424 unless defined $self->mirror_fetcher;
425  
426 my $content = eval { _body_to_scalar($request->body, $MAX_MIRROR_REQUEST_BYTES) };
427 return _typed_error_response($@) if blessed($@) && $@->isa('Net::Blossom::Server::Error');
428 die $@ if $@;
429  
430 my $data = eval { $JSON->decode($content) };
431 return Net::Blossom::Server::Response->error(400, 'Malformed mirror request')
432 if $@ || ref($data) ne 'HASH';
433 return Net::Blossom::Server::Response->error(400, 'Invalid mirror URL')
434 unless exists $data->{url} && defined $data->{url} && !ref($data->{url}) && length $data->{url}
435 && _valid_mirror_url($data->{url});
436  
437 my %upload_opts = (
438 content_length_mismatch_status => 502,
439 content_length_mismatch_reason => 'origin content length mismatch',
440 );
441 $upload_opts{pubkey} = $opts{pubkey} if defined $opts{pubkey};
442 if (defined $opts{authorization}) {
443 $upload_opts{allowed_sha256} = $opts{authorization}->hashes;
444 $upload_opts{sha256_mismatch_status} = 409;
445 $upload_opts{sha256_mismatch_reason} = 'mirrored blob hash is not authorized';
446 }
447  
448 my $sink = Net::Blossom::Server::_MirrorSink->new(
449 server => $self,
450 opts => \%upload_opts,
451 );
452 my $metadata = eval {
453 _mirror_fetch_metadata(
454 _fetch_mirror_blob($self->mirror_fetcher, $data->{url}, sink => $sink),
455 );
456 };
457 if ($@) {
458 my $error = $@;
459 eval { $sink->abort };
460 return $error->as_response
461 if blessed($error) && $error->isa('Net::Blossom::Server::Error');
462 return Net::Blossom::Server::Response->error(502, 'Origin fetch failed');
463 }
464  
465 $sink->start(%$metadata) unless $sink->started;
466 my $result = eval { $sink->finish };
467 if (!$result) {
468 my $error = $@;
469 eval { $sink->abort };
470 die $error;
471 }
472  
473 return Net::Blossom::Server::Response->json(
474 $result->descriptor->to_hash,
475 status => $result->created ? 201 : 200,
476 );
477 }
478  
479 sub handle_delete_blob {
480 my $self = shift;
481 my ($request, %opts) = @_;
482 my %known = map { $_ => 1 } qw(pubkey);
483 my @unknown = grep { !exists $known{$_} } keys %opts;
484 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
485  
486 croak "request must be a Net::Blossom::Server::Request"
487 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
488 croak "delete request method must be DELETE" unless $request->method eq 'DELETE';
489 croak "pubkey is required" unless defined $opts{pubkey};
490 _validate_pubkey($opts{pubkey});
491  
492 my $sha256 = _sha256_from_blob_path($request->path);
493 my $deleted = $self->storage->delete_blob($sha256, pubkey => $opts{pubkey});
494 return Net::Blossom::Server::Response->empty(404) unless $deleted;
495 return Net::Blossom::Server::Response->empty(204);
496 }
497  
498 sub handle_list_blobs {
499 my $self = shift;
500 my ($request, %opts) = @_;
501 my @unknown = keys %opts;
502 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
503  
504 croak "request must be a Net::Blossom::Server::Request"
505 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
506 croak "list request method must be GET" unless $request->method eq 'GET';
507  
508 my $pubkey = _pubkey_from_list_path($request->path);
509 my %list_opts = _list_options_from_query($request->query, $self->max_list_limit);
510 my $blobs = $self->storage->list_blobs($pubkey, %list_opts);
511 croak "storage list_blobs must return an array reference" unless ref($blobs) eq 'ARRAY';
512  
513 my @body;
514 for my $blob (@$blobs) {
515 croak "storage list_blobs items must be Net::Blossom::BlobDescriptor"
516 unless blessed($blob) && $blob->isa('Net::Blossom::BlobDescriptor');
517 push @body, $blob->to_hash;
518 }
519  
520 return Net::Blossom::Server::Response->json(\@body, status => 200);
521 }
522  
523 sub handle_request {
524 my $self = shift;
525 my ($request, %opts) = @_;
526 my %known = map { $_ => 1 } qw(pubkey authorization);
527 my @unknown = grep { !exists $known{$_} } keys %opts;
528 croak "unknown option(s): " . join(', ', sort @unknown) if @unknown;
529  
530 croak "request must be a Net::Blossom::Server::Request"
531 unless blessed($request) && $request->isa('Net::Blossom::Server::Request');
532  
533 if ($request->path eq '/upload') {
534 return $self->handle_head_upload($request) if $request->method eq 'HEAD';
535 return $self->handle_upload($request, _pubkey_opt(%opts)) if $request->method eq 'PUT';
536 return Net::Blossom::Server::Response->empty(405, headers => { Allow => 'HEAD, PUT' });
537 }
538  
539 if ($request->path eq '/media') {
540 return $self->handle_head_media($request) if $request->method eq 'HEAD';
541 return $self->handle_media($request, _pubkey_opt(%opts)) if $request->method eq 'PUT';
542 return Net::Blossom::Server::Response->empty(405, headers => { Allow => 'HEAD, PUT' });
543 }
544  
545 if ($request->path eq '/mirror') {
546 return $self->handle_mirror($request, _mirror_opts(%opts)) if $request->method eq 'PUT';
547 return Net::Blossom::Server::Response->empty(405, headers => { Allow => 'PUT' });
548 }
549  
550 if ($request->path =~ m{\A/list/[0-9a-f]{64}\z}) {
551 return Net::Blossom::Server::Response->empty(405, headers => { Allow => 'GET' })
552 unless $request->method eq 'GET';
553 return $self->handle_list_blobs($request);
554 }
555  
556 if (_is_blob_retrieval_path($request->path)) {
557 if ($request->method eq 'GET') {
558 return $self->handle_get_blob($request);
559 }
560 if ($request->method eq 'HEAD') {
561 return $self->handle_head_blob($request);
562 }
563 if (_is_exact_blob_path($request->path) && $request->method eq 'DELETE') {
564 return $self->handle_delete_blob($request, _pubkey_opt(%opts));
565 }
566 my $allow = _is_exact_blob_path($request->path) ? 'DELETE, GET, HEAD' : 'GET, HEAD';
567 return Net::Blossom::Server::Response->empty(405, headers => { Allow => $allow });
568 }
569  
570 return Net::Blossom::Server::Response->empty(404);
571 }
572  
573 sub _pubkey_from_list_path {
574 my ($path) = @_;
575 my ($pubkey) = defined $path ? ($path =~ m{\A/list/([^/]+)\z}) : ();
576 croak "list request path must be /list/<pubkey>"
577 unless defined $pubkey && length($pubkey) == 64;
578 _validate_pubkey($pubkey);
579 return $pubkey;
580 }
581  
582 sub _sha256_from_blob_path {
583 my ($path, %opts) = @_;
584 my $pattern = $opts{allow_extension}
585 ? qr{\A/([^/.]+)(?:\.[^/]+)?\z}
586 : qr{\A/([^/]+)\z};
587 my ($sha256) = defined $path ? ($path =~ $pattern) : ();
588 croak "blob request path must be /<sha256>"
589 unless defined $sha256 && length($sha256) == 64;
590 croak "sha256 must be 64-char lowercase hex" unless $sha256 =~ $HEX64;
591 return $sha256;
592 }
593  
594 sub _list_options_from_query {
595 my ($query, $max_list_limit) = @_;
596  
597 # Query parameters are client input, so malformed values are a BUD-12 400,
598 # not an internal error.
599 my %known = map { $_ => 1 } qw(cursor limit);
600 my @unknown = grep { !exists $known{$_} } keys %$query;
601 _bad_list_query('unknown query parameter(s): ' . join(', ', sort @unknown)) if @unknown;
602  
603 my %opts;
604 if (exists $query->{cursor}) {
605 _bad_list_query('cursor must be a scalar') if ref($query->{cursor});
606 _bad_list_query('cursor must be 64-char lowercase hex') unless $query->{cursor} =~ $HEX64;
607 $opts{cursor} = $query->{cursor};
608 }
609  
610 if (exists $query->{limit}) {
611 _bad_list_query('limit must be a scalar') if ref($query->{limit});
612 _bad_list_query('limit must be a positive integer') unless $query->{limit} =~ /\A[1-9][0-9]*\z/;
613 _bad_list_query("limit must not exceed $max_list_limit") if $query->{limit} > $max_list_limit;
614 $opts{limit} = $query->{limit};
615 } else {
616 $opts{limit} = $max_list_limit;
617 }
618  
619 return %opts;
620 }
621  
622 sub _bad_list_query {
623 my ($reason) = @_;
624 Net::Blossom::Server::Error->throw(status => 400, reason => $reason);
625 }
626  
627 sub _pubkey_opt {
628 my (%opts) = @_;
629 return defined $opts{pubkey} ? (pubkey => $opts{pubkey}) : ();
630 }
631  
632 sub _mirror_opts {
633 my (%opts) = @_;
634 my %mirror_opts;
635 $mirror_opts{pubkey} = $opts{pubkey} if defined $opts{pubkey};
636 $mirror_opts{authorization} = $opts{authorization} if defined $opts{authorization};
637 return %mirror_opts;
638 }
639  
640 sub _is_exact_blob_path {
641 my ($path) = @_;
642 return defined $path && $path =~ m{\A/[0-9a-f]{64}\z};
643 }
644  
645 sub _is_blob_retrieval_path {
646 my ($path) = @_;
647 return defined $path && $path =~ m{\A/[0-9a-f]{64}(?:\.[^/]+)?\z};
648 }
649  
650 sub _optional_sha256_header {
651 my ($request) = @_;
652 my $sha256 = $request->header('x-sha-256');
653 return undef unless defined $sha256 && length $sha256;
654 Net::Blossom::Server::Error->throw(
655 status => 400,
656 reason => 'X-SHA-256 must be 64-char lowercase hex',
657 ) unless $sha256 =~ $HEX64;
658 return $sha256;
659 }
660  
661 sub _preflight_error {
662 my ($request) = @_;
663  
664 my $sha256 = $request->header('x-sha-256');
665 return Net::Blossom::Server::Response->error(400, 'Missing X-SHA-256 header')
666 unless defined $sha256 && length $sha256;
667 return Net::Blossom::Server::Response->error(400, 'Invalid X-SHA-256 header')
668 unless $sha256 =~ $HEX64;
669  
670 my $type = $request->header('x-content-type');
671 return Net::Blossom::Server::Response->error(400, 'Missing X-Content-Type header')
672 unless defined $type && length $type;
673  
674 my $length = $request->header('x-content-length');
675 return Net::Blossom::Server::Response->error(411, 'Missing X-Content-Length header')
676 unless defined $length && length $length;
677 return Net::Blossom::Server::Response->error(400, 'Invalid X-Content-Length header')
678 unless $length =~ /\A\d+\z/;
679  
680 return undef;
681 }
682  
683 sub _descriptor_from_head_result {
684 my ($result) = @_;
685  
686 return $result
687 if blessed($result) && $result->isa('Net::Blossom::BlobDescriptor');
688 if (blessed($result) && $result->isa('Net::Blossom::Server::BlobResult')) {
689 my $body = $result->body;
690 $body->close if blessed($body) && $body->can('close');
691 return $result->descriptor;
692 }
693  
694 croak "storage head_blob must return a Net::Blossom::BlobDescriptor or Net::Blossom::Server::BlobResult";
695 }
696  
697 sub _validate_blob_result {
698 my ($result, $sha256) = @_;
699 croak "storage get_blob must return a Net::Blossom::Server::BlobResult"
700 unless blessed($result) && $result->isa('Net::Blossom::Server::BlobResult');
701 croak "storage returned descriptor sha256 mismatch"
702 unless $result->descriptor->sha256 eq $sha256;
703 return 1;
704 }
705  
706 sub _byte_range_spec {
707 my ($header) = @_;
708 return undef unless defined $header && !ref($header);
709 return undef unless $header =~ /\Abytes=(\d*)-(\d*)\z/i;
710  
711 my ($first, $last) = ($1, $2);
712 return undef unless length($first) || length($last);
713 return undef if length($first) && length($last) && $last < $first;
714  
715 return length($first)
716 ? {
717 first => 0 + $first,
718 (length($last) ? (last => 0 + $last) : ()),
719 }
720 : {suffix => 0 + $last};
721 }
722  
723 sub _resolve_byte_range {
724 my ($spec, $size) = @_;
725  
726 if (exists $spec->{suffix}) {
727 return undef unless $spec->{suffix} > 0 && $size > 0;
728 my $length = $spec->{suffix} < $size ? $spec->{suffix} : $size;
729 return {
730 offset => $size - $length,
731 length => $length,
732 };
733 }
734  
735 return undef if $spec->{first} >= $size;
736 my $last = exists $spec->{last} && $spec->{last} < $size
737 ? $spec->{last}
738 : $size - 1;
739 return {
740 offset => $spec->{first},
741 length => $last - $spec->{first} + 1,
742 };
743 }
744  
745 sub _range_not_satisfiable {
746 my ($size) = @_;
747 return Net::Blossom::Server::Response->empty(
748 416,
749 headers => {
750 'Accept-Ranges' => 'bytes',
751 'Content-Range' => "bytes */$size",
752 },
753 );
754 }
755  
756 sub _bounded_range_body {
757 my ($body, $offset, $length, $chunk_size) = @_;
758  
759 if (!ref($body)) {
760 my $range = substr($body, $offset, $length);
761 croak "range body length must match requested length"
762 unless length($range) == $length;
763 return $range;
764 }
765  
766 if (ref($body) eq 'ARRAY') {
767 my @range;
768 my $remaining = $length;
769 my $skip = $offset;
770 for my $chunk (@$body) {
771 croak "range body chunks must be defined" unless defined $chunk;
772 croak "range body chunks must be scalars" if ref($chunk);
773 if ($skip >= length($chunk)) {
774 $skip -= length($chunk);
775 next;
776 }
777  
778 my $take = length($chunk) - $skip;
779 $take = $remaining if $take > $remaining;
780 push @range, substr($chunk, $skip, $take) if $take;
781 $remaining -= $take;
782 last unless $remaining;
783 $skip = 0;
784 }
785 croak "range body length must match requested length" if $remaining;
786 return \@range;
787 }
788  
789 croak "range body must be a scalar, array reference, or stream object"
790 unless blessed($body) && ($body->can('read') || $body->can('getline'));
791 return Net::Blossom::Server::_RangeStream->new(
792 body => $body,
793 offset => $offset,
794 remaining => $length,
795 chunk_size => $chunk_size,
796 );
797 }
798  
799 sub _typed_error_response {
800 my ($error) = @_;
801 return $error->as_response;
802 }
803  
804 sub _body_to_scalar {
805 my ($body, $max) = @_;
806 croak "body is required" unless defined $body;
807  
808 if (!ref($body)) {
809 _content_too_large() if length($body) > $max;
810 return $body;
811 }
812  
813 _validate_body($body);
814 my $content = '';
815 if ($body->can('read')) {
816 while (1) {
817 my $chunk = '';
818 my $read = $body->read($chunk, 8192);
819 croak "body stream read failed" unless defined $read;
820 last if $read == 0;
821 $content .= $chunk;
822 _content_too_large() if length($content) > $max;
823 }
824 return $content;
825 }
826  
827 while (defined(my $chunk = $body->getline)) {
828 croak "body chunks must be scalars" if ref($chunk);
829 $content .= $chunk;
830 _content_too_large() if length($content) > $max;
831 }
832 return $content;
833 }
834  
835 sub _content_too_large {
836 Net::Blossom::Server::Error->throw(
837 status => 413,
838 reason => 'Mirror request body is too large',
839 );
840 }
841  
842 sub _valid_mirror_url {
843 my ($value) = @_;
844 return 0 unless defined $value && !ref($value) && length $value;
845 return 0 if $value =~ /[\x00-\x20]/;
846  
847 my $uri = URI->new($value);
848 my $scheme = $uri->scheme;
849 return 0 unless defined $scheme && $scheme =~ /\Ahttps?\z/i;
850  
851 my $authority = eval { $uri->authority };
852 return 0 unless defined $authority && length $authority;
853 return 0 if $authority =~ /\@/;
854  
855 my $host = eval { $uri->host };
856 return 0 unless defined $host && length $host;
857  
858 my $userinfo = eval { $uri->userinfo };
859 return 0 if defined $userinfo && length $userinfo;
860 return 0 if defined $uri->fragment;
861  
862 return 1;
863 }
864  
865 sub _fetch_mirror_blob {
866 my ($fetcher, $url, %opts) = @_;
867 return $fetcher->($url, %opts) if ref($fetcher) eq 'CODE';
868 return $fetcher->fetch_blob($url, %opts);
869 }
870  
871 sub _mirror_fetch_metadata {
872 my ($result) = @_;
873 croak "mirror fetcher must return a hash reference" unless ref($result) eq 'HASH';
874 croak "mirror fetcher must stream into sink, not return body" if exists $result->{body};
875  
876 my %opts;
877 if (defined $result->{type}) {
878 croak "mirror fetcher result type must be a scalar" if ref($result->{type});
879 croak "mirror fetcher result type is required" unless length $result->{type};
880 $opts{type} = $result->{type};
881 }
882 if (defined $result->{content_length}) {
883 _validate_content_length($result->{content_length});
884 $opts{content_length} = $result->{content_length};
885 }
886  
887 return \%opts;
888 }
889  
890 sub _copy_body_to_upload {
891 my ($self, $body, $upload, $sha) = @_;
892 my $max = $self->max_upload_bytes;
893 my $size = 0;
894  
895 if (!ref($body)) {
896 _upload_too_large() if defined $max && length($body) > $max;
897 _write_upload_chunk($upload, $sha, $body);
898 return length $body;
899 }
900  
901 if ($body->can('read')) {
902 while (1) {
903 my $chunk = '';
904 my $read = $body->read($chunk, $self->chunk_size);
905 croak "body stream read failed" unless defined $read;
906 last if $read == 0;
907 _write_upload_chunk($upload, $sha, $chunk);
908 $size += length $chunk;
909 _upload_too_large() if defined $max && $size > $max;
910 }
911 return $size;
912 }
913  
914 while (defined(my $chunk = $body->getline)) {
915 _write_upload_chunk($upload, $sha, $chunk);
916 $size += length $chunk;
917 _upload_too_large() if defined $max && $size > $max;
918 }
919 return $size;
920 }
921  
922 sub _upload_too_large {
923 Net::Blossom::Server::Error->throw(
924 status => 413,
925 reason => 'Uploaded blob is too large',
926 );
927 }
928  
929 sub _write_upload_chunk {
930 my ($upload, $sha, $chunk) = @_;
931 croak "body chunks must be scalars" if ref($chunk);
932 $sha->add($chunk);
933 my $written = $upload->write($chunk);
934 croak "storage write failed" unless defined $written;
935 }
936  
937 sub _upload_result_from_commit {
938 my ($committed) = @_;
939  
940 return $committed
941 if blessed($committed) && $committed->isa('Net::Blossom::Server::UploadResult');
942  
943 if (ref($committed) eq 'HASH' && exists $committed->{descriptor}) {
944 my $descriptor = $committed->{descriptor};
945 $descriptor = Net::Blossom::BlobDescriptor->from_hash($descriptor)
946 if ref($descriptor) eq 'HASH';
947 return Net::Blossom::Server::UploadResult->new(
948 descriptor => $descriptor,
949 created => $committed->{created},
950 );
951 }
952  
953 my $descriptor;
954 $descriptor = $committed
955 if blessed($committed) && $committed->isa('Net::Blossom::BlobDescriptor');
956 $descriptor = Net::Blossom::BlobDescriptor->from_hash($committed)
957 if ref($committed) eq 'HASH';
958 return Net::Blossom::Server::UploadResult->new(
959 descriptor => $descriptor,
960 created => 1,
961 ) if defined $descriptor;
962  
963 croak "storage commit must return an upload result or blob descriptor";
964 }
965  
966 sub _validate_committed_descriptor {
967 my ($descriptor, $sha256, $size, $type) = @_;
968 croak "storage returned descriptor sha256 mismatch" unless $descriptor->sha256 eq $sha256;
969 croak "storage returned descriptor size mismatch" unless $descriptor->size == $size;
970 croak "storage returned descriptor type mismatch" unless $descriptor->type eq $type;
971 }
972  
973 sub _validate_body {
974 my ($body) = @_;
975 return unless ref($body);
976 return if blessed($body) && ($body->can('read') || $body->can('getline'));
977 croak "body must be a scalar or stream object";
978 }
979  
980 sub _validate_content_length {
981 my ($content_length) = @_;
982 croak "content_length must be a scalar" if ref($content_length);
983 croak "content_length must be a non-negative integer"
984 unless $content_length =~ /\A\d+\z/;
985 }
986  
987 sub _validate_allowed_sha256 {
988 my ($hashes) = @_;
989 croak "allowed_sha256 must be an array reference" unless ref($hashes) eq 'ARRAY';
990 for my $hash (@$hashes) {
991 croak "allowed_sha256 must contain 64-char lowercase hex values"
992 unless defined $hash && !ref($hash) && $hash =~ $HEX64;
993 }
994 }
995  
996 sub _validate_http_status {
997 my ($status, $name) = @_;
998 croak "$name must be an HTTP status code"
999 unless !ref($status) && $status =~ /\A[1-5][0-9][0-9]\z/;
1000 }
1001  
1002 sub _sha256_mismatch {
1003 my (%opts) = @_;
1004 my $reason = defined $opts{sha256_mismatch_reason}
1005 ? $opts{sha256_mismatch_reason}
1006 : ($opts{default_reason} || 'sha256 mismatch');
1007  
1008 if (defined $opts{sha256_mismatch_status}) {
1009 Net::Blossom::Server::Error->throw(
1010 status => $opts{sha256_mismatch_status},
1011 reason => $reason,
1012 );
1013 }
1014  
1015 croak $reason;
1016 }
1017  
1018 sub _content_length_mismatch {
1019 my (%opts) = @_;
1020 my $reason = defined $opts{content_length_mismatch_reason}
1021 ? $opts{content_length_mismatch_reason}
1022 : 'content_length mismatch';
1023  
1024 if (defined $opts{content_length_mismatch_status}) {
1025 Net::Blossom::Server::Error->throw(
1026 status => $opts{content_length_mismatch_status},
1027 reason => $reason,
1028 );
1029 }
1030  
1031 croak $reason;
1032 }
1033  
1034 sub _validate_uploaded {
1035 my ($uploaded) = @_;
1036 croak "uploaded must be a scalar" if ref($uploaded);
1037 croak "uploaded must be a non-negative integer"
1038 unless $uploaded =~ /\A\d+\z/;
1039 }
1040  
1041 sub _validate_pubkey {
1042 my ($pubkey) = @_;
1043 croak "pubkey must be a scalar" if ref($pubkey);
1044 croak "pubkey must be 64-char lowercase hex" unless $pubkey =~ $HEX64;
1045 }
1046  
1047 {
1048 package Net::Blossom::Server::_RangeStream;
1049  
1050 use strictures 2;
1051  
1052 use Carp qw(croak);
1053 use Class::Tiny qw(body offset remaining chunk_size), {
1054 buffer => '',
1055 closed => 0,
1056 };
1057 use Scalar::Util qw(blessed);
1058  
1059 sub BUILD {
1060 my ($self) = @_;
1061 croak "range body must be a stream object"
1062 unless blessed($self->{body})
1063 && ($self->{body}->can('read') || $self->{body}->can('getline'));
1064 $self->buffer;
1065 $self->closed;
1066 return;
1067 }
1068  
1069 sub read {
1070 my ($self, undef, $length) = @_;
1071 croak "read length must be a non-negative integer"
1072 unless defined $length && !ref($length) && $length =~ /\A[0-9]+\z/;
1073 $_[1] = '';
1074 return 0 if $self->{closed} || !$length;
1075  
1076 $self->_skip_prefix;
1077 my $want = $length < $self->{remaining} ? $length : $self->{remaining};
1078 my $chunk = $self->_read_source($want);
1079 if (!length($chunk)) {
1080 $self->close;
1081 croak "range body ended before requested length";
1082 }
1083  
1084 $_[1] = $chunk;
1085 $self->{remaining} -= length($chunk);
1086 $self->close unless $self->{remaining};
1087 return length($chunk);
1088 }
1089  
1090 sub getline {
1091 my ($self) = @_;
1092 my $chunk = '';
1093 my $read = $self->read($chunk, $self->{chunk_size});
1094 return unless $read;
1095 return $chunk;
1096 }
1097  
1098 sub close {
1099 my ($self) = @_;
1100 return 1 if $self->{closed};
1101 $self->{body}->close if $self->{body}->can('close');
1102 $self->{buffer} = '';
1103 $self->{closed} = 1;
1104 return 1;
1105 }
1106  
1107 sub _skip_prefix {
1108 my ($self) = @_;
1109 if (!$self->{body}->can('read')) {
1110 while ($self->{offset}) {
1111 my $chunk = $self->{body}->getline;
1112 if (!defined $chunk || !length($chunk)) {
1113 $self->close;
1114 croak "range body ended before requested offset";
1115 }
1116 croak "range body stream chunks must be scalars" if ref($chunk);
1117  
1118 if (length($chunk) <= $self->{offset}) {
1119 $self->{offset} -= length($chunk);
1120 next;
1121 }
1122  
1123 $self->{buffer} = substr(
1124 $chunk,
1125 $self->{offset},
1126 $self->{remaining},
1127 );
1128 $self->{offset} = 0;
1129 }
1130 return;
1131 }
1132  
1133 while ($self->{offset}) {
1134 my $want = $self->{offset} < $self->{chunk_size}
1135 ? $self->{offset}
1136 : $self->{chunk_size};
1137 my $chunk = $self->_read_source($want);
1138 if (!length($chunk)) {
1139 $self->close;
1140 croak "range body ended before requested offset";
1141 }
1142 $self->{offset} -= length($chunk);
1143 }
1144 return;
1145 }
1146  
1147 sub _read_source {
1148 my ($self, $length) = @_;
1149 if (length($self->{buffer})) {
1150 return substr($self->{buffer}, 0, $length, '');
1151 }
1152  
1153 if ($self->{body}->can('read')) {
1154 my $chunk = '';
1155 my $read = $self->{body}->read($chunk, $length);
1156 croak "range body stream read failed" unless defined $read;
1157 croak "range body stream returned an invalid length"
1158 unless $read == length($chunk) && length($chunk) <= $length;
1159 return $chunk;
1160 }
1161  
1162 my $chunk = $self->{body}->getline;
1163 return '' unless defined $chunk;
1164 croak "range body stream chunks must be scalars" if ref($chunk);
1165 return $chunk if length($chunk) <= $length;
1166 my $buffer_length = $self->{remaining} - $length;
1167 $self->{buffer} = substr($chunk, $length, $buffer_length)
1168 if $buffer_length;
1169 return substr($chunk, 0, $length);
1170 }
1171  
1172 sub DEMOLISH {
1173 my ($self) = @_;
1174 eval { $self->close } unless $self->{closed};
1175 return;
1176 }
1177 }
1178  
1179 {
1180 package Net::Blossom::Server::_MirrorSink;
1181  
1182 use strictures 2;
1183  
1184 use Carp qw(croak);
1185 use subs 'started';
1186 use Class::Tiny qw(server opts upload type content_length), {
1187 sha => sub { Digest::SHA->new(256) },
1188 size => 0,
1189 started => 0,
1190 committed => 0,
1191 };
1192  
1193 sub BUILDARGS {
1194 my ($class, %args) = @_;
1195 croak "server is required" unless defined $args{server};
1196 croak "opts must be a hash reference" unless ref($args{opts}) eq 'HASH';
1197  
1198 return \%args;
1199 }
1200  
1201 sub BUILD {
1202 my ($self) = @_;
1203 $self->sha;
1204 $self->size;
1205 $self->started;
1206 $self->committed;
1207 return;
1208 }
1209  
1210 sub started {
1211 my ($self) = @_;
1212 return $self->{started};
1213 }
1214  
1215 sub start {
1216 my $self = shift;
1217 my %metadata = @_;
1218 my %known = map { $_ => 1 } qw(type content_length);
1219 my @unknown = grep { !exists $known{$_} } keys %metadata;
1220 croak "unknown mirror metadata: " . join(', ', sort @unknown) if @unknown;
1221 croak "mirror sink already started" if $self->{started};
1222  
1223 my $type = defined $metadata{type} ? $metadata{type} : 'application/octet-stream';
1224 croak "mirror content type must be a scalar" if ref($type);
1225 croak "mirror content type is required" unless length $type;
1226  
1227 Net::Blossom::Server::_validate_content_length($metadata{content_length})
1228 if defined $metadata{content_length};
1229  
1230 my %context = (type => $type);
1231 $context{content_length} = $metadata{content_length} if defined $metadata{content_length};
1232 $context{pubkey} = $self->{opts}{pubkey} if defined $self->{opts}{pubkey};
1233 $context{allowed_sha256} = [@{$self->{opts}{allowed_sha256}}]
1234 if defined $self->{opts}{allowed_sha256};
1235  
1236 my $upload = $self->{server}->storage->begin_upload(%context);
1237 Net::Blossom::Server::Storage->assert_upload($upload);
1238  
1239 $self->{upload} = $upload;
1240 $self->{type} = $type;
1241 $self->{content_length} = $metadata{content_length};
1242 $self->{started} = 1;
1243 return 1;
1244 }
1245  
1246 sub write {
1247 my ($self, $chunk) = @_;
1248 croak "mirror sink must be started before write" unless $self->{started};
1249 croak "mirror body chunks must be scalars" if ref($chunk);
1250  
1251 my $new_size = $self->{size} + length($chunk);
1252 my $max = $self->{server}->max_upload_bytes;
1253 Net::Blossom::Server::_upload_too_large()
1254 if defined $max && $new_size > $max;
1255  
1256 Net::Blossom::Server::_write_upload_chunk($self->{upload}, $self->{sha}, $chunk);
1257 $self->{size} = $new_size;
1258 return length $chunk;
1259 }
1260  
1261 sub finish {
1262 my ($self) = @_;
1263 $self->start unless $self->{started};
1264  
1265 my %opts = %{$self->{opts}};
1266 $opts{content_length} = $self->{content_length} if defined $self->{content_length};
1267 Net::Blossom::Server::_content_length_mismatch(%opts)
1268 if defined $self->{content_length} && $self->{size} != $self->{content_length};
1269  
1270 my $sha256 = $self->{sha}->hexdigest;
1271 Net::Blossom::Server::_sha256_mismatch(%opts, default_reason => 'sha256 is not allowed')
1272 if defined $opts{allowed_sha256}
1273 && !grep { $_ eq $sha256 } @{$opts{allowed_sha256}};
1274  
1275 my $uploaded = defined $opts{uploaded} ? $opts{uploaded} : $self->{server}->clock->();
1276 my %commit_metadata = (
1277 sha256 => $sha256,
1278 size => $self->{size},
1279 type => $self->{type},
1280 uploaded => $uploaded,
1281 );
1282 $commit_metadata{pubkey} = $opts{pubkey} if defined $opts{pubkey};
1283  
1284 my $result = Net::Blossom::Server::_upload_result_from_commit(
1285 $self->{upload}->commit(%commit_metadata),
1286 );
1287 Net::Blossom::Server::_validate_committed_descriptor(
1288 $result->descriptor,
1289 $sha256,
1290 $self->{size},
1291 $self->{type},
1292 );
1293  
1294 $self->{committed} = 1;
1295 return $result;
1296 }
1297  
1298 sub abort {
1299 my ($self) = @_;
1300 return 1 unless $self->{started};
1301 return 1 if $self->{committed};
1302 return $self->{upload}->abort;
1303 }
1304 }
1305  
1306 1;
1307  
1308 =pod
1309  
1310 =head1 NAME
1311  
1312 Net::Blossom::Server - Server-side support for the Blossom protocol
1313  
1314 =head1 SYNOPSIS
1315  
1316 use Net::Blossom::Server;
1317  
1318 my $server = Net::Blossom::Server->new(
1319 storage => $storage,
1320 );
1321  
1322 =head1 DESCRIPTION
1323  
1324 C<Net::Blossom::Server> is the framework-neutral server core for the Blossom
1325 protocol. Gateway adapters such as PSGI or PAGI should translate native requests
1326 into C<Net::Blossom::Server::Request> objects and translate
1327 C<Net::Blossom::Server::Response> objects back to their gateway format. It uses
1328 shared protocol types from L<Net::Blossom>, which also provides the client.
1329 Storage implementations are published under the
1330 L<Net::Blossom::Server::Backend namespace|https://metacpan.org/search?q=module%3ANet%3A%3ABlossom%3A%3AServer%3A%3ABackend+level%3A5+NOT+distribution%3ANet-Blossom-Server>
1331 and implement L<Net::Blossom::Server::Storage>.
1332  
1333 Server support lives in a separate CPAN distribution so client users do not need
1334 server, storage, daemon, or web framework dependencies.
1335  
1336 =head1 CONSTRUCTOR
1337  
1338 =head2 new
1339  
1340 my $server = Net::Blossom::Server->new(%args);
1341  
1342 Required arguments:
1343  
1344 =over 4
1345  
1346 =item * C<storage>
1347  
1348 Storage object that satisfies L<Net::Blossom::Server::Storage>.
1349  
1350 =back
1351  
1352 Optional arguments:
1353  
1354 =over 4
1355  
1356 =item * C<chunk_size>
1357  
1358 Positive integer read size used when copying stream bodies. Defaults to C<65536>.
1359  
1360 =item * C<clock>
1361  
1362 Code reference returning the upload timestamp. Defaults to C<time>.
1363  
1364 =item * C<mirror_fetcher>
1365  
1366 Optional code reference or object with C<fetch_blob>. This is required for
1367 C<PUT /mirror>. Mirror fetchers stream origin bytes into a server-provided sink;
1368 no default network fetcher is provided.
1369  
1370 =item * C<max_upload_bytes>
1371  
1372 Optional positive integer bounding the size of an accepted upload. When set,
1373 C<PUT /upload>, C<PUT /media>, and mirrored origin bodies that exceed it are
1374 rejected with C<413> and the partial upload is aborted. Defaults to unset (no
1375 limit).
1376  
1377 =item * C<max_list_limit>
1378  
1379 Positive integer maximum C<GET /list/E<lt>pubkeyE<gt>> page size. List requests
1380 without a C<limit> query parameter use this value as the default. Requests with
1381 a larger C<limit> are rejected with C<400>. Defaults to C<100>.
1382  
1383 =back
1384  
1385 Unknown arguments or invalid values croak.
1386  
1387 =head1 ACCESSORS
1388  
1389 =head2 storage
1390  
1391 Returns the configured storage object.
1392  
1393 =head2 chunk_size
1394  
1395 Returns the stream copy chunk size.
1396  
1397 =head2 clock
1398  
1399 Returns the clock code reference.
1400  
1401 =head2 mirror_fetcher
1402  
1403 Returns the optional mirror fetcher.
1404  
1405 =head2 max_upload_bytes
1406  
1407 Returns the configured maximum upload size, or C<undef> when uploads are
1408 not size-limited.
1409  
1410 =head2 max_list_limit
1411  
1412 Returns the configured maximum list page size.
1413  
1414 =head1 METHODS
1415  
1416 =head2 receive_blob
1417  
1418 my $result = $server->receive_blob($body, %opts);
1419  
1420 Copies a scalar or stream body into storage while computing SHA-256 in the server
1421 core. Returns a C<Net::Blossom::Server::UploadResult>.
1422  
1423 Options:
1424  
1425 =over 4
1426  
1427 =item * C<type>
1428  
1429 Blob media type. Defaults to C<application/octet-stream>.
1430  
1431 =item * C<expected_sha256>
1432  
1433 Optional lowercase 64-character SHA-256 hash. When present, the computed hash
1434 must match before the upload is committed.
1435  
1436 =item * C<allowed_sha256>
1437  
1438 Optional array reference of lowercase 64-character SHA-256 hashes. When present,
1439 the computed hash must match one of these values before the upload is committed.
1440 This is used for deferred BUD-11 C<PUT /mirror> authorization.
1441  
1442 =item * C<content_length>
1443  
1444 Optional expected body size. When present, the copied byte count must match
1445 before the upload is committed.
1446  
1447 =item * C<uploaded>
1448  
1449 Optional upload timestamp. Defaults to C<< $server->clock->() >>.
1450  
1451 =item * C<pubkey>
1452  
1453 Optional uploader public key as lowercase 64-character hex. Gateway adapters
1454 will normally derive this from BUD-11 authorization.
1455  
1456 =item * C<sha256_mismatch_status>
1457  
1458 Optional HTTP status code for SHA-256 mismatches. When supplied, mismatches
1459 throw L<Net::Blossom::Server::Error> with this status instead of croaking with
1460 a plain string.
1461  
1462 =item * C<sha256_mismatch_reason>
1463  
1464 Optional reason string used with C<sha256_mismatch_status>.
1465  
1466 =item * C<content_length_mismatch_status>
1467  
1468 Optional HTTP status code for content-length mismatches. When supplied,
1469 mismatches throw L<Net::Blossom::Server::Error> with this status instead of
1470 croaking with a plain string.
1471  
1472 =item * C<content_length_mismatch_reason>
1473  
1474 Optional reason string used with C<content_length_mismatch_status>.
1475  
1476 =back
1477  
1478 The storage upload is aborted if hashing, length validation, SHA-256 validation,
1479 or storage writing fails.
1480  
1481 Storage commit results that are raw C<Net::Blossom::BlobDescriptor> objects or
1482 descriptor hash references are accepted as newly created uploads for compatibility
1483 with early storage implementations. New storage implementations should return a
1484 C<Net::Blossom::Server::UploadResult> or a hash reference with C<descriptor> and
1485 C<created>.
1486  
1487 =head2 handle_upload
1488  
1489 my $response = $server->handle_upload($request, %opts);
1490  
1491 Handles a normalized C<PUT /upload> request and returns a
1492 C<Net::Blossom::Server::Response>. The request must be a
1493 C<Net::Blossom::Server::Request> with a defined body.
1494  
1495 The method passes the request body, content type, content length, optional
1496 C<X-SHA-256>, and optional C<pubkey> into C<receive_blob>. When C<X-SHA-256> is
1497 present, a hash mismatch throws a typed C<409> error before storage commit.
1498 C<Content-Length> mismatches throw a typed C<400> error before storage commit.
1499 The response body is the blob descriptor encoded as JSON. The response status is
1500 C<201> when the blob was newly stored and C<200> when it already existed.
1501  
1502 Options:
1503  
1504 =over 4
1505  
1506 =item * C<pubkey>
1507  
1508 Optional already-verified uploader public key as lowercase 64-character hex.
1509 Authorization verification is deliberately outside this method.
1510  
1511 =back
1512  
1513 =head2 handle_head_upload
1514  
1515 my $response = $server->handle_head_upload($request);
1516  
1517 Handles a normalized C<HEAD /upload> BUD-06 preflight request. It validates the
1518 C<X-SHA-256>, C<X-Content-Type>, and C<X-Content-Length> headers and returns an
1519 empty C<200> response when the metadata is well-formed. Malformed metadata
1520 returns C<400>; missing C<X-Content-Length> returns C<411>.
1521  
1522 =head2 handle_get_blob
1523  
1524 my $response = $server->handle_get_blob($request);
1525  
1526 Handles a normalized C<GET /E<lt>sha256E<gt>> request and returns a
1527 C<Net::Blossom::Server::Response>. The request path must contain one lowercase
1528 64-character SHA-256 hash segment and may include a file extension.
1529  
1530 Without a valid C<Range> header, the method calls
1531 C<< $server->storage->get_blob($sha256) >> and returns C<200>. A valid single
1532 byte range returns C<206> with C<Content-Range>. An unsatisfiable range returns
1533 C<416>. Malformed ranges, unsupported units, and multiple ranges are ignored.
1534  
1535 When storage provides both C<head_blob> and C<get_blob_range>, range requests
1536 use them to avoid reading the complete blob. Older storage implementations fall
1537 back to C<get_blob> and return only the requested bytes from scalar, array, or
1538 stream bodies. A stream that implements C<read> is not read past the requested
1539 range. Successful blob responses include C<Accept-Ranges: bytes>.
1540  
1541 =head2 handle_head_blob
1542  
1543 my $response = $server->handle_head_blob($request);
1544  
1545 Handles a normalized C<HEAD /E<lt>sha256E<gt>> request and returns the same
1546 C<Content-Type> and C<Content-Length> headers as C<GET /E<lt>sha256E<gt>>
1547 without returning the blob body. It also returns C<Accept-Ranges: bytes>. The
1548 request path may include a file extension.
1549  
1550 If storage provides an optional C<head_blob($sha256)> method, that method is
1551 used and may return either a L<Net::Blossom::BlobDescriptor> or a
1552 L<Net::Blossom::Server::BlobResult>. Otherwise C<get_blob> is used and the body
1553 is discarded. A closeable discarded body is closed.
1554  
1555 =head2 handle_media
1556  
1557 my $response = $server->handle_media($request, %opts);
1558  
1559 Handles a normalized C<PUT /media> request. The current implementation uses the
1560 same identity byte path as C<PUT /upload>: it stores the received bytes without
1561 media transformation and returns a blob descriptor JSON response with C<201> or
1562 C<200>. When C<X-SHA-256> is present, a hash mismatch throws a typed C<409>
1563 error before storage commit. C<Content-Length> mismatches throw a typed C<400>
1564 error before storage commit.
1565  
1566 Options:
1567  
1568 =over 4
1569  
1570 =item * C<pubkey>
1571  
1572 Optional already-verified uploader public key as lowercase 64-character hex.
1573  
1574 =back
1575  
1576 =head2 handle_head_media
1577  
1578 my $response = $server->handle_head_media($request);
1579  
1580 Handles a normalized C<HEAD /media> BUD-05 preflight request. It validates the
1581 C<X-SHA-256>, C<X-Content-Type>, and C<X-Content-Length> headers and returns the
1582 same status behavior as C<handle_head_upload>.
1583  
1584 =head2 handle_mirror
1585  
1586 my $response = $server->handle_mirror($request, %opts);
1587  
1588 Handles a normalized C<PUT /mirror> request. The request body must be a JSON
1589 object with a C<url> field. The URL must use C<http> or C<https>, have a host,
1590 must not include userinfo, and must not include a fragment.
1591  
1592 The server calls the configured C<mirror_fetcher> with a streaming sink and stores
1593 origin bytes as the fetcher writes them. SHA-256 calculation and storage commit
1594 remain owned by the server core. A missing C<mirror_fetcher> returns C<503>.
1595 Malformed mirror requests return C<400>. Origin fetch failures, unusable fetch
1596 results, or origin content-length mismatches return C<502>.
1597  
1598 The fetcher may be a code reference called with C<$url> and C<< sink => $sink >>,
1599 or an object called as C<< $fetcher->fetch_blob($url, sink => $sink) >>. It must
1600 call C<< $sink->start(%metadata) >> before writing bytes, then call
1601 C<< $sink->write($chunk) >> for each scalar byte chunk. C<%metadata> may include
1602 C<type> and C<content_length>; missing C<type> defaults to
1603 C<application/octet-stream>. For empty origin bodies, the fetcher may instead
1604 return a metadata hash reference and let the server start the sink. Returning a
1605 C<body> value is not supported.
1606  
1607 Options:
1608  
1609 =over 4
1610  
1611 =item * C<pubkey>
1612  
1613 Optional already-verified uploader public key.
1614  
1615 =item * C<authorization>
1616  
1617 Optional L<Net::Blossom::Server::AuthorizationResult>. When provided, the
1618 downloaded blob hash must match one of the authorized C<x> tag hashes before
1619 storage commit, otherwise a typed C<409> error is thrown.
1620  
1621 =back
1622  
1623 =head2 handle_delete_blob
1624  
1625 my $response = $server->handle_delete_blob($request, pubkey => $pubkey);
1626  
1627 Handles a normalized C<DELETE /E<lt>sha256E<gt>> request and returns a
1628 C<Net::Blossom::Server::Response>. The request path must contain one lowercase
1629 64-character SHA-256 hash segment.
1630  
1631 C<pubkey> is required and must be the already-verified owner public key as
1632 lowercase 64-character hex. Authorization event verification is deliberately
1633 outside this method.
1634  
1635 The method calls C<< $server->storage->delete_blob($sha256, pubkey => $pubkey) >>.
1636 It returns C<204> when storage deletes an owner relationship and C<404> when
1637 storage returns false.
1638  
1639 =head2 handle_list_blobs
1640  
1641 my $response = $server->handle_list_blobs($request);
1642  
1643 Handles a normalized C<GET /list/E<lt>pubkeyE<gt>> request and returns a
1644 C<Net::Blossom::Server::Response>. The request path must contain one lowercase
1645 64-character public key segment.
1646  
1647 The method reads optional C<cursor> and C<limit> query parameters. C<cursor>
1648 must be a lowercase 64-character SHA-256 hash. C<limit> must be a positive
1649 integer no larger than C<max_list_limit>. Requests without C<limit> use
1650 C<max_list_limit> as the default page size. Storage receives a bounded C<limit>
1651 for every list request.
1652  
1653 The method calls C<< $server->storage->list_blobs($pubkey, %opts) >> and
1654 returns status C<200> with a JSON array of blob descriptors. Storage must return
1655 an array reference of C<Net::Blossom::BlobDescriptor> objects.
1656  
1657 =head2 handle_request
1658  
1659 my $response = $server->handle_request($request, %opts);
1660  
1661 Dispatches a normalized C<Net::Blossom::Server::Request> and returns a
1662 C<Net::Blossom::Server::Response>. This is the framework-neutral routing entry
1663 point for future gateway adapters.
1664  
1665 Currently implemented routes:
1666  
1667 =over 4
1668  
1669 =item * C<PUT /upload>
1670  
1671 Delegates to C<handle_upload>.
1672  
1673 =item * C<HEAD /upload>
1674  
1675 Delegates to C<handle_head_upload>.
1676  
1677 =item * C<PUT /media>
1678  
1679 Delegates to C<handle_media>.
1680  
1681 =item * C<HEAD /media>
1682  
1683 Delegates to C<handle_head_media>.
1684  
1685 =item * C<PUT /mirror>
1686  
1687 Delegates to C<handle_mirror>.
1688  
1689 =item * C<GET /E<lt>sha256E<gt>>
1690  
1691 Delegates to C<handle_get_blob>.
1692  
1693 =item * C<HEAD /E<lt>sha256E<gt>>
1694  
1695 Delegates to C<handle_head_blob>.
1696  
1697 =item * C<DELETE /E<lt>sha256E<gt>>
1698  
1699 Delegates to C<handle_delete_blob>.
1700  
1701 =item * C<GET /list/E<lt>pubkeyE<gt>>
1702  
1703 Delegates to C<handle_list_blobs>.
1704  
1705 =back
1706  
1707 Unknown paths return C<404>. Known paths with unsupported methods return C<405>.
1708  
1709 Options:
1710  
1711 =over 4
1712  
1713 =item * C<pubkey>
1714  
1715 Optional already-verified uploader public key. Passed through to upload, media,
1716 mirror, and delete handlers as needed.
1717  
1718 =item * C<authorization>
1719  
1720 Optional L<Net::Blossom::Server::AuthorizationResult>. Passed through to
1721 C<handle_mirror> for deferred hash authorization.
1722  
1723 =back
1724  
1725 =head1 STATUS
1726  
1727 The server core is under active development. It implements the protocol handlers
1728 documented above and remains framework-neutral.
1729  
1730 =head1 INTERNAL METHODS
1731  
1732 =head2 BUILDARGS
1733  
1734 Normalizes constructor arguments for Class::Tiny.
1735  
1736 =head2 BUILD
1737  
1738 Validates the constructed object for Class::Tiny.
1739  
1740 =cut
« Server/Authorization.pm ↑ Summary Server/PSGI.pm »