diff options
author | Rebecca Turner <me@re-becca.org> | 2015-05-22 11:33:46 +0300 |
---|---|---|
committer | Rebecca Turner <me@re-becca.org> | 2015-06-26 03:27:03 +0300 |
commit | d3c858ce4cfb3aee515bb299eb034fe1b5e44344 (patch) | |
tree | e7714c839934a729b68038f4c7dc5ec3ed877638 /node_modules/hawk | |
parent | 24564b9654528d23c726cf9ea82b1aef2044b692 (diff) |
deps: deduplicate npm@3 style
Diffstat (limited to 'node_modules/hawk')
27 files changed, 7175 insertions, 0 deletions
diff --git a/node_modules/hawk/.npmignore b/node_modules/hawk/.npmignore new file mode 100644 index 000000000..70febc05e --- /dev/null +++ b/node_modules/hawk/.npmignore @@ -0,0 +1,20 @@ +.idea +*.iml +npm-debug.log +dump.rdb +node_modules +components +build +results.tap +results.xml +npm-shrinkwrap.json +config.json +.DS_Store +*/.DS_Store +*/*/.DS_Store +._* +*/._* +*/*/._* +coverage.* +lib-cov + diff --git a/node_modules/hawk/.travis.yml b/node_modules/hawk/.travis.yml new file mode 100755 index 000000000..047f7e3d5 --- /dev/null +++ b/node_modules/hawk/.travis.yml @@ -0,0 +1,5 @@ +language: node_js + +node_js: + - 0.10 + diff --git a/node_modules/hawk/LICENSE b/node_modules/hawk/LICENSE new file mode 100755 index 000000000..788093684 --- /dev/null +++ b/node_modules/hawk/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2012-2014, Eran Hammer and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hueniverse/hawk/graphs/contributors diff --git a/node_modules/hawk/Makefile b/node_modules/hawk/Makefile new file mode 100755 index 000000000..b102d5ab8 --- /dev/null +++ b/node_modules/hawk/Makefile @@ -0,0 +1,8 @@ +test: + @node node_modules/lab/bin/lab -a code +test-cov: + @node node_modules/lab/bin/lab -a code -t 100 +test-cov-html: + @node node_modules/lab/bin/lab -a code -r html -o coverage.html + +.PHONY: test test-cov test-cov-html diff --git a/node_modules/hawk/README.md b/node_modules/hawk/README.md new file mode 100755 index 000000000..0bcd28790 --- /dev/null +++ b/node_modules/hawk/README.md @@ -0,0 +1,635 @@ +![hawk Logo](https://raw.github.com/hueniverse/hawk/master/images/hawk.png) + +<img align="right" src="https://raw.github.com/hueniverse/hawk/master/images/logo.png" /> **Hawk** is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial +HTTP request cryptographic verification. For more complex use cases such as access delegation, see [Oz](https://github.com/hueniverse/oz). + +Current version: **2.3** + +Note: 2.x is the same exact protocol as 1.1. The version increment reflects a change in the internal error format +used by the module and used by the node API. + +[![Build Status](https://secure.travis-ci.org/hueniverse/hawk.png)](http://travis-ci.org/hueniverse/hawk) + +# Table of Content + +- [**Introduction**](#introduction) + - [Replay Protection](#replay-protection) + - [Usage Example](#usage-example) + - [Protocol Example](#protocol-example) + - [Payload Validation](#payload-validation) + - [Response Payload Validation](#response-payload-validation) + - [Browser Support and Considerations](#browser-support-and-considerations) +<p></p> +- [**Single URI Authorization**](#single-uri-authorization) + - [Usage Example](#bewit-usage-example) +<p></p> +- [**Security Considerations**](#security-considerations) + - [MAC Keys Transmission](#mac-keys-transmission) + - [Confidentiality of Requests](#confidentiality-of-requests) + - [Spoofing by Counterfeit Servers](#spoofing-by-counterfeit-servers) + - [Plaintext Storage of Credentials](#plaintext-storage-of-credentials) + - [Entropy of Keys](#entropy-of-keys) + - [Coverage Limitations](#coverage-limitations) + - [Future Time Manipulation](#future-time-manipulation) + - [Client Clock Poisoning](#client-clock-poisoning) + - [Bewit Limitations](#bewit-limitations) + - [Host Header Forgery](#host-header-forgery) +<p></p> +- [**Frequently Asked Questions**](#frequently-asked-questions) +<p></p> +- [**Implementations**](#implementations) +- [**Acknowledgements**](#acknowledgements) + +# Introduction + +**Hawk** is an HTTP authentication scheme providing mechanisms for making authenticated HTTP requests with +partial cryptographic verification of the request and response, covering the HTTP method, request URI, host, +and optionally the request payload. + +Similar to the HTTP [Digest access authentication schemes](http://www.ietf.org/rfc/rfc2617.txt), **Hawk** uses a set of +client credentials which include an identifier (e.g. username) and key (e.g. password). Likewise, just as with the Digest scheme, +the key is never included in authenticated requests. Instead, it is used to calculate a request MAC value which is +included in its place. + +However, **Hawk** has several differences from Digest. In particular, while both use a nonce to limit the possibility of +replay attacks, in **Hawk** the client generates the nonce and uses it in combination with a timestamp, leading to less +"chattiness" (interaction with the server). + +Also unlike Digest, this scheme is not intended to protect the key itself (the password in Digest) because +the client and server must both have access to the key material in the clear. + +The primary design goals of this scheme are to: +* simplify and improve HTTP authentication for services that are unwilling or unable to deploy TLS for all resources, +* secure credentials against leakage (e.g., when the client uses some form of dynamic configuration to determine where + to send an authenticated request), and +* avoid the exposure of credentials sent to a malicious server over an unauthenticated secure channel due to client + failure to validate the server's identity as part of its TLS handshake. + +In addition, **Hawk** supports a method for granting third-parties temporary access to individual resources using +a query parameter called _bewit_ (in falconry, a leather strap used to attach a tracking device to the leg of a hawk). + +The **Hawk** scheme requires the establishment of a shared symmetric key between the client and the server, +which is beyond the scope of this module. Typically, the shared credentials are established via an initial +TLS-protected phase or derived from some other shared confidential information available to both the client +and the server. + + +## Replay Protection + +Without replay protection, an attacker can use a compromised (but otherwise valid and authenticated) request more +than once, gaining access to a protected resource. To mitigate this, clients include both a nonce and a timestamp when +making requests. This gives the server enough information to prevent replay attacks. + +The nonce is generated by the client, and is a string unique across all requests with the same timestamp and +key identifier combination. + +The timestamp enables the server to restrict the validity period of the credentials where requests occuring afterwards +are rejected. It also removes the need for the server to retain an unbounded number of nonce values for future checks. +By default, **Hawk** uses a time window of 1 minute to allow for time skew between the client and server (which in +practice translates to a maximum of 2 minutes as the skew can be positive or negative). + +Using a timestamp requires the client's clock to be in sync with the server's clock. **Hawk** requires both the client +clock and the server clock to use NTP to ensure synchronization. However, given the limitations of some client types +(e.g. browsers) to deploy NTP, the server provides the client with its current time (in seconds precision) in response +to a bad timestamp. + +There is no expectation that the client will adjust its system clock to match the server (in fact, this would be a +potential attack vector). Instead, the client only uses the server's time to calculate an offset used only +for communications with that particular server. The protocol rewards clients with synchronized clocks by reducing +the number of round trips required to authenticate the first request. + + +## Usage Example + +Server code: + +```javascript +var Http = require('http'); +var Hawk = require('hawk'); + + +// Credentials lookup function + +var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'Steve' + }; + + return callback(null, credentials); +}; + +// Create HTTP server + +var handler = function (req, res) { + + // Authenticate incoming request + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + // Prepare response + + var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!'); + var headers = { 'Content-Type': 'text/plain' }; + + // Generate Server-Authorization response header + + var header = Hawk.server.header(credentials, artifacts, { payload: payload, contentType: headers['Content-Type'] }); + headers['Server-Authorization'] = header; + + // Send the response back + + res.writeHead(!err ? 200 : 401, headers); + res.end(payload); + }); +}; + +// Start server + +Http.createServer(handler).listen(8000, 'example.com'); +``` + +Client code: + +```javascript +var Request = require('request'); +var Hawk = require('hawk'); + + +// Client credentials + +var credentials = { + id: 'dh37fgj492je', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256' +} + +// Request options + +var requestOptions = { + uri: 'http://example.com:8000/resource/1?b=1&a=2', + method: 'GET', + headers: {} +}; + +// Generate Authorization request header + +var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'some-app-data' }); +requestOptions.headers.Authorization = header.field; + +// Send authenticated request + +Request(requestOptions, function (error, response, body) { + + // Authenticate the server's response + + var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body }); + + // Output results + + console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)')); +}); +``` + +**Hawk** utilized the [**SNTP**](https://github.com/hueniverse/sntp) module for time sync management. By default, the local +machine time is used. To automatically retrieve and synchronice the clock within the application, use the SNTP 'start()' method. + +```javascript +Hawk.sntp.start(); +``` + + +## Protocol Example + +The client attempts to access a protected resource without authentication, sending the following HTTP request to +the resource server: + +``` +GET /resource/1?b=1&a=2 HTTP/1.1 +Host: example.com:8000 +``` + +The resource server returns an authentication challenge. + +``` +HTTP/1.1 401 Unauthorized +WWW-Authenticate: Hawk +``` + +The client has previously obtained a set of **Hawk** credentials for accessing resources on the "http://example.com/" +server. The **Hawk** credentials issued to the client include the following attributes: + +* Key identifier: dh37fgj492je +* Key: werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn +* Algorithm: sha256 + +The client generates the authentication header by calculating a timestamp (e.g. the number of seconds since January 1, +1970 00:00:00 GMT), generating a nonce, and constructing the normalized request string (each value followed by a newline +character): + +``` +hawk.1.header +1353832234 +j4h3g2 +GET +/resource/1?b=1&a=2 +example.com +8000 + +some-app-ext-data + +``` + +The request MAC is calculated using HMAC with the specified hash algorithm "sha256" and the key over the normalized request string. +The result is base64-encoded to produce the request MAC: + +``` +6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE= +``` + +The client includes the **Hawk** key identifier, timestamp, nonce, application specific data, and request MAC with the request using +the HTTP `Authorization` request header field: + +``` +GET /resource/1?b=1&a=2 HTTP/1.1 +Host: example.com:8000 +Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE=" +``` + +The server validates the request by calculating the request MAC again based on the request received and verifies the validity +and scope of the **Hawk** credentials. If valid, the server responds with the requested resource. + + +### Payload Validation + +**Hawk** provides optional payload validation. When generating the authentication header, the client calculates a payload hash +using the specified hash algorithm. The hash is calculated over the concatenated value of (each followed by a newline character): +* `hawk.1.payload` +* the content-type in lowercase, without any parameters (e.g. `application/json`) +* the request payload prior to any content encoding (the exact representation requirements should be specified by the server for payloads other than simple single-part ascii to ensure interoperability) + +For example: + +* Payload: `Thank you for flying Hawk` +* Content Type: `text/plain` +* Hash (sha256): `Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=` + +Results in the following input to the payload hash function (newline terminated values): + +``` +hawk.1.payload +text/plain +Thank you for flying Hawk + +``` + +Which produces the following hash value: + +``` +Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY= +``` + +The client constructs the normalized request string (newline terminated values): + +``` +hawk.1.header +1353832234 +j4h3g2 +POST +/resource/1?a=1&b=2 +example.com +8000 +Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY= +some-app-ext-data + +``` + +Then calculates the request MAC and includes the **Hawk** key identifier, timestamp, nonce, payload hash, application specific data, +and request MAC, with the request using the HTTP `Authorization` request header field: + +``` +POST /resource/1?a=1&b=2 HTTP/1.1 +Host: example.com:8000 +Authorization: Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw=" +``` + +It is up to the server if and when it validates the payload for any given request, based solely on it's security policy +and the nature of the data included. + +If the payload is available at the time of authentication, the server uses the hash value provided by the client to construct +the normalized string and validates the MAC. If the MAC is valid, the server calculates the payload hash and compares the value +with the provided payload hash in the header. In many cases, checking the MAC first is faster than calculating the payload hash. + +However, if the payload is not available at authentication time (e.g. too large to fit in memory, streamed elsewhere, or processed +at a different stage in the application), the server may choose to defer payload validation for later by retaining the hash value +provided by the client after validating the MAC. + +It is important to note that MAC validation does not mean the hash value provided by the client is valid, only that the value +included in the header was not modified. Without calculating the payload hash on the server and comparing it to the value provided +by the client, the payload may be modified by an attacker. + + +## Response Payload Validation + +**Hawk** provides partial response payload validation. The server includes the `Server-Authorization` response header which enables the +client to authenticate the response and ensure it is talking to the right server. **Hawk** defines the HTTP `Server-Authorization` header +as a response header using the exact same syntax as the `Authorization` request header field. + +The header is contructed using the same process as the client's request header. The server uses the same credentials and other +artifacts provided by the client to constructs the normalized request string. The `ext` and `hash` values are replaced with +new values based on the server response. The rest as identical to those used by the client. + +The result MAC digest is included with the optional `hash` and `ext` values: + +``` +Server-Authorization: Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific" +``` + + +## Browser Support and Considerations + +A browser script is provided for including using a `<script>` tag in [lib/browser.js](/lib/browser.js). It's also a [component](http://component.io/hueniverse/hawk). + +**Hawk** relies on the _Server-Authorization_ and _WWW-Authenticate_ headers in its response to communicate with the client. +Therefore, in case of CORS requests, it is important to consider sending _Access-Control-Expose-Headers_ with the value +_"WWW-Authenticate, Server-Authorization"_ on each response from your server. As explained in the +[specifications](http://www.w3.org/TR/cors/#access-control-expose-headers-response-header), it will indicate that these headers +can safely be accessed by the client (using getResponseHeader() on the XmlHttpRequest object). Otherwise you will be met with a +["simple response header"](http://www.w3.org/TR/cors/#simple-response-header) which excludes these fields and would prevent the +Hawk client from authenticating the requests.You can read more about the why and how in this +[article](http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server) + + +# Single URI Authorization + +There are cases in which limited and short-term access to a protected resource is granted to a third party which does not +have access to the shared credentials. For example, displaying a protected image on a web page accessed by anyone. **Hawk** +provides limited support for such URIs in the form of a _bewit_ - a URI query parameter appended to the request URI which contains +the necessary credentials to authenticate the request. + +Because of the significant security risks involved in issuing such access, bewit usage is purposely limited only to GET requests +and for a finite period of time. Both the client and server can issue bewit credentials, however, the server should not use the same +credentials as the client to maintain clear traceability as to who issued which credentials. + +In order to simplify implementation, bewit credentials do not support single-use policy and can be replayed multiple times within +the granted access timeframe. + + +## Bewit Usage Example + +Server code: + +```javascript +var Http = require('http'); +var Hawk = require('hawk'); + + +// Credentials lookup function + +var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256' + }; + + return callback(null, credentials); +}; + +// Create HTTP server + +var handler = function (req, res) { + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + res.writeHead(!err ? 200 : 401, { 'Content-Type': 'text/plain' }); + res.end(!err ? 'Access granted' : 'Shoosh!'); + }); +}; + +Http.createServer(handler).listen(8000, 'example.com'); +``` + +Bewit code generation: + +```javascript +var Request = require('request'); +var Hawk = require('hawk'); + + +// Client credentials + +var credentials = { + id: 'dh37fgj492je', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256' +} + +// Generate bewit + +var duration = 60 * 5; // 5 Minutes +var bewit = Hawk.uri.getBewit('http://example.com:8080/resource/1?b=1&a=2', { credentials: credentials, ttlSec: duration, ext: 'some-app-data' }); +var uri = 'http://example.com:8000/resource/1?b=1&a=2' + '&bewit=' + bewit; +``` + + +# Security Considerations + +The greatest sources of security risks are usually found not in **Hawk** but in the policies and procedures surrounding its use. +Implementers are strongly encouraged to assess how this module addresses their security requirements. This section includes +an incomplete list of security considerations that must be reviewed and understood before deploying **Hawk** on the server. +Many of the protections provided in **Hawk** depends on whether and how they are used. + +### MAC Keys Transmission + +**Hawk** does not provide any mechanism for obtaining or transmitting the set of shared credentials required. Any mechanism used +to obtain **Hawk** credentials must ensure that these transmissions are protected using transport-layer mechanisms such as TLS. + +### Confidentiality of Requests + +While **Hawk** provides a mechanism for verifying the integrity of HTTP requests, it provides no guarantee of request +confidentiality. Unless other precautions are taken, eavesdroppers will have full access to the request content. Servers should +carefully consider the types of data likely to be sent as part of such requests, and employ transport-layer security mechanisms +to protect sensitive resources. + +### Spoofing by Counterfeit Servers + +**Hawk** provides limited verification of the server authenticity. When receiving a response back from the server, the server +may choose to include a response `Server-Authorization` header which the client can use to verify the response. However, it is up to +the server to determine when such measure is included, to up to the client to enforce that policy. + +A hostile party could take advantage of this by intercepting the client's requests and returning misleading or otherwise +incorrect responses. Service providers should consider such attacks when developing services using this protocol, and should +require transport-layer security for any requests where the authenticity of the resource server or of server responses is an issue. + +### Plaintext Storage of Credentials + +The **Hawk** key functions the same way passwords do in traditional authentication systems. In order to compute the request MAC, +the server must have access to the key in plaintext form. This is in contrast, for example, to modern operating systems, which +store only a one-way hash of user credentials. + +If an attacker were to gain access to these keys - or worse, to the server's database of all such keys - he or she would be able +to perform any action on behalf of any resource owner. Accordingly, it is critical that servers protect these keys from unauthorized +access. + +### Entropy of Keys + +Unless a transport-layer security protocol is used, eavesdroppers will have full access to authenticated requests and request +MAC values, and will thus be able to mount offline brute-force attacks to recover the key used. Servers should be careful to +assign keys which are long enough, and random enough, to resist such attacks for at least the length of time that the **Hawk** +credentials are valid. + +For example, if the credentials are valid for two weeks, servers should ensure that it is not possible to mount a brute force +attack that recovers the key in less than two weeks. Of course, servers are urged to err on the side of caution, and use the +longest key reasonable. + +It is equally important that the pseudo-random number generator (PRNG) used to generate these keys be of sufficiently high +quality. Many PRNG implementations generate number sequences that may appear to be random, but which nevertheless exhibit +patterns or other weaknesses which make cryptanalysis or brute force attacks easier. Implementers should be careful to use +cryptographically secure PRNGs to avoid these problems. + +### Coverage Limitations + +The request MAC only covers the HTTP `Host` header and optionally the `Content-Type` header. It does not cover any other headers +which can often affect how the request body is interpreted by the server. If the server behavior is influenced by the presence +or value of such headers, an attacker can manipulate the request headers without being detected. Implementers should use the +`ext` feature to pass application-specific information via the `Authorization` header which is protected by the request MAC. + +The response authentication, when performed, only covers the response payload, content-type, and the request information +provided by the client in it's request (method, resource, timestamp, nonce, etc.). It does not cover the HTTP status code or +any other response header field (e.g. Location) which can affect the client's behaviour. + +### Future Time Manipulation + +The protocol relies on a clock sync between the client and server. To accomplish this, the server informs the client of its +current time when an invalid timestamp is received. + +If an attacker is able to manipulate this information and cause the client to use an incorrect time, it would be able to cause +the client to generate authenticated requests using time in the future. Such requests will fail when sent by the client, and will +not likely leave a trace on the server (given the common implementation of nonce, if at all enforced). The attacker will then +be able to replay the request at the correct time without detection. + +The client must only use the time information provided by the server if: +* it was delivered over a TLS connection and the server identity has been verified, or +* the `tsm` MAC digest calculated using the same client credentials over the timestamp has been verified. + +### Client Clock Poisoning + +When receiving a request with a bad timestamp, the server provides the client with its current time. The client must never use +the time received from the server to adjust its own clock, and must only use it to calculate an offset for communicating with +that particular server. + +### Bewit Limitations + +Special care must be taken when issuing bewit credentials to third parties. Bewit credentials are valid until expiration and cannot +be revoked or limited without using other means. Whatever resource they grant access to will be completely exposed to anyone with +access to the bewit credentials which act as bearer credentials for that particular resource. While bewit usage is limited to GET +requests only and therefore cannot be used to perform transactions or change server state, it can still be used to expose private +and sensitive information. + +### Host Header Forgery + +Hawk validates the incoming request MAC against the incoming HTTP Host header. However, unless the optional `host` and `port` +options are used with `server.authenticate()`, a malicous client can mint new host names pointing to the server's IP address and +use that to craft an attack by sending a valid request that's meant for another hostname than the one used by the server. Server +implementors must manually verify that the host header received matches their expectation (or use the options mentioned above). + +# Frequently Asked Questions + +### Where is the protocol specification? + +If you are looking for some prose explaining how all this works, **this is it**. **Hawk** is being developed as an open source +project instead of a standard. In other words, the [code](/hueniverse/hawk/tree/master/lib) is the specification. Not sure about +something? Open an issue! + +### Is it done? + +As of version 0.10.0, **Hawk** is feature-complete. However, until this module reaches version 1.0.0 it is considered experimental +and is likely to change. This also means your feedback and contribution are very welcome. Feel free to open issues with questions +and suggestions. + +### Where can I find **Hawk** implementations in other languages? + +**Hawk**'s only reference implementation is provided in JavaScript as a node.js module. However, it has been ported to other languages. +The full list is maintained [here](https://github.com/hueniverse/hawk/issues?labels=port&state=closed). Please add an issue if you are +working on another port. A cross-platform test-suite is in the works. + +### Why isn't the algorithm part of the challenge or dynamically negotiated? + +The algorithm used is closely related to the key issued as different algorithms require different key sizes (and other +requirements). While some keys can be used for multiple algorithm, the protocol is designed to closely bind the key and algorithm +together as part of the issued credentials. + +### Why is Host and Content-Type the only headers covered by the request MAC? + +It is really hard to include other headers. Headers can be changed by proxies and other intermediaries and there is no +well-established way to normalize them. Many platforms change the case of header field names and values. The only +straight-forward solution is to include the headers in some blob (say, base64 encoded JSON) and include that with the request, +an approach taken by JWT and other such formats. However, that design violates the HTTP header boundaries, repeats information, +and introduces other security issues because firewalls will not be aware of these "hidden" headers. In addition, any information +repeated must be compared to the duplicated information in the header and therefore only moves the problem elsewhere. + +### Why not just use HTTP Digest? + +Digest requires pre-negotiation to establish a nonce. This means you can't just make a request - you must first send +a protocol handshake to the server. This pattern has become unacceptable for most web services, especially mobile +where extra round-trip are costly. + +### Why bother with all this nonce and timestamp business? + +**Hawk** is an attempt to find a reasonable, practical compromise between security and usability. OAuth 1.0 got timestamp +and nonces halfway right but failed when it came to scalability and consistent developer experience. **Hawk** addresses +it by requiring the client to sync its clock, but provides it with tools to accomplish it. + +In general, replay protection is a matter of application-specific threat model. It is less of an issue on a TLS-protected +system where the clients are implemented using best practices and are under the control of the server. Instead of dropping +replay protection, **Hawk** offers a required time window and an optional nonce verification. Together, it provides developers +with the ability to decide how to enforce their security policy without impacting the client's implementation. + +### What are `app` and `dlg` in the authorization header and normalized mac string? + +The original motivation for **Hawk** was to replace the OAuth 1.0 use cases. This included both a simple client-server mode which +this module is specifically designed for, and a delegated access mode which is being developed separately in +[Oz](https://github.com/hueniverse/oz). In addition to the **Hawk** use cases, Oz requires another attribute: the application id `app`. +This provides binding between the credentials and the application in a way that prevents an attacker from tricking an application +to use credentials issued to someone else. It also has an optional 'delegated-by' attribute `dlg` which is the application id of the +application the credentials were directly issued to. The goal of these two additions is to allow Oz to utilize **Hawk** directly, +but with the additional security of delegated credentials. + +### What is the purpose of the static strings used in each normalized MAC input? + +When calculating a hash or MAC, a static prefix (tag) is added. The prefix is used to prevent MAC values from being +used or reused for a purpose other than what they were created for (i.e. prevents switching MAC values between a request, +response, and a bewit use cases). It also protects against exploits created after a potential change in how the protocol +creates the normalized string. For example, if a future version would switch the order of nonce and timestamp, it +can create an exploit opportunity for cases where the nonce is similar in format to a timestamp. + +### Does **Hawk** have anything to do with OAuth? + +Short answer: no. + +**Hawk** was originally proposed as the OAuth MAC Token specification. However, the OAuth working group in its consistent +incompetence failed to produce a final, usable solution to address one of the most popular use cases of OAuth 1.0 - using it +to authenticate simple client-server transactions (i.e. two-legged). As you can guess, the OAuth working group is still hard +at work to produce more garbage. + +**Hawk** provides a simple HTTP authentication scheme for making client-server requests. It does not address the OAuth use case +of delegating access to a third party. If you are looking for an OAuth alternative, check out [Oz](https://github.com/hueniverse/oz). + +# Implementations + +- [Logibit Hawk in F#/.Net](https://github.com/logibit/logibit.hawk/) +- [Tent Hawk in Ruby](https://github.com/tent/hawk-ruby) +- [Wealdtech in Java](https://github.com/wealdtech/hawk) +- [Kumar's Mohawk in Python](https://github.com/kumar303/mohawk/) + +# Acknowledgements + +**Hawk** is a derivative work of the [HTTP MAC Authentication Scheme](http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05) proposal +co-authored by Ben Adida, Adam Barth, and Eran Hammer, which in turn was based on the OAuth 1.0 community specification. + +Special thanks to Ben Laurie for his always insightful feedback and advice. + +The **Hawk** logo was created by [Chris Carrasco](http://chriscarrasco.com). diff --git a/node_modules/hawk/bower.json b/node_modules/hawk/bower.json new file mode 100644 index 000000000..7d2d120e0 --- /dev/null +++ b/node_modules/hawk/bower.json @@ -0,0 +1,24 @@ +{ + "name": "hawk", + "main": "lib/browser.js", + "license": "./LICENSE", + "ignore": [ + "!lib", + "lib/*", + "!lib/browser.js", + "index.js" + ], + "keywords": [ + "http", + "authentication", + "scheme", + "hawk" + ], + "authors": [ + "Eran Hammer <eran@hammer.io>" + ], + "repository": { + "type": "git", + "url": "git://github.com/hueniverse/hawk.git" + } +} diff --git a/node_modules/hawk/component.json b/node_modules/hawk/component.json new file mode 100644 index 000000000..63e76a2e3 --- /dev/null +++ b/node_modules/hawk/component.json @@ -0,0 +1,19 @@ +{ + "name": "hawk", + "repo": "hueniverse/hawk", + "description": "HTTP Hawk Authentication Scheme", + "version": "1.0.0", + "keywords": [ + "http", + "authentication", + "scheme", + "hawk" + ], + "dependencies": {}, + "development": {}, + "license": "BSD", + "main": "lib/browser.js", + "scripts": [ + "lib/browser.js" + ] +}
\ No newline at end of file diff --git a/node_modules/hawk/example/usage.js b/node_modules/hawk/example/usage.js new file mode 100755 index 000000000..8c063f6cf --- /dev/null +++ b/node_modules/hawk/example/usage.js @@ -0,0 +1,78 @@ +// Load modules + +var Http = require('http'); +var Request = require('request'); +var Hawk = require('../lib'); + + +// Declare internals + +var internals = { + credentials: { + dh37fgj492je: { + id: 'dh37fgj492je', // Required by Hawk.client.header + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'Steve' + } + } +}; + + +// Credentials lookup function + +var credentialsFunc = function (id, callback) { + + return callback(null, internals.credentials[id]); +}; + + +// Create HTTP server + +var handler = function (req, res) { + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!'); + var headers = { + 'Content-Type': 'text/plain', + 'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' }) + }; + + res.writeHead(!err ? 200 : 401, headers); + res.end(payload); + }); +}; + +Http.createServer(handler).listen(8000, '127.0.0.1'); + + +// Send unauthenticated request + +Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) { + + console.log(response.statusCode + ': ' + body); +}); + + +// Send authenticated request + +credentialsFunc('dh37fgj492je', function (err, credentials) { + + var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' }); + var options = { + uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2', + method: 'GET', + headers: { + authorization: header.field + } + }; + + Request(options, function (error, response, body) { + + var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body }); + console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)')); + process.exit(0); + }); +}); + diff --git a/node_modules/hawk/images/hawk.png b/node_modules/hawk/images/hawk.png Binary files differnew file mode 100755 index 000000000..a0e15cda0 --- /dev/null +++ b/node_modules/hawk/images/hawk.png diff --git a/node_modules/hawk/images/logo.png b/node_modules/hawk/images/logo.png Binary files differnew file mode 100755 index 000000000..b8ff59017 --- /dev/null +++ b/node_modules/hawk/images/logo.png diff --git a/node_modules/hawk/index.js b/node_modules/hawk/index.js new file mode 100755 index 000000000..4cc88b358 --- /dev/null +++ b/node_modules/hawk/index.js @@ -0,0 +1 @@ +module.exports = require('./lib');
\ No newline at end of file diff --git a/node_modules/hawk/lib/browser.js b/node_modules/hawk/lib/browser.js new file mode 100755 index 000000000..3307fa243 --- /dev/null +++ b/node_modules/hawk/lib/browser.js @@ -0,0 +1,641 @@ +/* + HTTP Hawk Authentication Scheme + Copyright (c) 2012-2014, Eran Hammer <eran@hammer.io> + BSD Licensed +*/ + + +// Declare namespace + +var hawk = { + internals: {} +}; + + +hawk.client = { + + // Generate an Authorization header for a given request + + /* + uri: 'http://example.com/resource?a=b' or object generated by hawk.utils.parseUri() + method: HTTP verb (e.g. 'GET', 'POST') + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + + // Optional + + ext: 'application-specific', // Application specific data sent via the ext attribute + timestamp: Date.now() / 1000, // A pre-calculated timestamp in seconds + nonce: '2334f34f', // A pre-generated nonce + localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) + payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) + contentType: 'application/json', // Payload content-type (ignored if hash provided) + hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash + app: '24s23423f34dx', // Oz application id + dlg: '234sz34tww3sd' // Oz delegated-by application id + } + */ + + header: function (uri, method, options) { + + var result = { + field: '', + artifacts: {} + }; + + // Validate inputs + + if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') || + !method || typeof method !== 'string' || + !options || typeof options !== 'object') { + + result.err = 'Invalid argument type'; + return result; + } + + // Application time + + var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + result.err = 'Invalid credentials object'; + return result; + } + + if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) { + result.err = 'Unknown algorithm'; + return result; + } + + // Parse URI + + if (typeof uri === 'string') { + uri = hawk.utils.parseUri(uri); + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || hawk.utils.randomString(6), + method: method, + resource: uri.relative, + host: uri.hostname, + port: uri.port, + hash: options.hash, + ext: options.ext, + app: options.app, + dlg: options.dlg + }; + + result.artifacts = artifacts; + + // Calculate payload hash + + if (!artifacts.hash && + (options.payload || options.payload === '')) { + + artifacts.hash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + } + + var mac = hawk.crypto.calculateMac('header', credentials, artifacts); + + // Construct header + + var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed + var header = 'Hawk id="' + credentials.id + + '", ts="' + artifacts.ts + + '", nonce="' + artifacts.nonce + + (artifacts.hash ? '", hash="' + artifacts.hash : '') + + (hasExt ? '", ext="' + hawk.utils.escapeHeaderAttribute(artifacts.ext) : '') + + '", mac="' + mac + '"'; + + if (artifacts.app) { + header += ', app="' + artifacts.app + + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'; + } + + result.field = header; + + return result; + }, + + // Generate a bewit value for a given URI + + /* + uri: 'http://example.com/resource?a=b' + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + ttlSec: 60 * 60, // TTL in seconds + + // Optional + + ext: 'application-specific', // Application specific data sent via the ext attribute + localtimeOffsetMsec: 400 // Time offset to sync with server time + }; + */ + + bewit: function (uri, options) { + + // Validate inputs + + if (!uri || + (typeof uri !== 'string') || + !options || + typeof options !== 'object' || + !options.ttlSec) { + + return ''; + } + + options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value + + // Application time + + var now = hawk.utils.now(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + return ''; + } + + if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return ''; + } + + // Parse URI + + uri = hawk.utils.parseUri(uri); + + // Calculate signature + + var exp = now + options.ttlSec; + var mac = hawk.crypto.calculateMac('bewit', credentials, { + ts: exp, + nonce: '', + method: 'GET', + resource: uri.relative, // Maintain trailing '?' and query params + host: uri.hostname, + port: uri.port, + ext: options.ext + }); + + // Construct bewit: id\exp\mac\ext + + var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext; + return hawk.utils.base64urlEncode(bewit); + }, + + // Validate server response + + /* + request: object created via 'new XMLHttpRequest()' after response received + artifacts: object received from header().artifacts + options: { + payload: optional payload received + required: specifies if a Server-Authorization header is required. Defaults to 'false' + } + */ + + authenticate: function (request, credentials, artifacts, options) { + + options = options || {}; + + var getHeader = function (name) { + + return request.getResponseHeader ? request.getResponseHeader(name) : request.getHeader(name); + }; + + var wwwAuthenticate = getHeader('www-authenticate'); + if (wwwAuthenticate) { + + // Parse HTTP WWW-Authenticate header + + var attributes = hawk.utils.parseAuthorizationHeader(wwwAuthenticate, ['ts', 'tsm', 'error']); + if (!attributes) { + return false; + } + + if (attributes.ts) { + var tsm = hawk.crypto.calculateTsMac(attributes.ts, credentials); + if (tsm !== attributes.tsm) { + return false; + } + + hawk.utils.setNtpOffset(attributes.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision + } + } + + // Parse HTTP Server-Authorization header + + var serverAuthorization = getHeader('server-authorization'); + if (!serverAuthorization && + !options.required) { + + return true; + } + + var attributes = hawk.utils.parseAuthorizationHeader(serverAuthorization, ['mac', 'ext', 'hash']); + if (!attributes) { + return false; + } + + var modArtifacts = { + ts: artifacts.ts, + nonce: artifacts.nonce, + method: artifacts.method, + resource: artifacts.resource, + host: artifacts.host, + port: artifacts.port, + hash: attributes.hash, + ext: attributes.ext, + app: artifacts.app, + dlg: artifacts.dlg + }; + + var mac = hawk.crypto.calculateMac('response', credentials, modArtifacts); + if (mac !== attributes.mac) { + return false; + } + + if (!options.payload && + options.payload !== '') { + + return true; + } + + if (!attributes.hash) { + return false; + } + + var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, getHeader('content-type')); + return (calculatedHash === attributes.hash); + }, + + message: function (host, port, message, options) { + + // Validate inputs + + if (!host || typeof host !== 'string' || + !port || typeof port !== 'number' || + message === null || message === undefined || typeof message !== 'string' || + !options || typeof options !== 'object') { + + return null; + } + + // Application time + + var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + // Invalid credential object + return null; + } + + if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return null; + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || hawk.utils.randomString(6), + host: host, + port: port, + hash: hawk.crypto.calculatePayloadHash(message, credentials.algorithm) + }; + + // Construct authorization + + var result = { + id: credentials.id, + ts: artifacts.ts, + nonce: artifacts.nonce, + hash: artifacts.hash, + mac: hawk.crypto.calculateMac('message', credentials, artifacts) + }; + + return result; + }, + + authenticateTimestamp: function (message, credentials, updateClock) { // updateClock defaults to true + + var tsm = hawk.crypto.calculateTsMac(message.ts, credentials); + if (tsm !== message.tsm) { + return false; + } + + if (updateClock !== false) { + hawk.utils.setNtpOffset(message.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision + } + + return true; + } +}; + + +hawk.crypto = { + + headerVersion: '1', + + algorithms: ['sha1', 'sha256'], + + calculateMac: function (type, credentials, options) { + + var normalized = hawk.crypto.generateNormalizedString(type, options); + + var hmac = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()](normalized, credentials.key); + return hmac.toString(CryptoJS.enc.Base64); + }, + + generateNormalizedString: function (type, options) { + + var normalized = 'hawk.' + hawk.crypto.headerVersion + '.' + type + '\n' + + options.ts + '\n' + + options.nonce + '\n' + + (options.method || '').toUpperCase() + '\n' + + (options.resource || '') + '\n' + + options.host.toLowerCase() + '\n' + + options.port + '\n' + + (options.hash || '') + '\n'; + + if (options.ext) { + normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); + } + + normalized += '\n'; + + if (options.app) { + normalized += options.app + '\n' + + (options.dlg || '') + '\n'; + } + + return normalized; + }, + + calculatePayloadHash: function (payload, algorithm, contentType) { + + var hash = CryptoJS.algo[algorithm.toUpperCase()].create(); + hash.update('hawk.' + hawk.crypto.headerVersion + '.payload\n'); + hash.update(hawk.utils.parseContentType(contentType) + '\n'); + hash.update(payload); + hash.update('\n'); + return hash.finalize().toString(CryptoJS.enc.Base64); + }, + + calculateTsMac: function (ts, credentials) { + + var hash = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()]('hawk.' + hawk.crypto.headerVersion + '.ts\n' + ts + '\n', credentials.key); + return hash.toString(CryptoJS.enc.Base64); + } +}; + + +// localStorage compatible interface + +hawk.internals.LocalStorage = function () { + + this._cache = {}; + this.length = 0; + + this.getItem = function (key) { + + return this._cache.hasOwnProperty(key) ? String(this._cache[key]) : null; + }; + + this.setItem = function (key, value) { + + this._cache[key] = String(value); + this.length = Object.keys(this._cache).length; + }; + + this.removeItem = function (key) { + + delete this._cache[key]; + this.length = Object.keys(this._cache).length; + }; + + this.clear = function () { + + this._cache = {}; + this.length = 0; + }; + + this.key = function (i) { + + return Object.keys(this._cache)[i || 0]; + }; +}; + + +hawk.utils = { + + storage: new hawk.internals.LocalStorage(), + + setStorage: function (storage) { + + var ntpOffset = hawk.utils.storage.getItem('hawk_ntp_offset'); + hawk.utils.storage = storage; + if (ntpOffset) { + hawk.utils.setNtpOffset(ntpOffset); + } + }, + + setNtpOffset: function (offset) { + + try { + hawk.utils.storage.setItem('hawk_ntp_offset', offset); + } + catch (err) { + console.error('[hawk] could not write to storage.'); + console.error(err); + } + }, + + getNtpOffset: function () { + + var offset = hawk.utils.storage.getItem('hawk_ntp_offset'); + if (!offset) { + return 0; + } + + return parseInt(offset, 10); + }, + + now: function (localtimeOffsetMsec) { + + return Math.floor(((new Date()).getTime() + (localtimeOffsetMsec || 0)) / 1000) + hawk.utils.getNtpOffset(); + }, + + escapeHeaderAttribute: function (attribute) { + + return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); + }, + + parseContentType: function (header) { + + if (!header) { + return ''; + } + + return header.split(';')[0].replace(/^\s+|\s+$/g, '').toLowerCase(); + }, + + parseAuthorizationHeader: function (header, keys) { + + if (!header) { + return null; + } + + var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something] + if (!headerParts) { + return null; + } + + var scheme = headerParts[1]; + if (scheme.toLowerCase() !== 'hawk') { + return null; + } + + var attributesString = headerParts[2]; + if (!attributesString) { + return null; + } + + var attributes = {}; + var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) { + + // Check valid attribute names + + if (keys.indexOf($1) === -1) { + return; + } + + // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9 + + if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) { + return; + } + + // Check for duplicates + + if (attributes.hasOwnProperty($1)) { + return; + } + + attributes[$1] = $2; + return ''; + }); + + if (verify !== '') { + return null; + } + + return attributes; + }, + + randomString: function (size) { + + var randomSource = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + var len = randomSource.length; + + var result = []; + for (var i = 0; i < size; ++i) { + result[i] = randomSource[Math.floor(Math.random() * len)]; + } + + return result.join(''); + }, + + parseUri: function (input) { + + // Based on: parseURI 1.2.2 + // http://blog.stevenlevithan.com/archives/parseuri + // (c) Steven Levithan <stevenlevithan.com> + // MIT License + + var keys = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'hostname', 'port', 'resource', 'relative', 'pathname', 'directory', 'file', 'query', 'fragment']; + + var uriRegex = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?)(?:#(.*))?)/; + var uriByNumber = input.match(uriRegex); + var uri = {}; + + for (var i = 0, il = keys.length; i < il; ++i) { + uri[keys[i]] = uriByNumber[i] || ''; + } + + if (uri.port === '') { + uri.port = (uri.protocol.toLowerCase() === 'http' ? '80' : (uri.protocol.toLowerCase() === 'https' ? '443' : '')); + } + + return uri; + }, + + base64urlEncode: function (value) { + + var wordArray = CryptoJS.enc.Utf8.parse(value); + var encoded = CryptoJS.enc.Base64.stringify(wordArray); + return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); + } +}; + + +// $lab:coverage:off$ + +// Based on: Crypto-JS v3.1.2 +// Copyright (c) 2009-2013, Jeff Mott. All rights reserved. +// http://code.google.com/p/crypto-js/ +// http://code.google.com/p/crypto-js/wiki/License + +var CryptoJS = CryptoJS || function (h, r) { var k = {}, l = k.lib = {}, n = function () { }, f = l.Base = { extend: function (a) { n.prototype = this; var b = new n; a && b.mixIn(a); b.hasOwnProperty("init") || (b.init = function () { b.$super.init.apply(this, arguments) }); b.init.prototype = b; b.$super = this; return b }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var b in a) a.hasOwnProperty(b) && (this[b] = a[b]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, j = l.WordArray = f.extend({ init: function (a, b) { a = this.words = a || []; this.sigBytes = b != r ? b : 4 * a.length }, toString: function (a) { return (a || s).stringify(this) }, concat: function (a) { var b = this.words, d = a.words, c = this.sigBytes; a = a.sigBytes; this.clamp(); if (c % 4) for (var e = 0; e < a; e++) b[c + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 - 8 * ((c + e) % 4); else if (65535 < d.length) for (e = 0; e < a; e += 4) b[c + e >>> 2] = d[e >>> 2]; else b.push.apply(b, d); this.sigBytes += a; return this }, clamp: function () { var a = this.words, b = this.sigBytes; a[b >>> 2] &= 4294967295 << 32 - 8 * (b % 4); a.length = h.ceil(b / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var b = [], d = 0; d < a; d += 4) b.push(4294967296 * h.random() | 0); return new j.init(b, a) } }), m = k.enc = {}, s = m.Hex = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) { var e = b[c >>> 2] >>> 24 - 8 * (c % 4) & 255; d.push((e >>> 4).toString(16)); d.push((e & 15).toString(16)) } return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c += 2) d[c >>> 3] |= parseInt(a.substr(c, 2), 16) << 24 - 4 * (c % 8); return new j.init(d, b / 2) } }, p = m.Latin1 = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) d.push(String.fromCharCode(b[c >>> 2] >>> 24 - 8 * (c % 4) & 255)); return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c++) d[c >>> 2] |= (a.charCodeAt(c) & 255) << 24 - 8 * (c % 4); return new j.init(d, b) } }, t = m.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(p.stringify(a))) } catch (b) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return p.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new j.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = t.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var b = this._data, d = b.words, c = b.sigBytes, e = this.blockSize, f = c / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); a = f * e; c = h.min(4 * a, c); if (a) { for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); g = d.splice(0, a); b.sigBytes -= c } return new j.init(g, c) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new u.HMAC.init(a, d)).finalize(b) } } }); var u = k.algo = {}; return k }(Math); +(function () { var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function () { this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (n, p) { for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) { if (16 > c) d[c] = n[p + c] | 0; else { var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16]; d[c] = g << 1 | g >>> 31 } g = (e << 5 | e >>> 27) + b + d[c]; g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514); b = j; j = h; h = f << 30 | f >>> 2; f = e; e = g } a[0] = a[0] + e | 0; a[1] = a[1] + f | 0; a[2] = a[2] + h | 0; a[3] = a[3] + j | 0; a[4] = a[4] + b | 0 }, _doFinalize: function () { var b = this._data, d = b.words, a = 8 * this._nDataBytes, e = 8 * b.sigBytes; d[e >>> 5] |= 128 << 24 - e % 32; d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296); d[(e + 64 >>> 9 << 4) + 15] = a; b.sigBytes = 4 * d.length; this._process(); return this._hash }, clone: function () { var b = l.clone.call(this); b._hash = this._hash.clone(); return b } }); k.SHA1 = l._createHelper(b); k.HmacSHA1 = l._createHmacHelper(b) })(); +(function (k) { for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) { return 4294967296 * (q - (q | 0)) | 0 }, l = 2, b = 0; 64 > b;) { var d; a: { d = l; for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) { d = !1; break a } d = !0 } d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++); l++ } var n = [], h = h.SHA256 = j.extend({ _doReset: function () { this._hash = new v.init(s.slice(0)) }, _doProcessBlock: function (q, h) { for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) { if (16 > e) n[e] = q[h + e] | 0; else { var m = n[e - 15], p = n[e - 2]; n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16] } m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e]; p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b); l = j; j = g; g = f; f = k + m | 0; k = b; b = d; d = c; c = m + p | 0 } a[0] = a[0] + c | 0; a[1] = a[1] + d | 0; a[2] = a[2] + b | 0; a[3] = a[3] + k | 0; a[4] = a[4] + f | 0; a[5] = a[5] + g | 0; a[6] = a[6] + j | 0; a[7] = a[7] + l | 0 }, _doFinalize: function () { var d = this._data, b = d.words, a = 8 * this._nDataBytes, c = 8 * d.sigBytes; b[c >>> 5] |= 128 << 24 - c % 32; b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296); b[(c + 64 >>> 9 << 4) + 15] = a; d.sigBytes = 4 * b.length; this._process(); return this._hash }, clone: function () { var b = j.clone.call(this); b._hash = this._hash.clone(); return b } }); g.SHA256 = j._createHelper(h); g.HmacSHA256 = j._createHmacHelper(h) })(Math); +(function () { var c = CryptoJS, k = c.enc.Utf8; c.algo.HMAC = c.lib.Base.extend({ init: function (a, b) { a = this._hasher = new a.init; "string" == typeof b && (b = k.parse(b)); var c = a.blockSize, e = 4 * c; b.sigBytes > e && (b = a.finalize(b)); b.clamp(); for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486; f.sigBytes = g.sigBytes = e; this.reset() }, reset: function () { var a = this._hasher; a.reset(); a.update(this._iKey) }, update: function (a) { this._hasher.update(a); return this }, finalize: function (a) { var b = this._hasher; a = b.finalize(a); b.reset(); return b.finalize(this._oKey.clone().concat(a)) } }) })(); +(function () { var h = CryptoJS, j = h.lib.WordArray; h.enc.Base64 = { stringify: function (b) { var e = b.words, f = b.sigBytes, c = this._map; b.clamp(); b = []; for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63)); if (e = c.charAt(64)) for (; b.length % 4;) b.push(e); return b.join("") }, parse: function (b) { var e = b.length, f = this._map, c = f.charAt(64); c && (c = b.indexOf(c), -1 != c && (e = c)); for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) { var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4); c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4); a++ } return j.create(c, a) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })(); + +hawk.crypto.internals = CryptoJS; + + +// Export if used as a module + +if (typeof module !== 'undefined' && module.exports) { + module.exports = hawk; +} + +// $lab:coverage:on$ diff --git a/node_modules/hawk/lib/client.js b/node_modules/hawk/lib/client.js new file mode 100755 index 000000000..7fdd48412 --- /dev/null +++ b/node_modules/hawk/lib/client.js @@ -0,0 +1,369 @@ +// Load modules + +var Url = require('url'); +var Hoek = require('hoek'); +var Cryptiles = require('cryptiles'); +var Crypto = require('./crypto'); +var Utils = require('./utils'); + + +// Declare internals + +var internals = {}; + + +// Generate an Authorization header for a given request + +/* + uri: 'http://example.com/resource?a=b' or object from Url.parse() + method: HTTP verb (e.g. 'GET', 'POST') + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + + // Optional + + ext: 'application-specific', // Application specific data sent via the ext attribute + timestamp: Date.now(), // A pre-calculated timestamp + nonce: '2334f34f', // A pre-generated nonce + localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) + payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) + contentType: 'application/json', // Payload content-type (ignored if hash provided) + hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash + app: '24s23423f34dx', // Oz application id + dlg: '234sz34tww3sd' // Oz delegated-by application id + } +*/ + +exports.header = function (uri, method, options) { + + var result = { + field: '', + artifacts: {} + }; + + // Validate inputs + + if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') || + !method || typeof method !== 'string' || + !options || typeof options !== 'object') { + + result.err = 'Invalid argument type'; + return result; + } + + // Application time + + var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + result.err = 'Invalid credential object'; + return result; + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + result.err = 'Unknown algorithm'; + return result; + } + + // Parse URI + + if (typeof uri === 'string') { + uri = Url.parse(uri); + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || Cryptiles.randomString(6), + method: method, + resource: uri.pathname + (uri.search || ''), // Maintain trailing '?' + host: uri.hostname, + port: uri.port || (uri.protocol === 'http:' ? 80 : 443), + hash: options.hash, + ext: options.ext, + app: options.app, + dlg: options.dlg + }; + + result.artifacts = artifacts; + + // Calculate payload hash + + if (!artifacts.hash && + (options.payload || options.payload === '')) { + + artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + } + + var mac = Crypto.calculateMac('header', credentials, artifacts); + + // Construct header + + var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed + var header = 'Hawk id="' + credentials.id + + '", ts="' + artifacts.ts + + '", nonce="' + artifacts.nonce + + (artifacts.hash ? '", hash="' + artifacts.hash : '') + + (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') + + '", mac="' + mac + '"'; + + if (artifacts.app) { + header += ', app="' + artifacts.app + + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'; + } + + result.field = header; + + return result; +}; + + +// Validate server response + +/* + res: node's response object + artifacts: object received from header().artifacts + options: { + payload: optional payload received + required: specifies if a Server-Authorization header is required. Defaults to 'false' + } +*/ + +exports.authenticate = function (res, credentials, artifacts, options) { + + artifacts = Hoek.clone(artifacts); + options = options || {}; + + if (res.headers['www-authenticate']) { + + // Parse HTTP WWW-Authenticate header + + var attributes = Utils.parseAuthorizationHeader(res.headers['www-authenticate'], ['ts', 'tsm', 'error']); + if (attributes instanceof Error) { + return false; + } + + // Validate server timestamp (not used to update clock since it is done via the SNPT client) + + if (attributes.ts) { + var tsm = Crypto.calculateTsMac(attributes.ts, credentials); + if (tsm !== attributes.tsm) { + return false; + } + } + } + + // Parse HTTP Server-Authorization header + + if (!res.headers['server-authorization'] && + !options.required) { + + return true; + } + + var attributes = Utils.parseAuthorizationHeader(res.headers['server-authorization'], ['mac', 'ext', 'hash']); + if (attributes instanceof Error) { + return false; + } + + artifacts.ext = attributes.ext; + artifacts.hash = attributes.hash; + + var mac = Crypto.calculateMac('response', credentials, artifacts); + if (mac !== attributes.mac) { + return false; + } + + if (!options.payload && + options.payload !== '') { + + return true; + } + + if (!attributes.hash) { + return false; + } + + var calculatedHash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, res.headers['content-type']); + return (calculatedHash === attributes.hash); +}; + + +// Generate a bewit value for a given URI + +/* + uri: 'http://example.com/resource?a=b' or object from Url.parse() + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + ttlSec: 60 * 60, // TTL in seconds + + // Optional + + ext: 'application-specific', // Application specific data sent via the ext attribute + localtimeOffsetMsec: 400 // Time offset to sync with server time + }; +*/ + +exports.getBewit = function (uri, options) { + + // Validate inputs + + if (!uri || + (typeof uri !== 'string' && typeof uri !== 'object') || + !options || + typeof options !== 'object' || + !options.ttlSec) { + + return ''; + } + + options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value + + // Application time + + var now = Utils.now(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + return ''; + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return ''; + } + + // Parse URI + + if (typeof uri === 'string') { + uri = Url.parse(uri); + } + + // Calculate signature + + var exp = Math.floor(now / 1000) + options.ttlSec; + var mac = Crypto.calculateMac('bewit', credentials, { + ts: exp, + nonce: '', + method: 'GET', + resource: uri.pathname + (uri.search || ''), // Maintain trailing '?' + host: uri.hostname, + port: uri.port || (uri.protocol === 'http:' ? 80 : 443), + ext: options.ext + }); + + // Construct bewit: id\exp\mac\ext + + var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext; + return Hoek.base64urlEncode(bewit); +}; + + +// Generate an authorization string for a message + +/* + host: 'example.com', + port: 8000, + message: '{"some":"payload"}', // UTF-8 encoded string for body hash generation + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + + // Optional + + timestamp: Date.now(), // A pre-calculated timestamp + nonce: '2334f34f', // A pre-generated nonce + localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) + } +*/ + +exports.message = function (host, port, message, options) { + + // Validate inputs + + if (!host || typeof host !== 'string' || + !port || typeof port !== 'number' || + message === null || message === undefined || typeof message !== 'string' || + !options || typeof options !== 'object') { + + return null; + } + + // Application time + + var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec); + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + // Invalid credential object + return null; + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return null; + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || Cryptiles.randomString(6), + host: host, + port: port, + hash: Crypto.calculatePayloadHash(message, credentials.algorithm) + }; + + // Construct authorization + + var result = { + id: credentials.id, + ts: artifacts.ts, + nonce: artifacts.nonce, + hash: artifacts.hash, + mac: Crypto.calculateMac('message', credentials, artifacts) + }; + + return result; +}; + + + diff --git a/node_modules/hawk/lib/crypto.js b/node_modules/hawk/lib/crypto.js new file mode 100755 index 000000000..d3c8244a9 --- /dev/null +++ b/node_modules/hawk/lib/crypto.js @@ -0,0 +1,126 @@ +// Load modules + +var Crypto = require('crypto'); +var Url = require('url'); +var Utils = require('./utils'); + + +// Declare internals + +var internals = {}; + + +// MAC normalization format version + +exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats + + +// Supported HMAC algorithms + +exports.algorithms = ['sha1', 'sha256']; + + +// Calculate the request MAC + +/* + type: 'header', // 'header', 'bewit', 'response' + credentials: { + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + options: { + method: 'GET', + resource: '/resource?a=1&b=2', + host: 'example.com', + port: 8080, + ts: 1357718381034, + nonce: 'd3d345f', + hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=', + ext: 'app-specific-data', + app: 'hf48hd83qwkj', // Application id (Oz) + dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app + } +*/ + +exports.calculateMac = function (type, credentials, options) { + + var normalized = exports.generateNormalizedString(type, options); + + var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized); + var digest = hmac.digest('base64'); + return digest; +}; + + +exports.generateNormalizedString = function (type, options) { + + var resource = options.resource || ''; + if (resource && + resource[0] !== '/') { + + var url = Url.parse(resource, false); + resource = url.path; // Includes query + } + + var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' + + options.ts + '\n' + + options.nonce + '\n' + + (options.method || '').toUpperCase() + '\n' + + resource + '\n' + + options.host.toLowerCase() + '\n' + + options.port + '\n' + + (options.hash || '') + '\n'; + + if (options.ext) { + normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); + } + + normalized += '\n'; + + if (options.app) { + normalized += options.app + '\n' + + (options.dlg || '') + '\n'; + } + + return normalized; +}; + + +exports.calculatePayloadHash = function (payload, algorithm, contentType) { + + var hash = exports.initializePayloadHash(algorithm, contentType); + hash.update(payload || ''); + return exports.finalizePayloadHash(hash); +}; + + +exports.initializePayloadHash = function (algorithm, contentType) { + + var hash = Crypto.createHash(algorithm); + hash.update('hawk.' + exports.headerVersion + '.payload\n'); + hash.update(Utils.parseContentType(contentType) + '\n'); + return hash; +}; + + +exports.finalizePayloadHash = function (hash) { + + hash.update('\n'); + return hash.digest('base64'); +}; + + +exports.calculateTsMac = function (ts, credentials) { + + var hmac = Crypto.createHmac(credentials.algorithm, credentials.key); + hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n'); + return hmac.digest('base64'); +}; + + +exports.timestampMessage = function (credentials, localtimeOffsetMsec) { + + var now = Utils.nowSecs(localtimeOffsetMsec); + var tsm = exports.calculateTsMac(now, credentials); + return { ts: now, tsm: tsm }; +}; diff --git a/node_modules/hawk/lib/index.js b/node_modules/hawk/lib/index.js new file mode 100755 index 000000000..a883882c8 --- /dev/null +++ b/node_modules/hawk/lib/index.js @@ -0,0 +1,15 @@ +// Export sub-modules + +exports.error = exports.Error = require('boom'); +exports.sntp = require('sntp'); + +exports.server = require('./server'); +exports.client = require('./client'); +exports.crypto = require('./crypto'); +exports.utils = require('./utils'); + +exports.uri = { + authenticate: exports.server.authenticateBewit, + getBewit: exports.client.getBewit +}; + diff --git a/node_modules/hawk/lib/server.js b/node_modules/hawk/lib/server.js new file mode 100755 index 000000000..a80393031 --- /dev/null +++ b/node_modules/hawk/lib/server.js @@ -0,0 +1,534 @@ +// Load modules + +var Boom = require('boom'); +var Hoek = require('hoek'); +var Cryptiles = require('cryptiles'); +var Crypto = require('./crypto'); +var Utils = require('./utils'); + + +// Declare internals + +var internals = {}; + + +// Hawk authentication + +/* + req: node's HTTP request object or an object as follows: + + var request = { + method: 'GET', + url: '/resource/4?a=1&b=2', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="' + }; + + credentialsFunc: required function to lookup the set of Hawk credentials based on the provided credentials id. + The credentials include the MAC key, MAC algorithm, and other attributes (such as username) + needed by the application. This function is the equivalent of verifying the username and + password in Basic authentication. + + var credentialsFunc = function (id, callback) { + + // Lookup credentials in database + db.lookup(id, function (err, item) { + + if (err || !item) { + return callback(err); + } + + var credentials = { + // Required + key: item.key, + algorithm: item.algorithm, + // Application specific + user: item.user + }; + + return callback(null, credentials); + }); + }; + + options: { + + hostHeaderName: optional header field name, used to override the default 'Host' header when used + behind a cache of a proxy. Apache2 changes the value of the 'Host' header while preserving + the original (which is what the module must verify) in the 'x-forwarded-host' header field. + Only used when passed a node Http.ServerRequest object. + + nonceFunc: optional nonce validation function. The function signature is function(nonce, ts, callback) + where 'callback' must be called using the signature function(err). + + timestampSkewSec: optional number of seconds of permitted clock skew for incoming timestamps. Defaults to 60 seconds. + Provides a +/- skew which means actual allowed window is double the number of seconds. + + localtimeOffsetMsec: optional local clock time offset express in a number of milliseconds (positive or negative). + Defaults to 0. + + payload: optional payload for validation. The client calculates the hash value and includes it via the 'hash' + header attribute. The server always ensures the value provided has been included in the request + MAC. When this option is provided, it validates the hash value itself. Validation is done by calculating + a hash value over the entire payload (assuming it has already be normalized to the same format and + encoding used by the client to calculate the hash on request). If the payload is not available at the time + of authentication, the authenticatePayload() method can be used by passing it the credentials and + attributes.hash returned in the authenticate callback. + + host: optional host name override. Only used when passed a node request object. + port: optional port override. Only used when passed a node request object. + } + + callback: function (err, credentials, artifacts) { } + */ + +exports.authenticate = function (req, credentialsFunc, options, callback) { + + callback = Hoek.nextTick(callback); + + // Default options + + options.nonceFunc = options.nonceFunc || function (nonce, ts, nonceCallback) { return nonceCallback(); }; // No validation + options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds + + // Application time + + var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing + + // Convert node Http request object to a request configuration object + + var request = Utils.parseRequest(req, options); + if (request instanceof Error) { + return callback(Boom.badRequest(request.message)); + } + + // Parse HTTP Authorization header + + var attributes = Utils.parseAuthorizationHeader(request.authorization); + if (attributes instanceof Error) { + return callback(attributes); + } + + // Construct artifacts container + + var artifacts = { + method: request.method, + host: request.host, + port: request.port, + resource: request.url, + ts: attributes.ts, + nonce: attributes.nonce, + hash: attributes.hash, + ext: attributes.ext, + app: attributes.app, + dlg: attributes.dlg, + mac: attributes.mac, + id: attributes.id + }; + + // Verify required header attributes + + if (!attributes.id || + !attributes.ts || + !attributes.nonce || + !attributes.mac) { + + return callback(Boom.badRequest('Missing attributes'), null, artifacts); + } + + // Fetch Hawk credentials + + credentialsFunc(attributes.id, function (err, credentials) { + + if (err) { + return callback(err, credentials || null, artifacts); + } + + if (!credentials) { + return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, artifacts); + } + + if (!credentials.key || + !credentials.algorithm) { + + return callback(Boom.internal('Invalid credentials'), credentials, artifacts); + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return callback(Boom.internal('Unknown algorithm'), credentials, artifacts); + } + + // Calculate MAC + + var mac = Crypto.calculateMac('header', credentials, artifacts); + if (!Cryptiles.fixedTimeComparison(mac, attributes.mac)) { + return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, artifacts); + } + + // Check payload hash + + if (options.payload || + options.payload === '') { + + if (!attributes.hash) { + return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts); + } + + var hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.contentType); + if (!Cryptiles.fixedTimeComparison(hash, attributes.hash)) { + return callback(Boom.unauthorized('Bad payload hash', 'Hawk'), credentials, artifacts); + } + } + + // Check nonce + + options.nonceFunc(attributes.nonce, attributes.ts, function (err) { + + if (err) { + return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials, artifacts); + } + + // Check timestamp staleness + + if (Math.abs((attributes.ts * 1000) - now) > (options.timestampSkewSec * 1000)) { + var tsm = Crypto.timestampMessage(credentials, options.localtimeOffsetMsec); + return callback(Boom.unauthorized('Stale timestamp', 'Hawk', tsm), credentials, artifacts); + } + + // Successful authentication + + return callback(null, credentials, artifacts); + }); + }); +}; + + +// Authenticate payload hash - used when payload cannot be provided during authenticate() + +/* + payload: raw request payload + credentials: from authenticate callback + artifacts: from authenticate callback + contentType: req.headers['content-type'] +*/ + +exports.authenticatePayload = function (payload, credentials, artifacts, contentType) { + + var calculatedHash = Crypto.calculatePayloadHash(payload, credentials.algorithm, contentType); + return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash); +}; + + +// Authenticate payload hash - used when payload cannot be provided during authenticate() + +/* + calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash() + artifacts: from authenticate callback +*/ + +exports.authenticatePayloadHash = function (calculatedHash, artifacts) { + + return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash); +}; + + +// Generate a Server-Authorization header for a given response + +/* + credentials: {}, // Object received from authenticate() + artifacts: {} // Object received from authenticate(); 'mac', 'hash', and 'ext' - ignored + options: { + ext: 'application-specific', // Application specific data sent via the ext attribute + payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) + contentType: 'application/json', // Payload content-type (ignored if hash provided) + hash: 'U4MKKSmiVxk37JCCrAVIjV=' // Pre-calculated payload hash + } +*/ + +exports.header = function (credentials, artifacts, options) { + + // Prepare inputs + + options = options || {}; + + if (!artifacts || + typeof artifacts !== 'object' || + typeof options !== 'object') { + + return ''; + } + + artifacts = Hoek.clone(artifacts); + delete artifacts.mac; + artifacts.hash = options.hash; + artifacts.ext = options.ext; + + // Validate credentials + + if (!credentials || + !credentials.key || + !credentials.algorithm) { + + // Invalid credential object + return ''; + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return ''; + } + + // Calculate payload hash + + if (!artifacts.hash && + (options.payload || options.payload === '')) { + + artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + } + + var mac = Crypto.calculateMac('response', credentials, artifacts); + + // Construct header + + var header = 'Hawk mac="' + mac + '"' + + (artifacts.hash ? ', hash="' + artifacts.hash + '"' : ''); + + if (artifacts.ext !== null && + artifacts.ext !== undefined && + artifacts.ext !== '') { // Other falsey values allowed + + header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"'; + } + + return header; +}; + + +/* + * Arguments and options are the same as authenticate() with the exception that the only supported options are: + * 'hostHeaderName', 'localtimeOffsetMsec', 'host', 'port' + */ + +exports.authenticateBewit = function (req, credentialsFunc, options, callback) { + + callback = Hoek.nextTick(callback); + + // Application time + + var now = Utils.now(options.localtimeOffsetMsec); + + // Convert node Http request object to a request configuration object + + var request = Utils.parseRequest(req, options); + if (request instanceof Error) { + return callback(Boom.badRequest(request.message)); + } + + // Extract bewit + + // 1 2 3 4 + var resource = request.url.match(/^(\/.*)([\?&])bewit\=([^&$]*)(?:&(.+))?$/); + if (!resource) { + return callback(Boom.unauthorized(null, 'Hawk')); + } + + // Bewit not empty + + if (!resource[3]) { + return callback(Boom.unauthorized('Empty bewit', 'Hawk')); + } + + // Verify method is GET + + if (request.method !== 'GET' && + request.method !== 'HEAD') { + + return callback(Boom.unauthorized('Invalid method', 'Hawk')); + } + + // No other authentication + + if (request.authorization) { + return callback(Boom.badRequest('Multiple authentications')); + } + + // Parse bewit + + var bewitString = Hoek.base64urlDecode(resource[3]); + if (bewitString instanceof Error) { + return callback(Boom.badRequest('Invalid bewit encoding')); + } + + // Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character) + + var bewitParts = bewitString.split('\\'); + if (bewitParts.length !== 4) { + return callback(Boom.badRequest('Invalid bewit structure')); + } + + var bewit = { + id: bewitParts[0], + exp: parseInt(bewitParts[1], 10), + mac: bewitParts[2], + ext: bewitParts[3] || '' + }; + + if (!bewit.id || + !bewit.exp || + !bewit.mac) { + + return callback(Boom.badRequest('Missing bewit attributes')); + } + + // Construct URL without bewit + + var url = resource[1]; + if (resource[4]) { + url += resource[2] + resource[4]; + } + + // Check expiration + + if (bewit.exp * 1000 <= now) { + return callback(Boom.unauthorized('Access expired', 'Hawk'), null, bewit); + } + + // Fetch Hawk credentials + + credentialsFunc(bewit.id, function (err, credentials) { + + if (err) { + return callback(err, credentials || null, bewit.ext); + } + + if (!credentials) { + return callback(Boom.unauthorized('Unknown credentials', 'Hawk'), null, bewit); + } + + if (!credentials.key || + !credentials.algorithm) { + + return callback(Boom.internal('Invalid credentials'), credentials, bewit); + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return callback(Boom.internal('Unknown algorithm'), credentials, bewit); + } + + // Calculate MAC + + var mac = Crypto.calculateMac('bewit', credentials, { + ts: bewit.exp, + nonce: '', + method: 'GET', + resource: url, + host: request.host, + port: request.port, + ext: bewit.ext + }); + + if (!Cryptiles.fixedTimeComparison(mac, bewit.mac)) { + return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials, bewit); + } + + // Successful authentication + + return callback(null, credentials, bewit); + }); +}; + + +/* + * options are the same as authenticate() with the exception that the only supported options are: + * 'nonceFunc', 'timestampSkewSec', 'localtimeOffsetMsec' + */ + +exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) { + + callback = Hoek.nextTick(callback); + + // Default options + + options.nonceFunc = options.nonceFunc || function (nonce, ts, nonceCallback) { return nonceCallback(); }; // No validation + options.timestampSkewSec = options.timestampSkewSec || 60; // 60 seconds + + // Application time + + var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing + + // Validate authorization + + if (!authorization.id || + !authorization.ts || + !authorization.nonce || + !authorization.hash || + !authorization.mac) { + + return callback(Boom.badRequest('Invalid authorization')) + } + + // Fetch Hawk credentials + + credentialsFunc(authorization.id, function (err, credentials) { + + if (err) { + return callback(err, credentials || null); + } + + if (!credentials) { + return callback(Boom.unauthorized('Unknown credentials', 'Hawk')); + } + + if (!credentials.key || + !credentials.algorithm) { + + return callback(Boom.internal('Invalid credentials'), credentials); + } + + if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return callback(Boom.internal('Unknown algorithm'), credentials); + } + + // Construct artifacts container + + var artifacts = { + ts: authorization.ts, + nonce: authorization.nonce, + host: host, + port: port, + hash: authorization.hash + }; + + // Calculate MAC + + var mac = Crypto.calculateMac('message', credentials, artifacts); + if (!Cryptiles.fixedTimeComparison(mac, authorization.mac)) { + return callback(Boom.unauthorized('Bad mac', 'Hawk'), credentials); + } + + // Check payload hash + + var hash = Crypto.calculatePayloadHash(message, credentials.algorithm); + if (!Cryptiles.fixedTimeComparison(hash, authorization.hash)) { + return callback(Boom.unauthorized('Bad message hash', 'Hawk'), credentials); + } + + // Check nonce + + options.nonceFunc(authorization.nonce, authorization.ts, function (err) { + + if (err) { + return callback(Boom.unauthorized('Invalid nonce', 'Hawk'), credentials); + } + + // Check timestamp staleness + + if (Math.abs((authorization.ts * 1000) - now) > (options.timestampSkewSec * 1000)) { + return callback(Boom.unauthorized('Stale timestamp'), credentials); + } + + // Successful authentication + + return callback(null, credentials); + }); + }); +}; diff --git a/node_modules/hawk/lib/utils.js b/node_modules/hawk/lib/utils.js new file mode 100755 index 000000000..de74606f3 --- /dev/null +++ b/node_modules/hawk/lib/utils.js @@ -0,0 +1,164 @@ +// Load modules + +var Sntp = require('sntp'); +var Boom = require('boom'); + + +// Declare internals + +var internals = {}; + + +exports.version = function () { + + return require('../package.json').version; +}; + + +// Extract host and port from request + +// $1 $2 +internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6) + + +exports.parseHost = function (req, hostHeaderName) { + + hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host'); + var hostHeader = req.headers[hostHeaderName]; + if (!hostHeader) { + return null; + } + + var hostParts = hostHeader.match(internals.hostHeaderRegex); + if (!hostParts) { + return null; + } + + return { + name: hostParts[1], + port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80)) + }; +}; + + +// Parse Content-Type header content + +exports.parseContentType = function (header) { + + if (!header) { + return ''; + } + + return header.split(';')[0].trim().toLowerCase(); +}; + + +// Convert node's to request configuration object + +exports.parseRequest = function (req, options) { + + if (!req.headers) { + return req; + } + + // Obtain host and port information + + if (!options.host || !options.port) { + var host = exports.parseHost(req, options.hostHeaderName); + if (!host) { + return new Error('Invalid Host header'); + } + } + + var request = { + method: req.method, + url: req.url, + host: options.host || host.name, + port: options.port || host.port, + authorization: req.headers.authorization, + contentType: req.headers['content-type'] || '' + }; + + return request; +}; + + +exports.now = function (localtimeOffsetMsec) { + + return Sntp.now() + (localtimeOffsetMsec || 0); +}; + + +exports.nowSecs = function (localtimeOffsetMsec) { + + return Math.floor(exports.now(localtimeOffsetMsec) / 1000); +}; + + +// Parse Hawk HTTP Authorization header + +exports.parseAuthorizationHeader = function (header, keys) { + + keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg']; + + if (!header) { + return Boom.unauthorized(null, 'Hawk'); + } + + var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something] + if (!headerParts) { + return Boom.badRequest('Invalid header syntax'); + } + + var scheme = headerParts[1]; + if (scheme.toLowerCase() !== 'hawk') { + return Boom.unauthorized(null, 'Hawk'); + } + + var attributesString = headerParts[2]; + if (!attributesString) { + return Boom.badRequest('Invalid header syntax'); + } + + var attributes = {}; + var errorMessage = ''; + var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) { + + // Check valid attribute names + + if (keys.indexOf($1) === -1) { + errorMessage = 'Unknown attribute: ' + $1; + return; + } + + // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9 + + if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) { + errorMessage = 'Bad attribute value: ' + $1; + return; + } + + // Check for duplicates + + if (attributes.hasOwnProperty($1)) { + errorMessage = 'Duplicate attribute: ' + $1; + return; + } + + attributes[$1] = $2; + return ''; + }); + + if (verify !== '') { + return Boom.badRequest(errorMessage || 'Bad header format'); + } + + return attributes; +}; + + +exports.unauthorized = function (message) { + + return Boom.unauthorized(message, 'Hawk'); +}; + diff --git a/node_modules/hawk/package.json b/node_modules/hawk/package.json new file mode 100644 index 000000000..d542c3e6d --- /dev/null +++ b/node_modules/hawk/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "hawk@~2.3.0", + "/Users/rebecca/code/npm/node_modules/request" + ] + ], + "_from": "hawk@>=2.3.0 <2.4.0", + "_id": "hawk@2.3.1", + "_inCache": true, + "_location": "/hawk", + "_npmUser": { + "email": "eran@hueniverse.com", + "name": "hueniverse" + }, + "_npmVersion": "1.4.28", + "_phantomChildren": {}, + "_requested": { + "name": "hawk", + "raw": "hawk@~2.3.0", + "rawSpec": "~2.3.0", + "scope": null, + "spec": ">=2.3.0 <2.4.0", + "type": "range" + }, + "_requiredBy": [ + "/request" + ], + "_resolved": "https://registry.npmjs.org/hawk/-/hawk-2.3.1.tgz", + "_shasum": "1e731ce39447fa1d0f6d707f7bceebec0fd1ec1f", + "_shrinkwrap": null, + "_spec": "hawk@~2.3.0", + "_where": "/Users/rebecca/code/npm/node_modules/request", + "author": { + "email": "eran@hammer.io", + "name": "Eran Hammer", + "url": "http://hueniverse.com" + }, + "browser": "./lib/browser.js", + "bugs": { + "url": "https://github.com/hueniverse/hawk/issues" + }, + "contributors": [], + "dependencies": { + "boom": "2.x.x", + "cryptiles": "2.x.x", + "hoek": "2.x.x", + "sntp": "1.x.x" + }, + "description": "HTTP Hawk Authentication Scheme", + "devDependencies": { + "code": "1.x.x", + "lab": "5.x.x" + }, + "directories": {}, + "dist": { + "shasum": "1e731ce39447fa1d0f6d707f7bceebec0fd1ec1f", + "tarball": "http://registry.npmjs.org/hawk/-/hawk-2.3.1.tgz" + }, + "engines": { + "node": ">=0.8.0" + }, + "gitHead": "492632da51ecedd5f59ce96f081860ad24ce6532", + "homepage": "https://github.com/hueniverse/hawk", + "keywords": [ + "authentication", + "hawk", + "http", + "scheme" + ], + "licenses": [ + { + "type": "BSD", + "url": "http://github.com/hueniverse/hawk/raw/master/LICENSE" + } + ], + "main": "index", + "maintainers": [ + { + "name": "hueniverse", + "email": "eran@hueniverse.com" + } + ], + "name": "hawk", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/hueniverse/hawk" + }, + "scripts": { + "test": "make test-cov" + }, + "version": "2.3.1" +} diff --git a/node_modules/hawk/test/browser.js b/node_modules/hawk/test/browser.js new file mode 100755 index 000000000..a45241389 --- /dev/null +++ b/node_modules/hawk/test/browser.js @@ -0,0 +1,1453 @@ +// Load modules + +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Hoek = require('hoek'); +var Lab = require('lab'); +var Browser = require('../lib/browser'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Browser', function () { + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: id, + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: (id === '1' ? 'sha1' : 'sha256'), + user: 'steve' + }; + + return callback(null, credentials); + }; + + it('should generate a bewit then successfully authenticate it', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2', + host: 'example.com', + port: 80 + }; + + credentialsFunc('123456', function (err, credentials) { + + var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' }); + req.url += '&bewit=' + bewit; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(attributes.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('should generate a bewit then successfully authenticate it (no ext)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2', + host: 'example.com', + port: 80 + }; + + credentialsFunc('123456', function (err, credentials) { + + var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100 }); + req.url += '&bewit=' + bewit; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + }); + + describe('#bewit', function () { + + it('returns a valid bewit value', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6'); + done(); + }); + + it('returns a valid bewit value (explicit HTTP port)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('http://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6'); + done(); + }); + + it('returns a valid bewit value (explicit HTTPS port)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com:8043/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcL2t4UjhwK0xSaTdvQTRnUXc3cWlxa3BiVHRKYkR4OEtRMC9HRUwvVytTUT1ceGFuZHlhbmR6'); + done(); + }); + + it('returns a valid bewit value (null ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c'); + done(); + }); + + it('errors on invalid options', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', 4); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + var credentials = { + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing credentials', function (done) { + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid credentials (key)', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha256' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid algorithm', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing options', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow'); + expect(bewit).to.equal(''); + done(); + }); + }); + + it('generates a header then successfully parse it (configuration)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (node request)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(res.headers['server-authorization']).to.exist(); + + expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (browserify)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + }, + getHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(res.headers['server-authorization']).to.exist(); + + expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (time offset)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', localtimeOffsetMsec: 100000 }).field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (no server header options)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); + expect(res.headers['server-authorization']).to.exist(); + + expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (no server header)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + }); + }); + + it('generates a header with stale ts and successfully authenticate on second call', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + Browser.utils.setNtpOffset(60 * 60 * 1000); + var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }); + req.authorization = header.field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Stale timestamp'); + + var res = { + headers: { + 'www-authenticate': err.output.headers['WWW-Authenticate'] + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000); + expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true); + expect(Browser.utils.getNtpOffset()).to.equal(0); + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + }); + + it('generates a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + var localStorage = new Browser.internals.LocalStorage(); + + Browser.utils.setStorage(localStorage) + + Browser.utils.setNtpOffset(60 * 60 * 1000); + var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }); + req.authorization = header.field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Stale timestamp'); + + var res = { + headers: { + 'www-authenticate': err.output.headers['WWW-Authenticate'] + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000); + expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000); + expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true); + expect(Browser.utils.getNtpOffset()).to.equal(0); + expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(0); + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + }); + + it('generates a header then fails to parse it (missing server header hash)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); + expect(res.headers['server-authorization']).to.exist(); + + expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(false); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (with hash)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it then validate payload', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true(); + expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false(); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (app)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(artifacts.app).to.equal('asd23ased'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (app, dlg)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(artifacts.app).to.equal('asd23ased'); + expect(artifacts.dlg).to.equal('23434szr3q4d'); + done(); + }); + }); + }); + + it('generates a header then fail authentication due to bad hash', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad payload hash'); + done(); + }); + }); + }); + + it('generates a header for one resource then fail to authenticate another', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; + req.url = '/something/else'; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(credentials).to.exist(); + done(); + }); + }); + }); + + describe('client', function () { + + describe('#header', function () { + + it('returns a valid authorization header (sha1)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="'); + done(); + }); + + it('returns a valid authorization header (sha256)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="'); + done(); + }); + + it('returns a valid authorization header (empty payload)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: '' }).field; + expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"404ghL7K+hfyhByKKejFBRGgTjU=\", ext=\"Bazinga!\", mac=\"Bh1sj1DOfFRWOdi3ww52nLCJdBE=\"'); + done(); + }); + + it('returns a valid authorization header (no ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('returns a valid authorization header (null ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('returns a valid authorization header (uri object)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var uri = Browser.utils.parseUri('https://example.net/somewhere/over/the/rainbow'); + var header = Browser.client.header(uri, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('errors on missing options', function (done) { + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST'); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on empty uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on invalid uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header(4, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on missing method', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', '', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on invalid method', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 5, { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on missing credentials', function (done) { + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credentials object'); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + var credentials = { + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credentials object'); + done(); + }); + + it('errors on invalid credentials (key)', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha256' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credentials object'); + done(); + }); + + it('errors on invalid algorithm', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Unknown algorithm'); + done(); + }); + + it('uses a pre-calculated payload hash', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var options = { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }; + options.hash = Browser.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="'); + done(); + }); + }); + + describe('#authenticate', function () { + + it('skips tsm validation when missing ts', function (done) { + + var res = { + headers: { + 'www-authenticate': 'Hawk error="Stale timestamp"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + ts: 1402135580, + nonce: 'iBRB6t', + method: 'GET', + resource: '/resource/4?filter=a', + host: 'example.com', + port: '8080', + ext: 'some-app-data' + }; + + expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + + it('returns false on invalid header', function (done) { + + var res = { + headers: { + 'server-authorization': 'Hawk mac="abc", bad="xyz"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(Browser.client.authenticate(res, {})).to.equal(false); + done(); + }); + + it('returns false on invalid mac', function (done) { + + var res = { + headers: { + 'content-type': 'text/plain', + 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1362336900', + nonce: 'eb5S_L', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + app: undefined, + dlg: undefined, + mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', + id: '123456' + }; + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(false); + done(); + }); + + it('returns true on ignoring hash', function (done) { + + var res = { + headers: { + 'content-type': 'text/plain', + 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1362336900', + nonce: 'eb5S_L', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + app: undefined, + dlg: undefined, + mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', + id: '123456' + }; + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + + it('errors on invalid WWW-Authenticate header format', function (done) { + + var res = { + headers: { + 'www-authenticate': 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(Browser.client.authenticate(res, {})).to.equal(false); + done(); + }); + + it('errors on invalid WWW-Authenticate header format', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var res = { + headers: { + 'www-authenticate': 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"' + }, + getResponseHeader: function (header) { + + return res.headers[header.toLowerCase()]; + } + }; + + expect(Browser.client.authenticate(res, credentials)).to.equal(false); + done(); + }); + }); + + describe('#message', function () { + + it('generates an authorization then successfully parse it', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + }); + + it('generates an authorization using custom nonce/timestamp', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials, nonce: 'abc123', timestamp: 1398536270957 }); + expect(auth).to.exist(); + expect(auth.nonce).to.equal('abc123'); + expect(auth.ts).to.equal(1398536270957); + done(); + }); + }); + + it('errors on missing host', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message(null, 8080, 'some message', { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on invalid host', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message(5, 8080, 'some message', { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on missing port', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 0, 'some message', { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on invalid port', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 'a', 'some message', { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on missing message', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 8080, undefined, { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on null message', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 8080, null, { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on invalid message', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Browser.client.message('example.com', 8080, 5, { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on missing credentials', function (done) { + + var auth = Browser.client.message('example.com', 8080, 'some message', {}); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on missing options', function (done) { + + var auth = Browser.client.message('example.com', 8080, 'some message'); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var creds = Hoek.clone(credentials); + delete creds.id; + var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on invalid credentials (key)', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var creds = Hoek.clone(credentials); + delete creds.key; + var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('errors on invalid algorithm', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var creds = Hoek.clone(credentials); + creds.algorithm = 'blah'; + var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds }); + expect(auth).to.not.exist(); + done(); + }); + }); + }); + + describe('#authenticateTimestamp', function (done) { + + it('validates a timestamp', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var tsm = Hawk.crypto.timestampMessage(credentials); + expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(true); + done(); + }); + }); + + it('validates a timestamp without updating local time', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var offset = Browser.utils.getNtpOffset(); + var tsm = Hawk.crypto.timestampMessage(credentials, 10000); + expect(Browser.client.authenticateTimestamp(tsm, credentials, false)).to.equal(true); + expect(offset).to.equal(Browser.utils.getNtpOffset()); + done(); + }); + }); + + it('detects a bad timestamp', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var tsm = Hawk.crypto.timestampMessage(credentials); + tsm.ts = 4; + expect(Browser.client.authenticateTimestamp(tsm, credentials)).to.equal(false); + done(); + }); + }); + }); + }); + + describe('internals', function () { + + describe('LocalStorage', function () { + + it('goes through the full lifecycle', function (done) { + + var storage = new Browser.internals.LocalStorage(); + expect(storage.length).to.equal(0); + expect(storage.getItem('a')).to.equal(null); + storage.setItem('a', 5); + expect(storage.length).to.equal(1); + expect(storage.key()).to.equal('a'); + expect(storage.key(0)).to.equal('a'); + expect(storage.getItem('a')).to.equal('5'); + storage.setItem('b', 'test'); + expect(storage.key()).to.equal('a'); + expect(storage.key(0)).to.equal('a'); + expect(storage.key(1)).to.equal('b'); + expect(storage.length).to.equal(2); + expect(storage.getItem('b')).to.equal('test'); + storage.removeItem('a'); + expect(storage.length).to.equal(1); + expect(storage.getItem('a')).to.equal(null); + expect(storage.getItem('b')).to.equal('test'); + storage.clear(); + expect(storage.length).to.equal(0); + expect(storage.getItem('a')).to.equal(null); + expect(storage.getItem('b')).to.equal(null); + done(); + }); + }); + }); + + describe('utils', function () { + + describe('#setStorage', function () { + + it('sets storage for the first time', function (done) { + + Browser.utils.storage = new Browser.internals.LocalStorage(); // Reset state + + expect(Browser.utils.storage.getItem('hawk_ntp_offset')).to.not.exist(); + Browser.utils.storage.setItem('test', '1'); + Browser.utils.setStorage(new Browser.internals.LocalStorage()); + expect(Browser.utils.storage.getItem('test')).to.not.exist(); + Browser.utils.storage.setItem('test', '2'); + expect(Browser.utils.storage.getItem('test')).to.equal('2'); + done(); + }); + }); + + describe('#setNtpOffset', function (done) { + + it('catches localStorage errors', function (done) { + + var orig = Browser.utils.storage.setItem; + var error = console.error; + var count = 0; + console.error = function () { if (count++ === 2) { console.error = error; } }; + Browser.utils.storage.setItem = function () { + + Browser.utils.storage.setItem = orig; + throw new Error() + }; + + expect(function () { + Browser.utils.setNtpOffset(100); + }).not.to.throw(); + + done(); + }); + }); + + describe('#parseAuthorizationHeader', function (done) { + + it('returns null on missing header', function (done) { + + expect(Browser.utils.parseAuthorizationHeader()).to.equal(null); + done(); + }); + + it('returns null on bad header syntax (structure)', function (done) { + + expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null); + done(); + }); + + it('returns null on bad header syntax (parts)', function (done) { + + expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null); + done(); + }); + + it('returns null on bad scheme name', function (done) { + + expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null); + done(); + }); + + it('returns null on bad attribute value', function (done) { + + expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null); + done(); + }); + + it('returns null on duplicated attribute', function (done) { + + expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null); + done(); + }); + }); + + describe('#parseUri', function () { + + it('returns empty port when unknown scheme', function (done) { + + var uri = Browser.utils.parseUri('ftp://domain'); + expect(uri.port).to.equal(''); + done(); + }); + + it('returns default port when missing', function (done) { + + var uri = Browser.utils.parseUri('http://'); + expect(uri.port).to.equal('80'); + done(); + }); + }); + + var str = "https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=url"; + var base64str = "aHR0cHM6Ly93d3cuZ29vZ2xlLmNhL3dlYmhwP3NvdXJjZWlkPWNocm9tZS1pbnN0YW50Jmlvbj0xJmVzcHY9MiZpZT1VVEYtOCNxPXVybA"; + + describe('#base64urlEncode', function () { + + it('should base64 URL-safe decode a string', function (done) { + + expect(Browser.utils.base64urlEncode(str)).to.equal(base64str); + done(); + }); + + }); + + }); +}); diff --git a/node_modules/hawk/test/client.js b/node_modules/hawk/test/client.js new file mode 100755 index 000000000..5983897b2 --- /dev/null +++ b/node_modules/hawk/test/client.js @@ -0,0 +1,443 @@ +// Load modules + +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('client', function () { + + describe('#header', function () { + + it('returns a valid authorization header (sha1)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var header = Hawk.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="'); + done(); + }); + + it('returns a valid authorization header (sha256)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="'); + done(); + }); + + it('returns a valid authorization header (no ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('returns a valid authorization header (null ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('returns a valid authorization header (empty payload)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: '', contentType: 'text/plain' }).field; + expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", mac=\"U5k16YEzn3UnBHKeBzsDXn067Gu3R4YaY6xOt9PYRZM=\"'); + done(); + }); + + it('returns a valid authorization header (pre hashed payload)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var options = { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }; + options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field; + expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="'); + done(); + }); + + it('errors on missing uri', function (done) { + + var header = Hawk.client.header('', 'POST'); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on invalid uri', function (done) { + + var header = Hawk.client.header(4, 'POST'); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on missing method', function (done) { + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', ''); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on invalid method', function (done) { + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 5); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on missing options', function (done) { + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST'); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid argument type'); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + var credentials = { + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credential object'); + done(); + }); + + it('errors on missing credentials', function (done) { + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credential object'); + done(); + }); + + it('errors on invalid credentials', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha256' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Invalid credential object'); + done(); + }); + + it('errors on invalid algorithm', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 }); + expect(header.field).to.equal(''); + expect(header.err).to.equal('Unknown algorithm'); + done(); + }); + }); + + describe('#authenticate', function () { + + it('returns false on invalid header', function (done) { + + var res = { + headers: { + 'server-authorization': 'Hawk mac="abc", bad="xyz"' + } + }; + + expect(Hawk.client.authenticate(res, {})).to.equal(false); + done(); + }); + + it('returns false on invalid mac', function (done) { + + var res = { + headers: { + 'content-type': 'text/plain', + 'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' + } + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1362336900', + nonce: 'eb5S_L', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + app: undefined, + dlg: undefined, + mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', + id: '123456' + }; + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(false); + done(); + }); + + it('returns true on ignoring hash', function (done) { + + var res = { + headers: { + 'content-type': 'text/plain', + 'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"' + } + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1362336900', + nonce: 'eb5S_L', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + app: undefined, + dlg: undefined, + mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=', + id: '123456' + }; + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + + it('fails on invalid WWW-Authenticate header format', function (done) { + + var header = 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"'; + expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(false); + done(); + }); + + it('fails on invalid WWW-Authenticate header format', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var header = 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"'; + expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, credentials)).to.equal(false); + done(); + }); + + it('skips tsm validation when missing ts', function (done) { + + var header = 'Hawk error="Stale timestamp"'; + expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(true); + done(); + }); + }); + + describe('#message', function () { + + it('generates authorization', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.exist(); + expect(auth.ts).to.equal(1353809207); + expect(auth.nonce).to.equal('abc123'); + done(); + }); + + it('errors on invalid host', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message(5, 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on invalid port', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', '80', 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on missing host', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 0, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on null message', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, null, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on missing message', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, undefined, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on invalid message', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, 5, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on missing options', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, 'I am the boodyman'); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + var credentials = { + key: '2983d45yun89q', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + + it('errors on invalid credentials (key)', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha1' + }; + + var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' }); + expect(auth).to.not.exist(); + done(); + }); + }); + }); +}); diff --git a/node_modules/hawk/test/crypto.js b/node_modules/hawk/test/crypto.js new file mode 100755 index 000000000..f2d3d4580 --- /dev/null +++ b/node_modules/hawk/test/crypto.js @@ -0,0 +1,86 @@ +// Load modules + +var Code = require('code'); +var Hawk = require('../lib'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('Crypto', function () { + + describe('#generateNormalizedString', function () { + + it('should return a valid normalized string', function (done) { + + expect(Hawk.crypto.generateNormalizedString('header', { + credentials: { + key: 'dasdfasdf', + algorithm: 'sha256' + }, + ts: 1357747017, + nonce: 'k3k4j5', + method: 'GET', + resource: '/resource/something', + host: 'example.com', + port: 8080 + })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\n\n'); + + done(); + }); + + it('should return a valid normalized string (ext)', function (done) { + + expect(Hawk.crypto.generateNormalizedString('header', { + credentials: { + key: 'dasdfasdf', + algorithm: 'sha256' + }, + ts: 1357747017, + nonce: 'k3k4j5', + method: 'GET', + resource: '/resource/something', + host: 'example.com', + port: 8080, + ext: 'this is some app data' + })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\n\nthis is some app data\n'); + + done(); + }); + + it('should return a valid normalized string (payload + ext)', function (done) { + + expect(Hawk.crypto.generateNormalizedString('header', { + credentials: { + key: 'dasdfasdf', + algorithm: 'sha256' + }, + ts: 1357747017, + nonce: 'k3k4j5', + method: 'GET', + resource: '/resource/something', + host: 'example.com', + port: 8080, + hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=', + ext: 'this is some app data' + })).to.equal('hawk.1.header\n1357747017\nk3k4j5\nGET\n/resource/something\nexample.com\n8080\nU4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=\nthis is some app data\n'); + + done(); + }); + }); + }); +}); + diff --git a/node_modules/hawk/test/index.js b/node_modules/hawk/test/index.js new file mode 100755 index 000000000..39f2c5b86 --- /dev/null +++ b/node_modules/hawk/test/index.js @@ -0,0 +1,378 @@ +// Load modules + +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: id, + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: (id === '1' ? 'sha1' : 'sha256'), + user: 'steve' + }; + + return callback(null, credentials); + }; + + it('generates a header then successfully parse it (configuration)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials, ext: 'some-app-data' }).field; + expect(req.authorization).to.exist(); + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (node request)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(res.headers['server-authorization']).to.exist(); + + expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (absolute request uri)', function (done) { + + var req = { + method: 'POST', + url: 'http://example.com:8080/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(res.headers['server-authorization']).to.exist(); + + expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (no server header options)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); + expect(res.headers['server-authorization']).to.exist(); + + expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + }); + }); + + it('generates a header then fails to parse it (missing server header hash)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:8080', + 'content-type': 'text/plain;x=y' + } + }; + + var payload = 'some not so random text'; + + credentialsFunc('123456', function (err, credentials) { + + var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); + req.headers.authorization = reqHeader.field; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true); + + var res = { + headers: { + 'content-type': 'text/plain' + } + }; + + res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts); + expect(res.headers['server-authorization']).to.exist(); + + expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(false); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (with hash)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it then validate payload', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true(); + expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false(); + done(); + }); + }); + }); + + it('generates a header then successfully parses and validates payload', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (app)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(artifacts.app).to.equal('asd23ased'); + done(); + }); + }); + }); + + it('generates a header then successfully parse it (app, dlg)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(artifacts.ext).to.equal('some-app-data'); + expect(artifacts.app).to.equal('asd23ased'); + expect(artifacts.dlg).to.equal('23434szr3q4d'); + done(); + }); + }); + }); + + it('generates a header then fail authentication due to bad hash', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field; + Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad payload hash'); + done(); + }); + }); + }); + + it('generates a header for one resource then fail to authenticate another', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + credentialsFunc('123456', function (err, credentials) { + + req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field; + req.url = '/something/else'; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(credentials).to.exist(); + done(); + }); + }); + }); +}); diff --git a/node_modules/hawk/test/message.js b/node_modules/hawk/test/message.js new file mode 100755 index 000000000..b0494cc45 --- /dev/null +++ b/node_modules/hawk/test/message.js @@ -0,0 +1,261 @@ +// Load modules + +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Hoek = require('hoek'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: id, + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: (id === '1' ? 'sha1' : 'sha256'), + user: 'steve' + }; + + return callback(null, credentials); + }; + + it('should generate an authorization then successfully parse it', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + }); + + it('should fail authorization on mismatching host', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Bad mac'); + done(); + }); + }); + }); + + it('should fail authorization on stale timestamp', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Stale timestamp'); + done(); + }); + }); + }); + + it('overrides timestampSkewSec', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials, localtimeOffsetMsec: 100000 }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials) { + + expect(err).to.not.exist(); + done(); + }); + }); + }); + + it('should fail authorization on invalid authorization', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + delete auth.id; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid authorization'); + done(); + }); + }); + }); + + it('should fail authorization on bad hash', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Bad message hash'); + done(); + }); + }); + }); + + it('should fail authorization on nonce error', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { nonceFunc: function (nonce, ts, callback) { callback (new Error('kaboom')); } }, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid nonce'); + done(); + }); + }); + }); + + it('should fail authorization on credentials error', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + var errFunc = function (id, callback) { + + callback(new Error('kablooey')); + }; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('kablooey'); + done(); + }); + }); + }); + + it('should fail authorization on missing credentials', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + var errFunc = function (id, callback) { + + callback(); + }; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown credentials'); + done(); + }); + }); + }); + + it('should fail authorization on invalid credentials', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + var errFunc = function (id, callback) { + + callback(null, {}); + }; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid credentials'); + done(); + }); + }); + }); + + it('should fail authorization on invalid credentials algorithm', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + expect(auth).to.exist(); + + var errFunc = function (id, callback) { + + callback(null, { key: '123', algorithm: '456' }); + }; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown algorithm'); + done(); + }); + }); + }); + + it('should fail on missing host', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials }); + expect(auth).to.not.exist(); + done(); + }); + }); + + it('should fail on missing credentials', function (done) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', {}); + expect(auth).to.not.exist(); + done(); + }); + + it('should fail on invalid algorithm', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var creds = Hoek.clone(credentials); + creds.algorithm = 'blah'; + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds }); + expect(auth).to.not.exist(); + done(); + }); + }); +}); diff --git a/node_modules/hawk/test/readme.js b/node_modules/hawk/test/readme.js new file mode 100755 index 000000000..60af19983 --- /dev/null +++ b/node_modules/hawk/test/readme.js @@ -0,0 +1,98 @@ +// Load modules + +var Code = require('code'); +var Hawk = require('../lib'); +var Hoek = require('hoek'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('README', function () { + + describe('core', function () { + + var credentials = { + id: 'dh37fgj492je', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256' + }; + + var options = { + credentials: credentials, + timestamp: 1353832234, + nonce: 'j4h3g2', + ext: 'some-app-ext-data' + }; + + it('should generate a header protocol example', function (done) { + + var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'GET', options).field; + + expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", ext="some-app-ext-data", mac="6R4rV5iE+NPoym+WwjeHzjAGXUtLNIxmo1vpMofpLAE="'); + done(); + }); + + it('should generate a normalized string protocol example', function (done) { + + var normalized = Hawk.crypto.generateNormalizedString('header', { + credentials: credentials, + ts: options.timestamp, + nonce: options.nonce, + method: 'GET', + resource: '/resource?a=1&b=2', + host: 'example.com', + port: 8000, + ext: options.ext + }); + + expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nGET\n/resource?a=1&b=2\nexample.com\n8000\n\nsome-app-ext-data\n'); + done(); + }); + + var payloadOptions = Hoek.clone(options); + payloadOptions.payload = 'Thank you for flying Hawk'; + payloadOptions.contentType = 'text/plain'; + + it('should generate a header protocol example (with payload)', function (done) { + + var header = Hawk.client.header('http://example.com:8000/resource/1?b=1&a=2', 'POST', payloadOptions).field; + + expect(header).to.equal('Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", hash="Yi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=", ext="some-app-ext-data", mac="aSe1DERmZuRl3pI36/9BdZmnErTw3sNzOOAUlfeKjVw="'); + done(); + }); + + it('should generate a normalized string protocol example (with payload)', function (done) { + + var normalized = Hawk.crypto.generateNormalizedString('header', { + credentials: credentials, + ts: options.timestamp, + nonce: options.nonce, + method: 'POST', + resource: '/resource?a=1&b=2', + host: 'example.com', + port: 8000, + hash: Hawk.crypto.calculatePayloadHash(payloadOptions.payload, credentials.algorithm, payloadOptions.contentType), + ext: options.ext + }); + + expect(normalized).to.equal('hawk.1.header\n1353832234\nj4h3g2\nPOST\n/resource?a=1&b=2\nexample.com\n8000\nYi9LfIIFRtBEPt74PVmbTF/xVAwPn7ub15ePICfgnuY=\nsome-app-ext-data\n'); + done(); + }); + }); + }); +}); + diff --git a/node_modules/hawk/test/server.js b/node_modules/hawk/test/server.js new file mode 100755 index 000000000..00d7d085f --- /dev/null +++ b/node_modules/hawk/test/server.js @@ -0,0 +1,985 @@ +// Load modules + +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('server', function () { + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: id, + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: (id === '1' ? 'sha1' : 'sha256'), + user: 'steve' + }; + + return callback(null, credentials); + }; + + describe('#authenticate', function () { + + it('parses a valid authentication header (sha1)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + + it('parses a valid authentication header (sha256)', function (done) { + + var req = { + method: 'GET', + url: '/resource/1?b=1&a=2', + host: 'example.com', + port: 8000, + authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + + it('parses a valid authentication header (host override)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + headers: { + host: 'example1.com:8080', + authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"' + } + }; + + Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + + it('parses a valid authentication header (host port override)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + headers: { + host: 'example1.com:80', + authorization: 'Hawk id="1", ts="1353788437", nonce="k3j4h2", mac="zy79QQ5/EYFmQqutVnYb73gAc/U=", ext="hello"' + } + }; + + Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', port: 8080, localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + + it('parses a valid authentication header (POST with payload)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123456", ts="1357926341", nonce="1AwuJD", hash="qAiXIVv+yjDATneWxZP2YCTa9aHRgQdnH9b3Wc+o3dg=", ext="some-app-data", mac="UeYcj5UoTVaAWXNvJfLVia7kU3VabxCqrccXP8sUGC4="' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1357926341000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + + it('errors on missing hash', function (done) { + + var req = { + method: 'GET', + url: '/resource/1?b=1&a=2', + host: 'example.com', + port: 8000, + authorization: 'Hawk id="dh37fgj492je", ts="1353832234", nonce="j4h3g2", mac="m8r1rHbXN6NgO+KIIhjO7sFRyd78RNGVUwehe8Cp2dU=", ext="some-app-data"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { payload: 'body', localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing required payload hash'); + done(); + }); + }); + + it('errors on a stale timestamp', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123456", ts="1362337299", nonce="UzmxSs", ext="some-app-data", mac="wnNUxchvvryMH2RxckTdZ/gY3ijzvccx4keVvELC61w="' + }; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Stale timestamp'); + var header = err.output.headers['WWW-Authenticate']; + var ts = header.match(/^Hawk ts\=\"(\d+)\"\, tsm\=\"([^\"]+)\"\, error=\"Stale timestamp\"$/); + var now = Hawk.utils.now(); + expect(parseInt(ts[1], 10) * 1000).to.be.within(now - 1000, now + 1000); + + var res = { + headers: { + 'www-authenticate': header + } + }; + + expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true); + done(); + }); + }); + + it('errors on a replay', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="bXx7a7p1h9QYQNZ8x7QhvDQym8ACgab4m3lVSFn4DBw=", ext="hello"' + }; + + var memoryCache = {}; + var options = { + localtimeOffsetMsec: 1353788437000 - Hawk.utils.now(), + nonceFunc: function (nonce, ts, callback) { + + if (memoryCache[nonce]) { + return callback(new Error()); + } + + memoryCache[nonce] = true; + return callback(); + } + }; + + Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials, artifacts) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + + Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid nonce'); + done(); + }); + }); + }); + + it('errors on an invalid authentication header: wrong scheme', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Basic asdasdasdasd' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.not.exist(); + done(); + }); + }); + + it('errors on an invalid authentication header: no scheme', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: '!@#' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid header syntax'); + done(); + }); + }); + + it('errors on an missing authorization header', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.isMissing).to.equal(true); + done(); + }); + }); + + it('errors on an missing host header', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + headers: { + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + } + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid Host header'); + done(); + }); + }); + + it('errors on an missing authorization attribute (id)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing attributes'); + done(); + }); + }); + + it('errors on an missing authorization attribute (ts)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing attributes'); + done(); + }); + }); + + it('errors on an missing authorization attribute (nonce)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing attributes'); + done(); + }); + }); + + it('errors on an missing authorization attribute (mac)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing attributes'); + done(); + }); + }); + + it('errors on an unknown authorization attribute', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", x="3", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Unknown attribute: x'); + done(); + }); + }); + + it('errors on an bad authorization header format', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123\\", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad header format'); + done(); + }); + }); + + it('errors on an bad authorization attribute value', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="\t", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad attribute value: id'); + done(); + }); + }); + + it('errors on an empty authorization attribute value', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad attribute value: id'); + done(); + }); + }); + + it('errors on duplicated authorization attribute key', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", id="456", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Duplicate attribute: id'); + done(); + }); + }); + + it('errors on an invalid authorization header format', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk' + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid header syntax'); + done(); + }); + }); + + it('errors on an bad host header (missing host)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + headers: { + host: ':8080', + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + } + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid Host header'); + done(); + }); + }); + + it('errors on an bad host header (pad port)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + headers: { + host: 'example.com:something', + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + } + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid Host header'); + done(); + }); + }); + + it('errors on credentialsFunc error', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + return callback(new Error('Unknown user')); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown user'); + done(); + }); + }); + + it('errors on credentialsFunc error (with credentials)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + return callback(new Error('Unknown user'), { some: 'value' }); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown user'); + expect(credentials.some).to.equal('value'); + done(); + }); + }); + + it('errors on missing credentials', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + return callback(null, null); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Unknown credentials'); + done(); + }); + }); + + it('errors on invalid credentials (id)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + user: 'steve' + }; + + return callback(null, credentials); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid credentials'); + expect(err.output.payload.message).to.equal('An internal server error occurred'); + done(); + }); + }); + + it('errors on invalid credentials (key)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: '23434d3q4d5345d', + user: 'steve' + }; + + return callback(null, credentials); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid credentials'); + expect(err.output.payload.message).to.equal('An internal server error occurred'); + done(); + }); + }); + + it('errors on unknown credentials algorithm', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'hmac-sha-0', + user: 'steve' + }; + + return callback(null, credentials); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown algorithm'); + expect(err.output.payload.message).to.equal('An internal server error occurred'); + done(); + }); + }); + + it('errors on unknown bad mac', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080, + authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=", ext="hello"' + }; + + var credentialsFunc = function (id, callback) { + + var credentials = { + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + return callback(null, credentials); + }; + + Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad mac'); + done(); + }); + }); + }); + + describe('#header', function () { + + it('generates header', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"'); + done(); + }); + + it('generates header (empty payload)', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(credentials, artifacts, { payload: '', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal('Hawk mac=\"i8/kUBDx0QF+PpCtW860kkV/fa9dbwEoe/FpGUXowf0=\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", ext=\"response-specific\"'); + done(); + }); + + it('generates header (pre calculated hash)', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var options = { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }; + options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + var header = Hawk.server.header(credentials, artifacts, options); + expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"'); + done(); + }); + + it('generates header (null ext)', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: null }); + expect(header).to.equal('Hawk mac=\"6PrybJTJs20jsgBw5eilXpcytD8kUbaIKNYXL+6g0ns=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\"'); + done(); + }); + + it('errors on missing artifacts', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var header = Hawk.server.header(credentials, null, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal(''); + done(); + }); + + it('errors on invalid artifacts', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + var header = Hawk.server.header(credentials, 5, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal(''); + done(); + }); + + it('errors on missing credentials', function (done) { + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(null, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal(''); + done(); + }); + + it('errors on invalid credentials (key)', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha256', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal(''); + done(); + }); + + it('errors on invalid algorithm', function (done) { + + var credentials = { + id: '123456', + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'x', + user: 'steve' + }; + + var artifacts = { + method: 'POST', + host: 'example.com', + port: '8080', + resource: '/resource/4?filter=a', + ts: '1398546787', + nonce: 'xUwusx', + hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=', + ext: 'some-app-data', + mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=', + id: '123456' + }; + + var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); + expect(header).to.equal(''); + done(); + }); + }); + + describe('#authenticateMessage', function () { + + it('errors on invalid authorization (ts)', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + delete auth.ts; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid authorization'); + done(); + }); + }); + }); + + it('errors on invalid authorization (nonce)', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + delete auth.nonce; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid authorization'); + done(); + }); + }); + }); + + it('errors on invalid authorization (hash)', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + delete auth.hash; + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid authorization'); + done(); + }); + }); + }); + + it('errors with credentials', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials }); + + Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, function (id, callback) { callback(new Error('something'), { some: 'value' }); }, {}, function (err, credentials) { + + expect(err).to.exist(); + expect(err.message).to.equal('something'); + expect(credentials.some).to.equal('value'); + done(); + }); + }); + }); + }); + + describe('#authenticatePayloadHash', function () { + + it('checks payload hash', function (done) { + + expect(Hawk.server.authenticatePayloadHash('abcdefg', { hash: 'abcdefg' })).to.equal(true); + expect(Hawk.server.authenticatePayloadHash('1234567', { hash: 'abcdefg' })).to.equal(false); + done(); + }); + }); + }); +}); diff --git a/node_modules/hawk/test/uri.js b/node_modules/hawk/test/uri.js new file mode 100755 index 000000000..e64b0095b --- /dev/null +++ b/node_modules/hawk/test/uri.js @@ -0,0 +1,590 @@ +// Load modules + +var Http = require('http'); +var Url = require('url'); +var Code = require('code'); +var Hawk = require('../lib'); +var Hoek = require('hoek'); +var Lab = require('lab'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('Uri', function () { + + var credentialsFunc = function (id, callback) { + + var credentials = { + id: id, + key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', + algorithm: 'sha256', + user: 'steve' + }; + + return callback(null, credentials); + }; + + it('should generate a bewit then successfully authenticate it', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2', + host: 'example.com', + port: 80 + }; + + credentialsFunc('123456', function (err, credentials) { + + var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' }); + req.url += '&bewit=' + bewit; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(attributes.ext).to.equal('some-app-data'); + done(); + }); + }); + }); + + it('should generate a bewit then successfully authenticate it (no ext)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2', + host: 'example.com', + port: 80 + }; + + credentialsFunc('123456', function (err, credentials) { + + var bewit = Hawk.uri.getBewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100 }); + req.url += '&bewit=' + bewit; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + done(); + }); + }); + }); + + it('should successfully authenticate a request (last param)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(attributes.ext).to.equal('some-app-data'); + done(); + }); + }); + + it('should successfully authenticate a request (first param)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2MjFcMzFjMmNkbUJFd1NJRVZDOVkva1NFb2c3d3YrdEVNWjZ3RXNmOGNHU2FXQT1cc29tZS1hcHAtZGF0YQ&a=1&b=2', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(attributes.ext).to.equal('some-app-data'); + done(); + }); + }); + + it('should successfully authenticate a request (only param)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.not.exist(); + expect(credentials.user).to.equal('steve'); + expect(attributes.ext).to.equal('some-app-data'); + done(); + }); + }); + + it('should fail on multiple authentication', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MTE0ODQ2NDFcZm1CdkNWT3MvcElOTUUxSTIwbWhrejQ3UnBwTmo4Y1VrSHpQd3Q5OXJ1cz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080, + authorization: 'Basic asdasdasdasd' + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Multiple authentications'); + done(); + }); + }); + + it('should fail on method other than GET', function (done) { + + credentialsFunc('123456', function (err, credentials) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + host: 'example.com', + port: 8080 + }; + + var exp = Math.floor(Hawk.utils.now() / 1000) + 60; + var ext = 'some-app-data'; + var mac = Hawk.crypto.calculateMac('bewit', credentials, { + timestamp: exp, + nonce: '', + method: req.method, + resource: req.url, + host: req.host, + port: req.port, + ext: ext + }); + + var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + ext; + + req.url += '&bewit=' + Hoek.base64urlEncode(bewit); + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid method'); + done(); + }); + }); + }); + + it('should fail on invalid host header', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + headers: { + host: 'example.com:something' + } + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid Host header'); + done(); + }); + }); + + it('should fail on empty bewit', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Empty bewit'); + expect(err.isMissing).to.not.exist(); + done(); + }); + }); + + it('should fail on invalid bewit', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=*', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid bewit encoding'); + expect(err.isMissing).to.not.exist(); + done(); + }); + }); + + it('should fail on missing bewit', function (done) { + + var req = { + method: 'GET', + url: '/resource/4', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.not.exist(); + expect(err.isMissing).to.equal(true); + done(); + }); + }); + + it('should fail on invalid bewit structure', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=abc', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Invalid bewit structure'); + done(); + }); + }); + + it('should fail on empty bewit attribute', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=YVxcY1xk', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing bewit attributes'); + done(); + }); + }); + + it('should fail on missing bewit id attribute', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=XDQ1NTIxNDc2MjJcK0JFbFhQMXhuWjcvd1Nrbm1ldGhlZm5vUTNHVjZNSlFVRHk4NWpTZVJ4VT1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Missing bewit attributes'); + done(); + }); + }); + + it('should fail on expired access', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?a=1&b=2&bewit=MTIzNDU2XDEzNTY0MTg1ODNcWk1wZlMwWU5KNHV0WHpOMmRucTRydEk3NXNXTjFjeWVITTcrL0tNZFdVQT1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Access expired'); + done(); + }); + }); + + it('should fail on credentials function error', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(Hawk.error.badRequest('Boom')); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Boom'); + done(); + }); + }); + + it('should fail on credentials function error with credentials', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(Hawk.error.badRequest('Boom'), { some: 'value' }); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Boom'); + expect(credentials.some).to.equal('value'); + done(); + }); + }); + + it('should fail on null credentials function response', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(null, null); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Unknown credentials'); + done(); + }); + }); + + it('should fail on invalid credentials function response', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(null, {}); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.message).to.equal('Invalid credentials'); + done(); + }); + }); + + it('should fail on invalid credentials function response (unknown algorithm)', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(null, { key: 'xxx', algorithm: 'xxx' }); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.message).to.equal('Unknown algorithm'); + done(); + }); + }); + + it('should fail on expired access', function (done) { + + var req = { + method: 'GET', + url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ', + host: 'example.com', + port: 8080 + }; + + Hawk.uri.authenticate(req, function (id, callback) { callback(null, { key: 'xxx', algorithm: 'sha256' }); }, {}, function (err, credentials, attributes) { + + expect(err).to.exist(); + expect(err.output.payload.message).to.equal('Bad mac'); + done(); + }); + }); + }); + + describe('#getBewit', function () { + + it('returns a valid bewit value', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6'); + done(); + }); + + it('returns a valid bewit value (explicit port)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6'); + done(); + }); + + it('returns a valid bewit value (null ext)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c'); + done(); + }); + + it('returns a valid bewit value (parsed uri)', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit(Url.parse('https://example.com/somewhere/over/the/rainbow'), { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6'); + done(); + }); + + it('errors on invalid options', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', 4); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid uri', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid credentials (id)', function (done) { + + var credentials = { + key: '2983d45yun89q', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing credentials', function (done) { + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid credentials (key)', function (done) { + + var credentials = { + id: '123456', + algorithm: 'sha256' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on invalid algorithm', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' }); + expect(bewit).to.equal(''); + done(); + }); + + it('errors on missing options', function (done) { + + var credentials = { + id: '123456', + key: '2983d45yun89q', + algorithm: 'hmac-sha-0' + }; + + var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow'); + expect(bewit).to.equal(''); + done(); + }); + }); +}); + diff --git a/node_modules/hawk/test/utils.js b/node_modules/hawk/test/utils.js new file mode 100755 index 000000000..9ccda8be3 --- /dev/null +++ b/node_modules/hawk/test/utils.js @@ -0,0 +1,120 @@ +// Load modules + +var Code = require('code'); +var Hawk = require('../lib'); +var Lab = require('lab'); +var Package = require('../package.json'); + + +// Declare internals + +var internals = {}; + + +// Test shortcuts + +var lab = exports.lab = Lab.script(); +var describe = lab.experiment; +var it = lab.test; +var expect = Code.expect; + + +describe('Hawk', function () { + + describe('Utils', function () { + + describe('#parseHost', function () { + + it('returns port 80 for non tls node request', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com', + 'content-type': 'text/plain;x=y' + } + }; + + expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(80); + done(); + }); + + it('returns port 443 for non tls node request', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: 'example.com', + 'content-type': 'text/plain;x=y' + }, + connection: { + encrypted: true + } + }; + + expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443); + done(); + }); + + it('returns port 443 for non tls node request (IPv6)', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: '[123:123:123]', + 'content-type': 'text/plain;x=y' + }, + connection: { + encrypted: true + } + }; + + expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443); + done(); + }); + + it('parses IPv6 headers', function (done) { + + var req = { + method: 'POST', + url: '/resource/4?filter=a', + headers: { + host: '[123:123:123]:8000', + 'content-type': 'text/plain;x=y' + }, + connection: { + encrypted: true + } + }; + + var host = Hawk.utils.parseHost(req, 'Host'); + expect(host.port).to.equal('8000'); + expect(host.name).to.equal('[123:123:123]'); + done(); + }); + }); + + describe('#version', function () { + + it('returns the correct package version number', function (done) { + + expect(Hawk.utils.version()).to.equal(Package.version); + done(); + }); + }); + + describe('#unauthorized', function () { + + it('returns a hawk 401', function (done) { + + expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"'); + done(); + }); + }); + }); +}); + + |