lib/ForgeOps/Tracker/StrictPrivacy.pm

filter: Statementstmt 26.4% 36 / 136 Branchbran 3.5% 2 / 56 Conditioncond 0.0% 0 / 38 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 36.8% 7 / 19 Podpod 0.0% 0 / 9 totaltotal 16.1% 45 / 279 CC 45 SCAR 38.1
CC
45
Cov
17%
_allowed
110.0
strict_path
72.0
_user
56.0
CRAP 45.1
« blib/lib/ForgeOps/Tracker/Integrations/Dancer2Performance.pm ↑ Summary lib/ForgeOps/Tracker/Configuration.pm »
1 package ForgeOps::Tracker::StrictPrivacy;
2  
3 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use Digest::SHA qw(sha256_hex hmac_sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # What the configuration's strict_privacy changes in everything this client sends, for apps that
10 # can't let personal or health data leave their own servers. With it on, only structured facts go
11 # out (the error's class, its stack frames, release, environment, server, which request it
12 # happened in, timings and counts); free text, which is where a name, an email or a diagnosis
13 # hides, never leaves this process: no error message, no breadcrumbs, no endpoint, no SQL
14 # statement, no source context, no user email or username, the user's id only as a keyed hash
15 # (privacy_user_key), and only the context/tag keys listed in privacy_allowed_fields.
16 #
17 # The same rules as the server's own StrictPrivacy (app/services/strict_privacy.rb), which applies
18 # them again on arrival when the project's Strict privacy setting is on;
19 # sdks/strict_privacy_vectors.json pins the results both have to agree on, byte for byte.
20 15 our @EXPORT_OK = qw(normalize_message message_fingerprint hashed_user_id event span span_name transaction_name strict_path);
21  
22 15 ▶use constant FINGERPRINT_LENGTH => 32;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 # ASCII "word" characters; boundaries are defined against these, the same in every SDK. Spelled
25 # out as classes rather than \w, so Perl's own idea of a word (Unicode letters, digits in other
26 # scripts) never changes the result on a string Perl holds as characters.
27 15 my $WORD = 'A-Za-z0-9_';
28 15 my $EMAIL = qr/[a-zA-Z0-9._%+-]+\@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
29 # A quoted value (KeyError: 'Jane Doe') is data, not the shape of the error. A single quote only
30 # opens or closes one where no ASCII word character touches it, so "Couldn't" never does.
31 15 my $DOUBLE_QUOTED = qr/"[^"\r\n]*"/;
32 15 my $SINGLE_QUOTED = qr/(?<![$WORD])'[^'\r\n]*'(?![$WORD])/;
33 15 my $HEX_OBJECT_ID = qr/0x[0-9a-fA-F]{4,}/;
34 15 my $UUID = qr/(?<![$WORD])[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?![$WORD])/;
35 15 my $NUMBER = qr/(?<![$WORD])[0-9]+(?![$WORD])/;
36  
37 # Span data that's structure, not content: the masked statement and which database it ran on.
38 15 my @SPAN_DATA_KEYS = ('db.statement', 'db.system');
39 15 my $HTTP_METHOD = qr/\A(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)/i;
40 15 my $SCHEME = qr{\A[a-z][a-z0-9+.-]*://}i;
41 15 my $ROUTE_PARAMETER = qr/\A(?::.+|\{.+\}|<.+>|\[.+\]|\*.*)\z/;
42  
43 # Error event fields that are never sent, and the per-frame source context.
44 15 my @EVENT_FIELDS_DROPPED = qw(message breadcrumbs endpoint sql_statement);
45 15 my @SOURCE_CONTEXT_FIELDS = qw(context_line pre_context post_context);
46  
47 # normalize_message($message): the message with emails, quoted values, hex object ids, UUIDs and
48 # standalone numbers replaced, in that order.
49 0 ▶sub normalize_message {
Subroutine normalize_message: not called CC=2 SCAR=17.9
Pod undocumented
50 0 my ($message) = @_;
51 0 ▶ my $text = defined $message ? "$message" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $message ? : 0 0 0
52 0 $text =~ s/$EMAIL/<email>/g;
53 0 $text =~ s/$DOUBLE_QUOTED/<str>/g;
54 0 $text =~ s/$SINGLE_QUOTED/<str>/g;
55 0 $text =~ s/$HEX_OBJECT_ID/0x/g;
56 0 $text =~ s/$UUID/<uuid>/g;
57 0 $text =~ s/$NUMBER/<n>/g;
58 0 return $text;
59 }
60  
61 # message_fingerprint($message): lets ForgeOps group errors without ever seeing their message: the
62 # first 32 hex characters of the SHA-256 of the normalized message's UTF-8 bytes, so two messages
63 # that differ only in ids hash the same, and nothing about the text can be read back from it. The
64 # message is encoded the same way encode_json encodes it on its way to the server.
65 0 ▶sub message_fingerprint {
Subroutine message_fingerprint: not called CC=1 SCAR=6.9
Pod undocumented
66 0 my ($message) = @_;
67 0 my $bytes = normalize_message($message);
68 0 utf8::encode($bytes);
69 0 return substr(sha256_hex($bytes), 0, FINGERPRINT_LENGTH);
70 }
71  
72 # hashed_user_id($id, $key): "h1:" and the first 32 lowercase hex characters of HMAC-SHA256 of the
73 # id's UTF-8 text, keyed with the app's own secret, which ForgeOps never sees. The same id hashes
74 # the same under one key, so affected customers can still be counted. The id is encoded the way
75 # encode_json would send it; the key, which is never sent, is taken as the UTF-8 bytes it already
76 # is when Perl holds it as bytes (as it does when read from %ENV), and encoded when it holds
77 # characters.
78 0 ▶sub hashed_user_id {
Subroutine hashed_user_id: not called CC=2 SCAR=17.9
Pod undocumented
79 0 my ($id, $key) = @_;
80 0 my $id_bytes = "$id";
81 0 utf8::encode($id_bytes);
82 0 my $key_bytes = "$key";
83 0 ▶ utf8::encode($key_bytes) if utf8::is_utf8($key_bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($key_bytes) 0 0 0
84 0 return 'h1:' . substr(hmac_sha256_hex($id_bytes, $key_bytes), 0, FINGERPRINT_LENGTH);
85 }
86  
87 # event(\%payload, \@allowed_fields, $user_key): an error event payload (EventBuilder::build's
88 # shape) reduced to what strict privacy sends. message is sent as "" alongside
89 # message_fingerprint, exactly what the server stores for a strict project.
90 0 ▶sub event {
Subroutine event: not called CC=3 SCAR=24.8
Pod undocumented
91 0 my ($payload, $allowed_fields, $user_key) = @_;
92 0 my %reduced = %$payload;
93 0 delete @reduced{@EVENT_FIELDS_DROPPED};
94 0 $reduced{message} = '';
95 0 $reduced{message_fingerprint} = message_fingerprint($payload->{message});
96 0 $reduced{transaction_name} = transaction_name($payload->{transaction_name});
97 0 $reduced{context} = _allowed($payload->{context}, $allowed_fields);
98 0 $reduced{tags} = _allowed($payload->{tags}, $allowed_fields);
99 0 $reduced{user} = _user($payload->{user}, $user_key);
100 $reduced{backtrace} = [
101 map {
102 0 my %frame = %$_;
103 0 delete @frame{@SOURCE_CONTEXT_FIELDS};
104 0 \%frame;
105 0 ▶ } @{ $payload->{backtrace} || [] }
Condition0%0/2
$payload->{'backtrace'} || []
l!l
00
MC/DC0%0/1
$payload->{'backtrace'} || []
$payload->{'backtrace'}
Truth table0%0/2
A
A= $payload->{'backtrace'}
Aresult
11
00
106 ];
107 0 delete $reduced{$_} for grep { !defined $reduced{$_} } keys %reduced;
108 0 return \%reduced;
109 }
110  
111 # span(\%span): a trace's span: an outbound call's name keeps its method and host, never its path
112 # or query, and its data keeps only the masked statement and database system. data is left out
113 # entirely when nothing is left of it, the same as the server does.
114 0 ▶sub span {
Subroutine span: not called CC=5 SCAR=34.0
Pod undocumented
115 0 my ($span) = @_;
116 0 my %reduced = %$span;
117 0 $reduced{name} = span_name($span->{name});
118 0 ▶ my $data = ref $span->{data} eq 'HASH' ? $span->{data} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $span->{'data'} eq 'HASH' ? : 0 0 0
119 0 ▶ my %kept = map { exists $data->{$_} ? ($_ => $data->{$_}) : () } @SPAN_DATA_KEYS;
Branch: 1 branch
BranchTrueFalseTotal
exists $data->{$_} ? : 0 0 0
120 0 ▶ if (%kept) {
Branch: 1 branch
BranchTrueFalseTotal
if (%kept) { } 0 0 0
121 0 $reduced{data} = \%kept;
122 }
123 else {
124 0 delete $reduced{data};
125 }
126 0 delete $reduced{$_} for grep { !defined $reduced{$_} } keys %reduced;
127 0 return \%reduced;
128 }
129  
130 # span_name($name): "GET https://api.example.com/patients/42?x=1" or
131 # "GET api.example.com/patients/42" becomes "GET api.example.com". A bare path ("/patients/42"),
132 # or a method and a path ("GET /patients/42", what the PSGI integration names every request), has
133 # its ids taken out, like a page path. A name that's none of these ("OrdersController#create",
134 # "patients#show") is kept.
135 0 ▶sub span_name {
Subroutine span_name: not called CC=6 SCAR=37.4
Pod undocumented
136 0 my ($name) = @_;
137 0 ▶ return $name unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 0 0
138 0 ▶ return strict_path($name) if index($name, '/') == 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($name, "/") == 0 0 0 0
139 0 ▶ return $name unless $name =~ $HTTP_METHOD;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$HTTP_METHOD/ 0 0 0
140  
141 0 my ($method, $target) = (uc $1, $2);
142 0 ▶ return "$method " . strict_path($target) if index($target, '/') == 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($target, "/") == 0 0 0 0
143 0 my $host = _host($target);
144 0 ▶ return "$method " . (defined $host ? $host : strict_path($target));
Branch: 1 branch
BranchTrueFalseTotal
defined $host ? : 0 0 0
145 }
146  
147 # transaction_name($name): which request something happened in: a route or a handler name is kept,
148 # but a raw path (PSGI's "GET /patients/42") keeps only its first segment, by the span name rule.
149 0 ▶sub transaction_name {
Subroutine transaction_name: not called CC=3 SCAR=24.8
Pod undocumented
150 0 my ($name) = @_;
151 0 ▶ return defined $name && length $name ? span_name($name) : $name;
Branch: 1 branch
BranchTrueFalseTotal
defined $name && length $name ? : 0 0 0
Condition0%0/3
defined $name and length $name
!ll&&!rl&&r
000
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table0%0/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
152 }
153  
154 # strict_path($path): A request or page path under strict privacy, with no query or fragment. A
155 # route template ("/patients/:id/notes", "/patients/{id}", "users/<int:id>/", "/files/*path",
156 # "/posts/[slug]") is kept as it is: its words are a developer's, and its parameters are already
157 # placeholders. A raw path keeps only its first segment, and the rest becomes ":path":
158 # "/patients/jane-doe/12" is "/patients/:path". Anything after the first segment of a raw path could
159 # name a person, and no rule can tell a name from a word ("/patients/janedoe"). A first segment that
160 # holds a digit or is over 40 characters is ":id" itself.
161 0 ▶sub strict_path {
Subroutine strict_path: not called CC=8 SCAR=42.8
Pod undocumented
162 0 my ($path) = @_;
163 0 ▶ $path = defined $path ? "$path" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $path ? : 0 0 0
164 0 $path =~ s/[?#].*\z//s;
165 0 ▶ return $path if _is_route_template($path);
Branch: 1 branch
BranchTrueFalseTotal
if _is_route_template($path) 0 0 0
166  
167 0 ▶ my $leading = index($path, '/') == 0 ? '/' : '';
Branch: 1 branch
BranchTrueFalseTotal
index($path, '/') == 0 ? : 0 0 0
168 0 my @segments = grep { length } split m{/}, $path;
169 0 ▶ return '/' unless @segments;
Branch: 1 branch
BranchTrueFalseTotal
unless @segments 0 0 0
170  
171 0 ▶ my $first = $segments[0] =~ /[0-9]/ || length($segments[0]) > 40 ? ':id' : $segments[0];
Branch: 1 branch
BranchTrueFalseTotal
$segments[0] =~ /[0-9]/ || length $segments[0] > 40 ? : 0 0 0
Condition0%0/3
$segments[0] =~ /[0-9]/ or length $segments[0] > 40
l!l&&r!l&&!r
000
MC/DC0%0/2
$segments[0] =~ /[0-9]/ or length $segments[0] > 40
$segments[0] =~ /[0-9]/ length $segments[0] > 40
Truth table0%0/3
A or B
A= $segments[0] =~ /[0-9]/B= length $segments[0] > 40
ABresult
1X1
011
000
172 0 ▶ return $leading . $first . (@segments > 1 ? '/:path' : '');
Branch: 1 branch
BranchTrueFalseTotal
@segments > 1 ? : 0 0 0
173 }
174  
175 # Whether any segment is a route parameter: ":id", "{id}", "<int:id>", "[slug]" or "*path".
176 0 ▶sub _is_route_template {
Subroutine _is_route_template: not called CC=1 SCAR=6.9
177 0 my ($path) = @_;
178 0 return scalar grep { $_ =~ $ROUTE_PARAMETER } split m{/}, $path;
179 }
180  
181 # An outbound call's host, read by hand rather than with a URL parser (an address a parser rejects
182 # must never be sent whole): what comes before the first "/", "?" or "#", without a scheme,
183 # credentials (up to the last "@", since a password can hold one) or port. Only a host when the
184 # address had a scheme or a port, or the name has a dot or is "localhost"; undef otherwise (a
185 # relative path).
186 0 ▶sub _host {
Subroutine _host: not called CC=6 SCAR=37.4
187 0 my ($target) = @_;
188 0 (my $authority = $target) =~ s/$SCHEME//;
189 0 my $scheme = $authority ne $target;
190 0 $authority =~ s{[/?#].*\z}{}s;
191 0 $authority =~ s/\A.*\@//s;
192 0 my $port = $authority =~ s/:[0-9]+\z//;
193 0 ▶ return undef unless length $authority;
Branch: 1 branch
BranchTrueFalseTotal
unless length $authority 0 0 0
194 0 ▶ return $authority if $scheme || $port || index($authority, '.') >= 0 || lc($authority) eq 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
if $scheme or $port or index($authority, ".") != -1 or lc $authority eq "localhost" 0 0 0
Condition0%0/9
$scheme or $port or index($authority, ".") != -1 or lc $authority eq "localhost"
l!l&&r!l&&!r
000
$scheme or $port or index($authority, ".") != -1
l!l&&r!l&&!r
000
$scheme or $port
l!l&&r!l&&!r
000
MC/DC0%0/4
$scheme or $port or index($authority, ".") != -1 or lc $authority eq "localhost"
$scheme $port index($authority, ".") != -1 lc $authority eq "localhost"
Truth table0%0/5
A or B or C or D
A= $schemeB= $portC= index($authority, ".") != -1D= lc $authority eq "localhost"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
195 0 return undef;
196 }
197  
198 # Only top-level keys named in allowed_fields, and only plain values under them (a string, a
199 # number, or a JSON boolean); undef (left out of the payload) when nothing is left.
200 0 ▶sub _allowed {
Subroutine _allowed: not called CC=10 SCAR=47.0
201 0 my ($fields, $allowed_fields) = @_;
202 0 my %allowed = map { ($_ => 1) } allowed_field_list($allowed_fields);
203 0 ▶ return undef unless %allowed && ref $fields eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless %allowed and ref $fields eq "HASH" 0 0 0
Condition0%0/3
%allowed and ref $fields eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
%allowed and ref $fields eq "HASH"
%allowed ref $fields eq "HASH"
Truth table0%0/3
A and B
A= %allowedB= ref $fields eq "HASH"
ABresult
0X0
100
111
204  
205 0 my %kept;
206 0 for my $key (keys %$fields) {
207 0 my $value = $fields->{$key};
208 0 ▶ next unless $allowed{$key} && defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless $allowed{$key} and defined $value 0 0 0
Condition0%0/3
$allowed{$key} and defined $value
!ll&&!rl&&r
000
MC/DC0%0/2
$allowed{$key} and defined $value
$allowed{$key} defined $value
Truth table0%0/3
A and B
A= $allowed{$key}B= defined $value
ABresult
0X0
100
111
209 0 ▶ next if ref $value && !(blessed($value) && $value->isa('JSON::PP::Boolean'));
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and not builtin::blessed($value) && $value->isa("JSON::PP::Boolean") 0 0 0
Condition0%0/6
ref $value and not builtin::blessed($value) && $value->isa("JSON::PP::Boolean")
!ll&&!rl&&r
000
builtin::blessed($value) && $value->isa('JSON::PP::Boolean')
!ll&&!rl&&r
000
MC/DC0%0/3
ref $value and not builtin::blessed($value) && $value->isa("JSON::PP::Boolean")
ref $value builtin::blessed($value) $value->isa('JSON::PP::Boolean')
Truth table0%0/4
A and not(B && C)
A= ref $valueB= builtin::blessed($value)C= $value->isa('JSON::PP::Boolean')
ABCresult
0XX0
1110
10X1
1101
210 0 $kept{$key} = $value;
211 }
212 0 ▶ return %kept ? \%kept : undef;
Branch: 1 branch
BranchTrueFalseTotal
%kept ? : 0 0 0
213 }
214  
215 # allowed_field_list($fields): privacy_allowed_fields as a list of names, whether it was set as an
216 # arrayref or as one comma-separated string (FORGE_OPS_PRIVACY_ALLOWED_FIELDS's own form).
217 65 ▶sub allowed_field_list {
Subroutine allowed_field_list: called CC=3 SCAR=14.2
Pod undocumented
218 65 my ($fields) = @_;
219 65 ▶ my @fields = ref $fields eq 'ARRAY' ? @$fields : split /,/, (defined $fields ? $fields : '');
Branch: 2 branches
BranchTrueFalseTotal
ref $fields eq 'ARRAY' ? : 0 65 65
defined $fields ? : 0 65 65
220 0 return grep { length } map { (my $field = "$_") =~ s/\A\s+|\s+\z//g; $field } @fields;
221 }
222  
223 # Only a keyed hash of the user's id (hashed_user_id), and only when the app set
224 # privacy_user_key; undef otherwise. A raw id can be a record number that identifies a person, and
225 # an unkeyed hash of a small number can be guessed back.
226 0 ▶sub _user {
Subroutine _user: not called CC=7 SCAR=40.3
227 0 my ($user, $key) = @_;
228 0 ▶ return undef unless ref $user eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $user eq "HASH" 0 0 0
229 0 ▶ return undef unless defined $key && length $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and length $key 0 0 0
Condition0%0/3
defined $key and length $key
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table0%0/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
230 0 my $id = $user->{id};
231 0 ▶ return undef unless defined $id && !ref $id && "$id" =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and not ref $id and "$id" =~ /\S/ 0 0 0
Condition0%0/6
defined $id and not ref $id and "$id" =~ /\S/
!ll&&!rl&&r
000
defined $id and not ref $id
!ll&&!rl&&r
000
MC/DC0%0/3
defined $id and not ref $id and "$id" =~ /\S/
defined $id not ref $id "$id" =~ /\S/
Truth table0%0/4
A and not(B) and C
A= defined $idB= not ref $idC= "$id" =~ /\S/
ABCresult
0XX0
10X0
1100
1111
232 0 return { id => hashed_user_id($id, $key) };
233 }
234  
235 15 1;
« blib/lib/ForgeOps/Tracker/Integrations/Dancer2Performance.pm ↑ Summary lib/ForgeOps/Tracker/Configuration.pm »