aboutsummaryrefslogtreecommitdiff
path: root/lib/Net/Hawk/Client.pm
blob: f307681b4c7280e3b6453404fc46d8aadf77afd3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package Net::Hawk::Client {
    use v6;
    use URI;
    use URI::Escape;
    use MIME::Base64;
    use Net::Hawk::Utils;
    use Net::Hawk::Crypto;
 
    our proto header(*@,*%) returns Hash {*};
    multi header(Str:D $uri!,*@pos,*%nam) returns Hash {
        return header(URI.new($uri),|@pos,|%nam);
    };
    multi header(
      URI:D $uri!,
      Str:D $method!,
        Int :$timestamp,
        Int :$localtime_offset_msec,
        Hash:D :$credentials (
            Str:D :id($),
            Str:D :key($),
            Str:D :algorithm($),
        ),
        Str :$nonce,
        Str :$hash,
        Str :$ext,
        Str :$app,
        Str :$dlg,
        Str :$payload,
        Str :$content_type,
        *%,
    ) returns Hash {
        $timestamp //= now_secs($localtime_offset_msec);
 
        my %artifacts = (
            ts => +($timestamp),
            nonce => $nonce // ['a'..'z','A'..'Z','_',0..9].pick(6).join(''),
            method => $method,
            resource => $uri.path_query,
            host => $uri.host,
            port => +($uri.port) // ($uri.scheme eq 'http' ?? 80 !! 443),
        );
        for <hash ext app dlg> -> $k {
            next unless defined $::($k);
            %artifacts{$k} = $::($k);
        }
 
        if ( !%artifacts<hash> && defined $payload ) {
            %artifacts<hash> = calculate_payload_hash(
                $payload,
                $credentials<algorithm>,
                $content_type,
            );
        }
 
        my $mac = calculate_mac(
            'header',
            $credentials,
            %artifacts,
        );
 
        my $has_ext = ($ext//''ne '';
 
        my $header = sprintf(
            'Hawk id="%s", ts="%d", nonce="%s"',
            $credentials<id>,
            %artifacts<ts>,
            %artifacts<nonce>,
        )
            ~ (%artifacts<hash> ?? sprintf(', hash="%s"',%artifacts<hash>) !! '')
            ~ ($has_ext ?? sprintf(', ext="%s"'%artifacts<ext>.trans(['\\','"']=>['\\\\','\\"']) ) !! '' )
            sprintf(', mac="%s"',$mac);
 
        if (%artifacts<app>) {
            $header ~= sprintf(', app="%s"'%artifacts<app>);
            if (%artifacts<dlg>) {
                $header ~= sprintf(', dlg="%s"',%artifacts<dlg>);
            }
        }
 
        return {
            field => $header,
            artifacts => %artifacts,
        };
    };
 
    my sub get_header(Str:D $key@headers) returns Str {
        @headers \
            ==> grep { .key eq $key } \
            ==> map { .value } \
            ==> join ',';
    };
    our sub authenticate(
          Array:D $headers,
          Hash:D $credentials,
          Hash $artifacts?,
          Hash $options?,
    ) returns Bool {
 
        my $www_auth = get_header('www-authenticate',$headers);
 
        if ($www_auth) {
            my $attributes = try {
                parse_authorization_header(
                    $www_auth,<ts tsm error>,
                );
            };
            return False unless $attributes;
 
            if ($attributes<ts>) {
                my $tsm = calculate_ts_mac(
                    +$attributes<ts>,$credentials,
                );
                return False unless $tsm eq $attributes<tsm>;
            }
        }
 
        my $serv_auth = get_header('server-authorization',$headers);
        return True unless $serv_auth || $options<required>;
 
        my $attributes = try {
            parse_authorization_header(
                $serv_auth,
                <mac ext hash>,
            );
        };
        return False unless $attributes;
 
        my $mac = calculate_mac(
            'response',
            $credentials,
            %(
                %$artifacts,
                $attributes<ext hash> :p,
            ),
        );
        return False unless $mac eq $attributes<mac>;
 
        return True unless defined $options<payload>;
        return False unless $attributes<hash>;
 
        my $calculated_hash = calculate_payload_hash(
            $options<payload>,
            $credentials<algorithm>,
            get_header('content-type',$headers),
        );
        return $calculated_hash eq $attributes<hash>;
    };
 
    our proto getBewit(*@,*%) {*};
    multi getBewit(Str:D $uri!,*@pos,*%nam) {
        return getBewit(URI.new($uri),|@pos,|%nam);
    };
    multi getBewit(
        URI $uri!,
        %options,
    ) returns Str {
        return ''
            unless $uri && %options
            && %options<ttl_sec>.defined
            && %options<credentials>
            && %options<credentials>{all <id key algorithm>}.defined
            && is_valid_hash_algorithm(%options<credentials><algorithm>)
            ;
 
        %options<ext> //'';
        my $now = now_msecs(%options<localtime_offset_msec>//0);
        my $exp = floor($now/1000)+%options<ttl_sec>;
        my $mac = calculate_mac(
            'bewit',
            %options<credentials>,
            {
                ts => $exp,
                nonce => '',
                method => 'GET',
                resource => $uri.path_query,
                host => $uri.host,
                port => +($uri.port) // ($uri.scheme eq 'http' ?? 80 !! 443),
                %options<ext> :p,
            }
        );
 
        my $bewit = "%options<credentials><id>\\$exp\\$mac\\%options<ext>";
        return uri_escape(MIME::Base64.new.encode-str($bewit));
    };
}