pax_global_header00006660000000000000000000000064141452557130014521gustar00rootroot0000000000000052 comment=391fbe4864c2daef0c04345c987e5aa4d44c3ba1 node-http-signature-1.3.6/000077500000000000000000000000001414525571300154315ustar00rootroot00000000000000node-http-signature-1.3.6/.dir-locals.el000066400000000000000000000002621414525571300200620ustar00rootroot00000000000000((nil . ((indent-tabs-mode . nil) (tab-width . 8) (fill-column . 80))) (js-mode . ((js-indent-level . 2) (indent-tabs-mode . nil) )))node-http-signature-1.3.6/.gitignore000066400000000000000000000000161414525571300174160ustar00rootroot00000000000000/node_modules node-http-signature-1.3.6/.gitmodules000066400000000000000000000002771414525571300176140ustar00rootroot00000000000000[submodule "deps/javascriptlint"] path = deps/javascriptlint url = git@github.com:joyent/javascriptlint [submodule "deps/jsstyle"] path = deps/jsstyle url = git@github.com:joyent/jsstyle node-http-signature-1.3.6/.npmignore000066400000000000000000000000661414525571300174320ustar00rootroot00000000000000.gitmodules deps docs Makefile node_modules test toolsnode-http-signature-1.3.6/CHANGES.md000066400000000000000000000043101414525571300170210ustar00rootroot00000000000000# node-http-signature changelog ## not yet released (nothing yet) ## 1.3.6 * Update jsprim due to vulnerability in json-schema (#123) ## 1.3.5 * Add keyPassphrase option to signer (#115) * Add support for created and expires values (#110) ## 1.3.4 * Fix breakage in v1.3.3 with the setting of the "algorithm" field in the Authorization header (#102) ## 1.3.3 **Bad release. Use 1.3.4.** * Add support for an opaque param in the Authorization header (#101) * Add support for adding the keyId and algorithm params into the signing string (#100) ## 1.3.2 * Allow Buffers to be used for verifyHMAC (#98) ## 1.3.1 * Fix node 0.10 usage (#90) ## 1.3.0 **Known issue:** This release broken http-signature with node 0.10. * Bump dependency `sshpk` * Add `Signature` header support (#83) ## 1.2.0 * Bump dependency `assert-plus` * Add ability to pass a custom header name * Replaced dependency `node-uuid` with `uuid` ## 1.1.1 * Version of dependency `assert-plus` updated: old version was missing some license information * Corrected examples in `http_signing.md`, added auto-tests to automatically validate these examples ## 1.1.0 * Bump version of `sshpk` dependency, remove peerDependency on it since it now supports exchanging objects between multiple versions of itself where possible ## 1.0.2 * Bump min version of `jsprim` dependency, to include fixes for using http-signature with `browserify` ## 1.0.1 * Bump minimum version of `sshpk` dependency, to include fixes for whitespace tolerance in key parsing. ## 1.0.0 * First semver release. * #36: Ensure verifySignature does not leak useful timing information * #42: Bring the library up to the latest version of the spec (including the request-target changes) * Support for ECDSA keys and signatures. * Now uses `sshpk` for key parsing, validation and conversion. * Fixes for #21, #47, #39 and compatibility with node 0.8 ## 0.11.0 * Split up HMAC and Signature verification to avoid vulnerabilities where a key intended for use with one can be validated against the other method instead. ## 0.10.2 * Updated versions of most dependencies. * Utility functions exported for PEM => SSH-RSA conversion. * Improvements to tests and examples. node-http-signature-1.3.6/Jenkinsfile000066400000000000000000000045341414525571300176230ustar00rootroot00000000000000@Library('jenkins-joylib@v1.0.8') _ pipeline { agent none options { buildDiscarder(logRotator(numToKeepStr: '30')) timestamps() } stages { stage('top') { parallel { stage('v0.10.48-zone') { agent { label joyCommonLabels(image_ver: '15.4.1') } tools { nodejs 'sdcnode-v0.10.48-zone' } stages { stage('check') { steps{ sh('make check') } } stage('test') { steps{ sh('make test') } } } } stage('v4-zone64') { agent { label joyCommonLabels(image_ver: '15.4.1') } tools { nodejs 'sdcnode-v4-zone64' } stages { stage('check') { steps{ sh('make check') } } stage('test') { steps{ sh('make test') } } } } stage('v6-zone64') { agent { label joyCommonLabels(image_ver: '18.4.0') } tools { nodejs 'sdcnode-v6-zone64' } stages { stage('check') { steps{ sh('make check') } } stage('test') { steps{ sh('make test') } } } } } } } post { always { joySlackNotifications() } } } node-http-signature-1.3.6/LICENSE000066400000000000000000000020531414525571300164360ustar00rootroot00000000000000Copyright Joyent, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-http-signature-1.3.6/Makefile000066400000000000000000000033311414525571300170710ustar00rootroot00000000000000# # Copyright 2019 Joyent, Inc. # JS_FILES := $(shell find lib -name '*.js') JSL_CONF_NODE = tools/jsl.node.conf JSL_FILES_NODE = $(JS_FILES) JSSTYLE_FILES = $(JS_FILES) JSSTYLE_FLAGS = -f tools/jsstyle.conf # This, and the includes below, provide: 'make check' and 'make clean'. include ./tools/mk/Makefile.defs # # Repo-specific targets # .PHONY: all all: $(REPO_DEPS) npm install CLEAN_FILES += ./node_modules .PHONY: test test: all TAP=1 ./node_modules/.bin/tap test/*.test.js # Ensure CHANGES.md and package.json have the same version. .PHONY: check-version check-version: @echo version is: $(shell cat package.json | json version) [ "`cat package.json | json version`" = "`grep '^## ' CHANGES.md | head -2 | tail -1 | awk '{print $$2}'`" ] check: check-version .PHONY: cutarelease cutarelease: $(COMPLETION_FILE) check-version [ -z "`git status --short`" ] # If this fails, the working dir is dirty. @which json 2>/dev/null 1>/dev/null && \ ver=$(shell json -f package.json version) && \ name=$(shell json -f package.json name) && \ publishedVer=$(shell npm view -j $(shell json -f package.json name)@$(shell json -f package.json version) version 2>/dev/null) && \ if [ -n "$$publishedVer" ]; then \ echo "error: $$name@$$ver is already published to npm"; \ exit 1; \ fi && \ echo "** Are you sure you want to tag and publish $$name@$$ver to npm?" && \ echo "** Enter to continue, Ctrl+C to abort." && \ read ver=$(shell cat package.json | json version) && \ date=$(shell date -u "+%Y-%m-%d") && \ git tag -a "v$$ver" -m "version $$ver ($$date)" && \ git push --tags origin && \ npm publish include ./tools/mk/Makefile.deps include ./tools/mk/Makefile.targ node-http-signature-1.3.6/README.md000066400000000000000000000031431414525571300167110ustar00rootroot00000000000000# node-http-signature node-http-signature is a node.js library that has client and server components for Joyent's [HTTP Signature Scheme](http_signing.md). ## Usage Note the example below signs a request with the same key/cert used to start an HTTP server. This is almost certainly not what you actually want, but is just used to illustrate the API calls; you will need to provide your own key management in addition to this library. ### Client ```js var fs = require('fs'); var https = require('https'); var httpSignature = require('http-signature'); var key = fs.readFileSync('./key.pem', 'ascii'); var options = { host: 'localhost', port: 8443, path: '/', method: 'GET', headers: {} }; // Adds a 'Date' header in, signs it, and adds the // 'Authorization' header in. var req = https.request(options, function(res) { console.log(res.statusCode); }); httpSignature.sign(req, { key: key, keyId: './cert.pem', keyPassphrase: 'secret' // (optional) }); req.end(); ``` ### Server ```js var fs = require('fs'); var https = require('https'); var httpSignature = require('http-signature'); var options = { key: fs.readFileSync('./key.pem'), cert: fs.readFileSync('./cert.pem') }; https.createServer(options, function (req, res) { var rc = 200; var parsed = httpSignature.parseRequest(req); var pub = fs.readFileSync(parsed.keyId, 'ascii'); if (!httpSignature.verifySignature(parsed, pub)) rc = 401; res.writeHead(rc); res.end(); }).listen(8443); ``` ## Installation npm install http-signature ## License MIT. ## Bugs See . node-http-signature-1.3.6/deps/000077500000000000000000000000001414525571300163645ustar00rootroot00000000000000node-http-signature-1.3.6/deps/javascriptlint/000077500000000000000000000000001414525571300214215ustar00rootroot00000000000000node-http-signature-1.3.6/deps/jsstyle/000077500000000000000000000000001414525571300200615ustar00rootroot00000000000000node-http-signature-1.3.6/http_signing.md000066400000000000000000000330131414525571300204500ustar00rootroot00000000000000# Abstract This document describes a way to add origin authentication, message integrity, and replay resistance to HTTP REST requests. It is intended to be used over the HTTPS protocol. # Copyright Notice Copyright (c) 2011 Joyent, Inc. and the persons identified as document authors. All rights reserved. Code Components extracted from this document must include MIT License text. # Introduction This protocol is intended to provide a standard way for clients to sign HTTP requests. RFC2617 (HTTP Authentication) defines Basic and Digest authentication mechanisms, and RFC5246 (TLS 1.2) defines client-auth, both of which are widely employed on the Internet today. However, it is common place that the burdens of PKI prevent web service operators from deploying that methodology, and so many fall back to Basic authentication, which has poor security characteristics. Additionally, OAuth provides a fully-specified alternative for authorization of web service requests, but is not (always) ideal for machine to machine communication, as the key acquisition steps (generally) imply a fixed infrastructure that may not make sense to a service provider (e.g., symmetric keys). Several web service providers have invented their own schemes for signing HTTP requests, but to date, none have been placed in the public domain as a standard. This document serves that purpose. There are no techniques in this proposal that are novel beyond previous art, however, this aims to be a simple mechanism for signing these requests. # Signature Authentication Scheme The "signature" authentication scheme is based on the model that the client must authenticate itself with a digital signature produced by either a private asymmetric key (e.g., RSA) or a shared symmetric key (e.g., HMAC). The scheme is parameterized enough such that it is not bound to any particular key type or signing algorithm. However, it does explicitly assume that clients can send an HTTP `Date` header. ## Authorization Header The client is expected to send an Authorization header (as defined in RFC 2617) with the following parameterization: credentials := "Signature" params params := 1#(keyId | algorithm | [headers] | [ext] | signature) digitalSignature := plain-string keyId := "keyId" "=" <"> plain-string <"> algorithm := "algorithm" "=" <"> plain-string <"> headers := "headers" "=" <"> 1#headers-value <"> ext := "ext" "=" <"> plain-string <"> signature := "signature" "=" <"> plain-string <"> headers-value := plain-string plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) ### Signature Parameters #### keyId REQUIRED. The `keyId` field is an opaque string that the server can use to look up the component they need to validate the signature. It could be an SSH key fingerprint, an LDAP DN, etc. Management of keys and assignment of `keyId` is out of scope for this document. #### algorithm REQUIRED. The `algorithm` parameter is used if the client and server agree on a non-standard digital signature algorithm. The full list of supported signature mechanisms is listed below. #### headers OPTIONAL. The `headers` parameter is used to specify the list of HTTP headers used to sign the request. If specified, it should be a quoted list of HTTP header names, separated by a single space character. By default, only one HTTP header is signed, which is the `Date` header. Note that the list MUST be specified in the order the values are concatenated together during signing. To include the HTTP request line in the signature calculation, use the special `request-line` value. While this is overloading the definition of `headers` in HTTP linguism, the request-line is defined in RFC 2616, and as the outlier from headers in useful signature calculation, it is deemed simpler to simply use `request-line` than to add a separate parameter for it. #### extensions OPTIONAL. The `extensions` parameter is used to include additional information which is covered by the request. The content and format of the string is out of scope for this document, and expected to be specified by implementors. #### signature REQUIRED. The `signature` parameter is a `Base64` encoded digital signature generated by the client. The client uses the `algorithm` and `headers` request parameters to form a canonicalized `signing string`. This `signing string` is then signed with the key associated with `keyId` and the algorithm corresponding to `algorithm`. The `signature` parameter is then set to the `Base64` encoding of the signature. ### Signing String Composition In order to generate the string that is signed with a key, the client MUST take the values of each HTTP header specified by `headers` in the order they appear. 1. If the header name is not `request-line` then append the lowercased header name followed with an ASCII colon `:` and an ASCII space ` `. 2. If the header name is `request-line` then append the HTTP request line, otherwise append the header value. 3. If value is not the last value then append an ASCII newline `\n`. The string MUST NOT include a trailing ASCII newline. # Example Requests All requests refer to the following request (body omitted): POST /foo HTTP/1.1 Host: example.org Date: Tue, 07 Jun 2014 20:51:35 GMT Content-Type: application/json Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE= Content-Length: 18 The "rsa-key-1" keyId refers to a private key known to the client and a public key known to the server. The "hmac-key-1" keyId refers to key known to the client and server. ## Default parameterization The authorization header and signature would be generated as: Authorization: Signature keyId="rsa-key-1",algorithm="rsa-sha256",signature="Base64(RSA-SHA256(signing string))" The client would compose the signing string as: date: Tue, 07 Jun 2014 20:51:35 GMT ## Header List The authorization header and signature would be generated as: Authorization: Signature keyId="rsa-key-1",algorithm="rsa-sha256",headers="(request-target) date content-type digest",signature="Base64(RSA-SHA256(signing string))" The client would compose the signing string as (`+ "\n"` inserted for readability): (request-target): post /foo + "\n" date: Tue, 07 Jun 2011 20:51:35 GMT + "\n" content-type: application/json + "\n" digest: SHA-256=Base64(SHA256(Body)) ## Algorithm The authorization header and signature would be generated as: Authorization: Signature keyId="hmac-key-1",algorithm="hmac-sha1",signature="Base64(HMAC-SHA1(signing string))" The client would compose the signing string as: date: Tue, 07 Jun 2011 20:51:35 GMT # Signing Algorithms Currently supported algorithm names are: * rsa-sha1 * rsa-sha256 * rsa-sha512 * dsa-sha1 * hmac-sha1 * hmac-sha256 * hmac-sha512 # Security Considerations ## Default Parameters Note the default parameterization of the `Signature` scheme is only safe if all requests are carried over a secure transport (i.e., TLS). Sending the default scheme over a non-secure transport will leave the request vulnerable to spoofing, tampering, replay/repudiation, and integrity violations (if using the STRIDE threat-modeling methodology). ## Insecure Transports If sending the request over plain HTTP, service providers SHOULD require clients to sign ALL HTTP headers, and the `request-line`. Additionally, service providers SHOULD require `Content-MD5` calculations to be performed to ensure against any tampering from clients. ## Nonces Nonces are out of scope for this document simply because many service providers fail to implement them correctly, or do not adopt security specifications because of the infrastructure complexity. Given the `header` parameterization, a service provider is fully enabled to add nonce semantics into this scheme by using something like an `x-request-nonce` header, and ensuring it is signed with the `Date` header. ## Clock Skew As the default scheme is to sign the `Date` header, service providers SHOULD protect against logged replay attacks by enforcing a clock skew. The server SHOULD be synchronized with NTP, and the recommendation in this specification is to allow 300s of clock skew (in either direction). ## Required Headers to Sign It is out of scope for this document to dictate what headers a service provider will want to enforce, but service providers SHOULD at minimum include the `Date` header. # References ## Normative References * [RFC2616] Hypertext Transfer Protocol -- HTTP/1.1 * [RFC2617] HTTP Authentication: Basic and Digest Access Authentication * [RFC5246] The Transport Layer Security (TLS) Protocol Version 1.2 ## Informative References Name: Mark Cavage (editor) Company: Joyent, Inc. Email: mark.cavage@joyent.com URI: http://www.joyent.com # Appendix A - Test Values The following test data uses the RSA (1024b) keys, which we will refer to as `keyId=Test` in the following samples: -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw oYi+1hqp1fIekaxsyQIDAQAB -----END PUBLIC KEY----- -----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== -----END RSA PRIVATE KEY----- And all examples use this request: POST /foo?param=value&pet=dog HTTP/1.1 Host: example.com Date: Thu, 05 Jan 2014 21:31:40 GMT Content-Type: application/json Digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE= Content-Length: 18 {"hello": "world"} ### Default The string to sign would be: date: Thu, 05 Jan 2014 21:31:40 GMT The Authorization header would be: Authorization: Signature keyId="Test",algorithm="rsa-sha256",signature="jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w=" ### All Headers Parameterized to include all headers, the string to sign would be (`+ "\n"` inserted for readability): (request-target): post /foo?param=value&pet=dog host: example.com date: Thu, 05 Jan 2014 21:31:40 GMT content-type: application/json digest: SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE= content-length: 18 The Authorization header would be: Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="Ef7MlxLXoBovhil3AlyjtBwAL9g4TN3tibLj7uuNB3CROat/9KaeQ4hW2NiJ+pZ6HQEOx9vYZAyi+7cmIkmJszJCut5kQLAwuX+Ms/mUFvpKlSo9StS2bMXDBNjOh4Auj774GFj4gwjS+3NhFeoqyr/MuN6HsEnkvn6zdgfE2i0=" ## Generating and verifying signatures using `openssl` The `openssl` commandline tool can be used to generate or verify the signatures listed above. Compose the signing string as usual, and pipe it into the the `openssl dgst` command, then into `openssl enc -base64`, as follows: $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \ openssl dgst -binary -sign /path/to/private.pem -sha256 | \ openssl enc -base64 jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9Hp... $ The `-sha256` option is necessary to produce an `rsa-sha256` signature. You can select other hash algorithms such as `sha1` by changing this argument. To verify a signature, first save the signature data, Base64-decoded, into a file, then use `openssl dgst` again with the `-verify` option: $ echo 'jKyvPcxB4JbmYY4mByy...' | openssl enc -A -d -base64 > signature $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \ openssl dgst -sha256 -verify /path/to/public.pem -signature ./signature Verified OK $ ## Generating and verifying signatures using `sshpk-sign` You can also generate and check signatures using the `sshpk-sign` tool which is included with the `sshpk` package in `npm`. Compose the signing string as above, and pipe it into `sshpk-sign` as follows: $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \ sshpk-sign -i /path/to/private.pem jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9Hp... $ This will produce an `rsa-sha256` signature by default, as you can see using the `-v` option: sshpk-sign: using rsa-sha256 with a 1024 bit key You can also use `sshpk-verify` in a similar manner: $ printf 'date: Thu, 05 Jan 2014 21:31:40 GMT' | \ sshpk-verify -i ./public.pem -s 'jKyvPcxB4JbmYY...' OK $ node-http-signature-1.3.6/lib/000077500000000000000000000000001414525571300161775ustar00rootroot00000000000000node-http-signature-1.3.6/lib/index.js000066400000000000000000000011621414525571300176440ustar00rootroot00000000000000// Copyright 2015 Joyent, Inc. var parser = require('./parser'); var signer = require('./signer'); var verify = require('./verify'); var utils = require('./utils'); ///--- API module.exports = { parse: parser.parseRequest, parseRequest: parser.parseRequest, sign: signer.signRequest, signRequest: signer.signRequest, createSigner: signer.createSigner, isSigner: signer.isSigner, sshKeyToPEM: utils.sshKeyToPEM, sshKeyFingerprint: utils.fingerprint, pemToRsaSSHKey: utils.pemToRsaSSHKey, verify: verify.verifySignature, verifySignature: verify.verifySignature, verifyHMAC: verify.verifyHMAC }; node-http-signature-1.3.6/lib/parser.js000066400000000000000000000300471414525571300200350ustar00rootroot00000000000000// Copyright 2012 Joyent, Inc. All rights reserved. var assert = require('assert-plus'); var util = require('util'); var utils = require('./utils'); ///--- Globals var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var HttpSignatureError = utils.HttpSignatureError; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var validateAlgorithm = utils.validateAlgorithm; var State = { New: 0, Params: 1 }; var ParamsState = { Name: 0, Quote: 1, Value: 2, Comma: 3, Number: 4 }; ///--- Specific Errors function ExpiredRequestError(message) { HttpSignatureError.call(this, message, ExpiredRequestError); } util.inherits(ExpiredRequestError, HttpSignatureError); function InvalidHeaderError(message) { HttpSignatureError.call(this, message, InvalidHeaderError); } util.inherits(InvalidHeaderError, HttpSignatureError); function InvalidParamsError(message) { HttpSignatureError.call(this, message, InvalidParamsError); } util.inherits(InvalidParamsError, HttpSignatureError); function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); ///--- Exported API module.exports = { /** * Parses the 'Authorization' header out of an http.ServerRequest object. * * Note that this API will fully validate the Authorization header, and throw * on any error. It will not however check the signature, or the keyId format * as those are specific to your environment. You can use the options object * to pass in extra constraints. * * As a response object you can expect this: * * { * "scheme": "Signature", * "params": { * "keyId": "foo", * "algorithm": "rsa-sha256", * "headers": [ * "date" or "x-date", * "digest" * ], * "signature": "base64" * }, * "signingString": "ready to be passed to crypto.verify()" * } * * @param {Object} request an http.ServerRequest. * @param {Object} options an optional options object with: * - clockSkew: allowed clock skew in seconds (default 300). * - headers: required header names (def: date or x-date) * - algorithms: algorithms to support (default: all). * - strict: should enforce latest spec parsing * (default: false). * @return {Object} parsed out object (see above). * @throws {TypeError} on invalid input. * @throws {InvalidHeaderError} on an invalid Authorization header error. * @throws {InvalidParamsError} if the params in the scheme are invalid. * @throws {MissingHeaderError} if the params indicate a header not present, * either in the request headers from the params, * or not in the params from a required header * in options. * @throws {StrictParsingError} if old attributes are used in strict parsing * mode. * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. */ parseRequest: function parseRequest(request, options) { assert.object(request, 'request'); assert.object(request.headers, 'request.headers'); if (options === undefined) { options = {}; } assert.object(options, 'options'); assert.optionalFinite(options.clockSkew, 'options.clockSkew'); var headers = [request.headers['x-date'] ? 'x-date' : 'date']; if (options.headers !== undefined) { assert.arrayOfString(headers, 'options.headers'); headers = options.headers; } var authzHeaderName = options.authorizationHeaderName; var authz = request.headers[authzHeaderName] || request.headers[utils.HEADER.AUTH] || request.headers[utils.HEADER.SIG]; if (!authz) { var errHeader = authzHeaderName ? authzHeaderName : utils.HEADER.AUTH + ' or ' + utils.HEADER.SIG; throw new MissingHeaderError('no ' + errHeader + ' header ' + 'present in the request'); } options.clockSkew = options.clockSkew || 300; var i = 0; var state = authz === request.headers[utils.HEADER.SIG] ? State.Params : State.New; var substate = ParamsState.Name; var tmpName = ''; var tmpValue = ''; var parsed = { scheme: authz === request.headers[utils.HEADER.SIG] ? 'Signature' : '', params: {}, signingString: '' }; for (i = 0; i < authz.length; i++) { var c = authz.charAt(i); switch (Number(state)) { case State.New: if (c !== ' ') parsed.scheme += c; else state = State.Params; break; case State.Params: switch (Number(substate)) { case ParamsState.Name: var code = c.charCodeAt(0); // restricted name of A-Z / a-z if ((code >= 0x41 && code <= 0x5a) || // A-Z (code >= 0x61 && code <= 0x7a)) { // a-z tmpName += c; } else if (c === '=') { if (tmpName.length === 0) throw new InvalidHeaderError('bad param format'); substate = ParamsState.Quote; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Quote: if (c === '"') { tmpValue = ''; substate = ParamsState.Value; } else { //number substate = ParamsState.Number; code = c.charCodeAt(0); if (code < 0x30 || code > 0x39) { //character not in 0-9 throw new InvalidHeaderError('bad param format'); } tmpValue = c; } break; case ParamsState.Value: if (c === '"') { parsed.params[tmpName] = tmpValue; substate = ParamsState.Comma; } else { tmpValue += c; } break; case ParamsState.Number: if (c === ',') { parsed.params[tmpName] = parseInt(tmpValue, 10); tmpName = ''; substate = ParamsState.Name; } else { code = c.charCodeAt(0); if (code < 0x30 || code > 0x39) { //character not in 0-9 throw new InvalidHeaderError('bad param format'); } tmpValue += c; } break; case ParamsState.Comma: if (c === ',') { tmpName = ''; substate = ParamsState.Name; } else { throw new InvalidHeaderError('bad param format'); } break; default: throw new Error('Invalid substate'); } break; default: throw new Error('Invalid substate'); } } if (!parsed.params.headers || parsed.params.headers === '') { if (request.headers['x-date']) { parsed.params.headers = ['x-date']; } else { parsed.params.headers = ['date']; } } else { parsed.params.headers = parsed.params.headers.split(' '); } // Minimally validate the parsed object if (!parsed.scheme || parsed.scheme !== 'Signature') throw new InvalidHeaderError('scheme was not "Signature"'); if (!parsed.params.keyId) throw new InvalidHeaderError('keyId was not specified'); if (!parsed.params.algorithm) throw new InvalidHeaderError('algorithm was not specified'); if (!parsed.params.signature) throw new InvalidHeaderError('signature was not specified'); // Check the algorithm against the official list try { validateAlgorithm(parsed.params.algorithm); } catch (e) { if (e instanceof InvalidAlgorithmError) throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + 'supported')); else throw (e); } // Build the signingString for (i = 0; i < parsed.params.headers.length; i++) { var h = parsed.params.headers[i].toLowerCase(); parsed.params.headers[i] = h; if (h === 'request-line') { if (!options.strict) { /* * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ parsed.signingString += request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { parsed.signingString += '(request-target): ' + request.method.toLowerCase() + ' ' + request.url; } else if (h === '(keyid)') { parsed.signingString += '(keyid): ' + parsed.params.keyId; } else if (h === '(algorithm)') { parsed.signingString += '(algorithm): ' + parsed.params.algorithm; } else if (h === '(opaque)') { var opaque = parsed.params.opaque; if (opaque === undefined) { throw new MissingHeaderError('opaque param was not in the ' + authzHeaderName + ' header'); } parsed.signingString += '(opaque): ' + opaque; } else if (h === '(created)') { parsed.signingString += '(created): ' + parsed.params.created; } else if (h === '(expires)') { parsed.signingString += '(expires): ' + parsed.params.expires; } else { var value = request.headers[h]; if (value === undefined) throw new MissingHeaderError(h + ' was not in the request'); parsed.signingString += h + ': ' + value; } if ((i + 1) < parsed.params.headers.length) parsed.signingString += '\n'; } // Check against the constraints var date; var skew; if (request.headers.date || request.headers['x-date']) { if (request.headers['x-date']) { date = new Date(request.headers['x-date']); } else { date = new Date(request.headers.date); } var now = new Date(); skew = Math.abs(now.getTime() - date.getTime()); if (skew > options.clockSkew * 1000) { throw new ExpiredRequestError('clock skew of ' + (skew / 1000) + 's was greater than ' + options.clockSkew + 's'); } } if (parsed.params.created) { skew = parsed.params.created - Math.floor(Date.now() / 1000); if (skew > options.clockSkew) { throw new ExpiredRequestError('Created lies in the future (with ' + 'skew ' + skew + 's greater than allowed ' + options.clockSkew + 's'); } } if (parsed.params.expires) { var expiredSince = Math.floor(Date.now() / 1000) - parsed.params.expires; if (expiredSince > options.clockSkew) { throw new ExpiredRequestError('Request expired with skew ' + expiredSince + 's greater than allowed ' + options.clockSkew + 's'); } } headers.forEach(function (hdr) { // Remember that we already checked any headers in the params // were in the request, so if this passes we're good. if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) throw new MissingHeaderError(hdr + ' was not a signed header'); }); parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); if (options.algorithms) { if (options.algorithms.indexOf(parsed.params.algorithm) === -1) throw new InvalidParamsError(parsed.params.algorithm + ' is not a supported algorithm'); } parsed.algorithm = parsed.params.algorithm.toUpperCase(); parsed.keyId = parsed.params.keyId; parsed.opaque = parsed.params.opaque; return parsed; } }; node-http-signature-1.3.6/lib/signer.js000066400000000000000000000367701414525571300200410ustar00rootroot00000000000000// Copyright 2012 Joyent, Inc. All rights reserved. var assert = require('assert-plus'); var crypto = require('crypto'); var util = require('util'); var sshpk = require('sshpk'); var jsprim = require('jsprim'); var utils = require('./utils'); var sprintf = require('util').format; var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Globals var AUTHZ_PARAMS = [ 'keyId', 'algorithm', 'created', 'expires', 'opaque', 'headers', 'signature' ]; ///--- Specific Errors function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); function FormatAuthz(prefix, params) { assert.string(prefix, 'prefix'); assert.object(params, 'params'); var authz = ''; for (var i = 0; i < AUTHZ_PARAMS.length; i++) { var param = AUTHZ_PARAMS[i]; var value = params[param]; if (value === undefined) continue; if (typeof (value) === 'number') { authz += prefix + sprintf('%s=%d', param, value); } else { assert.string(value, 'params.' + param); authz += prefix + sprintf('%s="%s"', param, value); } prefix = ','; } return (authz); } /* See createSigner() */ function RequestSigner(options) { assert.object(options, 'options'); var alg = []; if (options.algorithm !== undefined) { assert.string(options.algorithm, 'options.algorithm'); alg = validateAlgorithm(options.algorithm); } this.rs_alg = alg; /* * RequestSigners come in two varieties: ones with an rs_signFunc, and ones * with an rs_signer. * * rs_signFunc-based RequestSigners have to build up their entire signing * string within the rs_lines array and give it to rs_signFunc as a single * concat'd blob. rs_signer-based RequestSigners can add a line at a time to * their signing state by using rs_signer.update(), thus only needing to * buffer the hash function state and one line at a time. */ if (options.sign !== undefined) { assert.func(options.sign, 'options.sign'); this.rs_signFunc = options.sign; } else if (alg[0] === 'hmac' && options.key !== undefined) { assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key for HMAC must be a string or Buffer')); /* * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their * data in chunks rather than requiring it all to be given in one go * at the end, so they are more similar to signers than signFuncs. */ this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); this.rs_signer.sign = function () { var digest = this.digest('base64'); return ({ hashAlgorithm: alg[1], toString: function () { return (digest); } }); }; } else if (options.key !== undefined) { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) assert.optionalString(options.keyPassphrase, 'options.keyPassphrase'); key = sshpk.parsePrivateKey(key, 'auto', { passphrase: options.keyPassphrase }); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); this.rs_key = key; assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } this.rs_signer = key.createSign(alg[1]); } else { throw (new TypeError('options.sign (func) or options.key is required')); } this.rs_headers = []; this.rs_lines = []; } /** * Adds a header to be signed, with its value, into this signer. * * @param {String} header * @param {String} value * @return {String} value written */ RequestSigner.prototype.writeHeader = function (header, value) { assert.string(header, 'header'); header = header.toLowerCase(); assert.string(value, 'value'); this.rs_headers.push(header); if (this.rs_signFunc) { this.rs_lines.push(header + ': ' + value); } else { var line = header + ': ' + value; if (this.rs_headers.length > 0) line = '\n' + line; this.rs_signer.update(line); } return (value); }; /** * Adds a default Date header, returning its value. * * @return {String} */ RequestSigner.prototype.writeDateHeader = function () { return (this.writeHeader('date', jsprim.rfc1123(new Date()))); }; /** * Adds the request target line to be signed. * * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') * @param {String} path */ RequestSigner.prototype.writeTarget = function (method, path) { assert.string(method, 'method'); assert.string(path, 'path'); method = method.toLowerCase(); this.writeHeader('(request-target)', method + ' ' + path); }; /** * Calculate the value for the Authorization header on this request * asynchronously. * * @param {Func} callback (err, authz) */ RequestSigner.prototype.sign = function (cb) { assert.func(cb, 'callback'); if (this.rs_headers.length < 1) throw (new Error('At least one header must be signed')); var alg, authz; if (this.rs_signFunc) { var data = this.rs_lines.join('\n'); var self = this; this.rs_signFunc(data, function (err, sig) { if (err) { cb(err); return; } try { assert.object(sig, 'signature'); assert.string(sig.keyId, 'signature.keyId'); assert.string(sig.algorithm, 'signature.algorithm'); assert.string(sig.signature, 'signature.signature'); alg = validateAlgorithm(sig.algorithm); authz = FormatAuthz('Signature ', { keyId: sig.keyId, algorithm: sig.algorithm, headers: self.rs_headers.join(' '), signature: sig.signature }); } catch (e) { cb(e); return; } cb(null, authz); }); } else { try { var sigObj = this.rs_signer.sign(); } catch (e) { cb(e); return; } alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; var signature = sigObj.toString(); authz = FormatAuthz('Signature ', { keyId: this.rs_keyId, algorithm: alg, headers: this.rs_headers.join(' '), signature: signature }); cb(null, authz); } }; ///--- Exported API module.exports = { /** * Identifies whether a given object is a request signer or not. * * @param {Object} object, the object to identify * @returns {Boolean} */ isSigner: function (obj) { if (typeof (obj) === 'object' && obj instanceof RequestSigner) return (true); return (false); }, /** * Creates a request signer, used to asynchronously build a signature * for a request (does not have to be an http.ClientRequest). * * @param {Object} options, either: * - {String} keyId * - {String|Buffer} key * - {String} algorithm (optional, required for HMAC) * - {String} keyPassphrase (optional, not for HMAC) * or: * - {Func} sign (data, cb) * @return {RequestSigner} */ createSigner: function createSigner(options) { return (new RequestSigner(options)); }, /** * Adds an 'Authorization' header to an http.ClientRequest object. * * Note that this API will add a Date header if it's not already set. Any * other headers in the options.headers array MUST be present, or this * will throw. * * You shouldn't need to check the return type; it's just there if you want * to be pedantic. * * The optional flag indicates whether parsing should use strict enforcement * of the version draft-cavage-http-signatures-04 of the spec or beyond. * The default is to be loose and support * older versions for compatibility. * * @param {Object} request an instance of http.ClientRequest. * @param {Object} options signing parameters object: * - {String} keyId required. * - {String} key required (either a PEM or HMAC key). * - {Array} headers optional; defaults to ['date']. * - {String} algorithm optional (unless key is HMAC); * default is the same as the sshpk default * signing algorithm for the type of key given * - {String} httpVersion optional; defaults to '1.1'. * - {Boolean} strict optional; defaults to 'false'. * - {int} expiresIn optional; defaults to 60. The * seconds after which the signature should * expire; * - {String} keyPassphrase optional; The passphrase to * pass to sshpk to parse the privateKey. * This doesn't do anything if algorithm is * HMAC. * @return {Boolean} true if Authorization (and optionally Date) were added. * @throws {TypeError} on bad parameter types (input). * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with * the given key. * @throws {sshpk.KeyParseError} if key was bad. * @throws {MissingHeaderError} if a header to be signed was specified but * was not present. */ signRequest: function signRequest(request, options) { assert.object(request, 'request'); assert.object(options, 'options'); assert.optionalString(options.algorithm, 'options.algorithm'); assert.string(options.keyId, 'options.keyId'); assert.optionalString(options.opaque, 'options.opaque'); assert.optionalArrayOfString(options.headers, 'options.headers'); assert.optionalString(options.httpVersion, 'options.httpVersion'); assert.optionalNumber(options.expiresIn, 'options.expiresIn'); assert.optionalString(options.keyPassphrase, 'options.keyPassphrase'); if (!request.getHeader('Date')) request.setHeader('Date', jsprim.rfc1123(new Date())); var headers = ['date']; if (options.headers) headers = options.headers; if (!options.httpVersion) options.httpVersion = '1.1'; var alg = []; if (options.algorithm) { options.algorithm = options.algorithm.toLowerCase(); alg = validateAlgorithm(options.algorithm); } var key = options.key; if (alg[0] === 'hmac') { if (typeof (key) !== 'string' && !Buffer.isBuffer(key)) throw (new TypeError('options.key must be a string or Buffer')); } else { if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(options.key, 'auto', { passphrase: options.keyPassphrase }); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] === undefined) { alg[0] = key.type; } else if (key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } if (alg[1] === undefined) { alg[1] = key.defaultHashAlgorithm(); } options.algorithm = alg[0] + '-' + alg[1]; } var params = { 'keyId': options.keyId, 'algorithm': options.algorithm }; var i; var stringToSign = ''; for (i = 0; i < headers.length; i++) { if (typeof (headers[i]) !== 'string') throw new TypeError('options.headers must be an array of Strings'); var h = headers[i].toLowerCase(); if (h === 'request-line') { if (!options.strict) { /** * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ stringToSign += request.method + ' ' + request.path + ' HTTP/' + options.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { stringToSign += '(request-target): ' + request.method.toLowerCase() + ' ' + request.path; } else if (h === '(keyid)') { stringToSign += '(keyid): ' + options.keyId; } else if (h === '(algorithm)') { stringToSign += '(algorithm): ' + options.algorithm; } else if (h === '(opaque)') { var opaque = options.opaque; if (opaque == undefined || opaque === '') { throw new MissingHeaderError('options.opaque was not in the request'); } stringToSign += '(opaque): ' + opaque; } else if (h === '(created)') { var created = Math.floor(Date.now() / 1000); params.created = created; stringToSign += '(created): ' + created; } else if (h === '(expires)') { var expiresIn = options.expiresIn; if (expiresIn === undefined) { expiresIn = 60; } const expires = Math.floor(Date.now() / 1000) + expiresIn; params.expires = expires; stringToSign += '(expires): ' + expires; } else { var value = request.getHeader(h); if (value === undefined || value === '') { throw new MissingHeaderError(h + ' was not in the request'); } stringToSign += h + ': ' + value; } if ((i + 1) < headers.length) stringToSign += '\n'; } /* This is just for unit tests. */ if (request.hasOwnProperty('_stringToSign')) { request._stringToSign = stringToSign; } var signature; if (alg[0] === 'hmac') { var hmac = crypto.createHmac(alg[1].toUpperCase(), key); hmac.update(stringToSign); signature = hmac.digest('base64'); } else { var signer = key.createSign(alg[1]); signer.update(stringToSign); var sigObj = signer.sign(); if (!HASH_ALGOS[sigObj.hashAlgorithm]) { throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + ' is not a supported hash algorithm')); } assert.strictEqual(alg[1], sigObj.hashAlgorithm, 'hash algorithm mismatch'); signature = sigObj.toString(); assert.notStrictEqual(signature, '', 'empty signature produced'); } var authzHeaderName = options.authorizationHeaderName || 'Authorization'; var prefix = authzHeaderName.toLowerCase() === utils.HEADER.SIG ? '' : 'Signature '; params.signature = signature; if (options.opaque) params.opaque = options.opaque; if (options.headers) params.headers = options.headers.join(' '); request.setHeader(authzHeaderName, FormatAuthz(prefix, params)); return true; } }; node-http-signature-1.3.6/lib/utils.js000066400000000000000000000055501414525571300177020ustar00rootroot00000000000000// Copyright 2012 Joyent, Inc. All rights reserved. var assert = require('assert-plus'); var sshpk = require('sshpk'); var util = require('util'); var HASH_ALGOS = { 'sha1': true, 'sha256': true, 'sha512': true }; var PK_ALGOS = { 'rsa': true, 'dsa': true, 'ecdsa': true }; var HEADER = { AUTH: 'authorization', SIG: 'signature' }; function HttpSignatureError(message, caller) { if (Error.captureStackTrace) Error.captureStackTrace(this, caller || HttpSignatureError); this.message = message; this.name = caller.name; } util.inherits(HttpSignatureError, Error); function InvalidAlgorithmError(message) { HttpSignatureError.call(this, message, InvalidAlgorithmError); } util.inherits(InvalidAlgorithmError, HttpSignatureError); function validateAlgorithm(algorithm) { var alg = algorithm.toLowerCase().split('-'); if (alg.length !== 2) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + 'valid algorithm')); } if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + 'are not supported')); } if (!HASH_ALGOS[alg[1]]) { throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + 'supported hash algorithm')); } return (alg); } ///--- API module.exports = { HEADER: HEADER, HASH_ALGOS: HASH_ALGOS, PK_ALGOS: PK_ALGOS, HttpSignatureError: HttpSignatureError, InvalidAlgorithmError: InvalidAlgorithmError, validateAlgorithm: validateAlgorithm, /** * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. * * The intent of this module is to interoperate with OpenSSL only, * specifically the node crypto module's `verify` method. * * @param {String} key an OpenSSH public key. * @return {String} PEM encoded form of the RSA public key. * @throws {TypeError} on bad input. * @throws {Error} on invalid ssh key formatted data. */ sshKeyToPEM: function sshKeyToPEM(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.toString('pem')); }, /** * Generates an OpenSSH fingerprint from an ssh public key. * * @param {String} key an OpenSSH public key. * @return {String} key fingerprint. * @throws {TypeError} on bad input. * @throws {Error} if what you passed doesn't look like an ssh public key. */ fingerprint: function fingerprint(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.fingerprint('md5').toString('hex')); }, /** * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) * * The reverse of the above function. */ pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { assert.equal('string', typeof (pem), 'typeof pem'); var k = sshpk.parseKey(pem, 'pem'); k.comment = comment; return (k.toString('ssh')); } }; node-http-signature-1.3.6/lib/verify.js000066400000000000000000000060741414525571300200500ustar00rootroot00000000000000// Copyright 2015 Joyent, Inc. var assert = require('assert-plus'); var crypto = require('crypto'); var sshpk = require('sshpk'); var utils = require('./utils'); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Exported API module.exports = { /** * Verify RSA/DSA signature against public key. You are expected to pass in * an object that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} pubkey RSA/DSA private key PEM. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifySignature: function verifySignature(parsedSignature, pubkey) { assert.object(parsedSignature, 'parsedSignature'); if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) pubkey = sshpk.parseKey(pubkey); assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] === 'hmac' || alg[0] !== pubkey.type) return (false); var v = pubkey.createVerify(alg[1]); v.update(parsedSignature.signingString); return (v.verify(parsedSignature.params.signature, 'base64')); }, /** * Verify HMAC against shared secret. You are expected to pass in an object * that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} or {Buffer} secret HMAC shared secret. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifyHMAC: function verifyHMAC(parsedSignature, secret) { assert.object(parsedSignature, 'parsedHMAC'); assert(typeof (secret) === 'string' || Buffer.isBuffer(secret)); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] !== 'hmac') return (false); var hashAlg = alg[1].toUpperCase(); var hmac = crypto.createHmac(hashAlg, secret); hmac.update(parsedSignature.signingString); /* * Now double-hash to avoid leaking timing information - there's * no easy constant-time compare in JS, so we use this approach * instead. See for more info: * https://www.isecpartners.com/blog/2011/february/double-hmac- * verification.aspx */ var h1 = crypto.createHmac(hashAlg, secret); h1.update(hmac.digest()); h1 = h1.digest(); var h2 = crypto.createHmac(hashAlg, secret); h2.update(new Buffer(parsedSignature.params.signature, 'base64')); h2 = h2.digest(); /* Node 0.8 returns strings from .digest(). */ if (typeof (h1) === 'string') return (h1 === h2); /* And node 0.10 lacks the .equals() method on Buffers. */ if (Buffer.isBuffer(h1) && !h1.equals) return (h1.toString('binary') === h2.toString('binary')); return (h1.equals(h2)); } }; node-http-signature-1.3.6/package-lock.json000066400000000000000000000252021414525571300206460ustar00rootroot00000000000000{ "name": "http-signature", "version": "1.3.6", "lockfileVersion": 1, "requires": true, "dependencies": { "abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", "dev": true }, "asn1": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", "requires": { "safer-buffer": "~2.1.0" } }, "assert-plus": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=" }, "bcrypt-pbkdf": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", "requires": { "tweetnacl": "^0.14.3" } }, "buffer-equal": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-0.0.2.tgz", "integrity": "sha1-7Lt5D1aNQAmKYkK1SAXHWAXrk48=", "dev": true }, "bunker": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/bunker/-/bunker-0.1.2.tgz", "integrity": "sha1-yImSRkqOKm7ehpMDdfkrWAd++Xw=", "dev": true, "requires": { "burrito": ">=0.2.5 <0.3" } }, "burrito": { "version": "0.2.12", "resolved": "https://registry.npmjs.org/burrito/-/burrito-0.2.12.tgz", "integrity": "sha1-0NbmrIHV6ZeJxvpKzLCwAx6lT2s=", "dev": true, "requires": { "traverse": "~0.5.1", "uglify-js": "~1.1.1" }, "dependencies": { "traverse": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.5.2.tgz", "integrity": "sha1-4gPFjV9/DjfbbnTArLkpuwm2HYU=", "dev": true } } }, "charm": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/charm/-/charm-0.1.2.tgz", "integrity": "sha1-BsIe7RobBq62dVPNxT4jJ0usIpY=", "dev": true }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", "requires": { "assert-plus": "^1.0.0" } }, "deep-equal": { "version": "0.0.0", "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.0.0.tgz", "integrity": "sha1-mWedO70EcVb81FDT0B7rkGhpHoM=", "dev": true }, "deep-is": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", "dev": true }, "difflet": { "version": "0.2.6", "resolved": "https://registry.npmjs.org/difflet/-/difflet-0.2.6.tgz", "integrity": "sha1-qyOzH1ZJtvqo49KsvTNEZzZcpvo=", "dev": true, "requires": { "charm": "0.1.x", "deep-is": "0.1.x", "traverse": "0.6.x" } }, "ecc-jsbn": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", "requires": { "jsbn": "~0.1.0", "safer-buffer": "^2.1.0" } }, "extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=" }, "getpass": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", "requires": { "assert-plus": "^1.0.0" } }, "glob": { "version": "3.2.11", "resolved": "https://registry.npmjs.org/glob/-/glob-3.2.11.tgz", "integrity": "sha1-Spc/Y1uRkPcV0QmH1cAP0oFevj0=", "dev": true, "requires": { "inherits": "2", "minimatch": "0.3" } }, "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "dev": true }, "jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=" }, "json-schema": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" }, "jsprim": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-2.0.2.tgz", "integrity": "sha512-gqXddjPqQ6G40VdnI6T6yObEC+pDNvyP95wdQhkWkg7crHH3km5qP1FsOXEkzEQwnz6gz5qGTn1c2Y52wP3OyQ==", "requires": { "assert-plus": "1.0.0", "extsprintf": "1.3.0", "json-schema": "0.4.0", "verror": "1.10.0" } }, "lru-cache": { "version": "2.7.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.7.3.tgz", "integrity": "sha1-bUUk6LlV+V1PW1iFHOId1y+06VI=", "dev": true }, "minimatch": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.3.0.tgz", "integrity": "sha1-J12O2qxPG7MyZHIInnlJyDlGmd0=", "dev": true, "requires": { "lru-cache": "2", "sigmund": "~1.0.0" } }, "mkdirp": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.5.tgz", "integrity": "sha1-3j5fiWHIjHh+4TaN+EmsRBPsqNc=", "dev": true }, "nopt": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/nopt/-/nopt-2.2.1.tgz", "integrity": "sha1-KqCbfRdoSHs7ianFqlIzW/8Lrqc=", "dev": true, "requires": { "abbrev": "1" } }, "runforcover": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/runforcover/-/runforcover-0.0.2.tgz", "integrity": "sha1-NE8FfY1F0zrrxsyCIEZ49pxIV8w=", "dev": true, "requires": { "bunker": "0.1.X" } }, "safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, "sigmund": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz", "integrity": "sha1-P/IfGYytIXX587eBhT/ZTQ0ZtZA=", "dev": true }, "slide": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/slide/-/slide-1.1.6.tgz", "integrity": "sha1-VusCfWW00tzmyy4tMsTUr8nh1wc=", "dev": true }, "sshpk": { "version": "1.16.1", "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", "requires": { "asn1": "~0.2.3", "assert-plus": "^1.0.0", "bcrypt-pbkdf": "^1.0.0", "dashdash": "^1.12.0", "ecc-jsbn": "~0.1.1", "getpass": "^0.1.1", "jsbn": "~0.1.0", "safer-buffer": "^2.0.2", "tweetnacl": "~0.14.0" } }, "tap": { "version": "0.4.2", "resolved": "https://registry.npmjs.org/tap/-/tap-0.4.2.tgz", "integrity": "sha1-TZRhJmoNfG6j2A0dkitPLvbU+Zc=", "dev": true, "requires": { "buffer-equal": "~0.0.0", "deep-equal": "~0.0.0", "difflet": "~0.2.0", "glob": "~3.2.1", "inherits": "*", "mkdirp": "~0.3", "nopt": "~2", "runforcover": "~0.0.2", "slide": "*", "tap-consumer": "*", "yamlish": "*" }, "dependencies": { "inherits": { "version": "1.0.0", "bundled": true, "dev": true }, "yamlish": { "version": "0.0.5", "bundled": true, "dev": true } } }, "tap-consumer": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/tap-consumer/-/tap-consumer-0.0.1.tgz", "integrity": "sha1-oSf7Dyj+9LX+Vzsvz70XDicCB5Y=", "dev": true, "requires": { "inherits": "*", "tap-results": "0.x", "yamlish": "*" } }, "tap-results": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/tap-results/-/tap-results-0.0.2.tgz", "integrity": "sha1-oSTf56S2YnnG9lrtxU7Fl3RkJos=", "dev": true, "requires": { "inherits": "~1.0.0" }, "dependencies": { "inherits": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/inherits/-/inherits-1.0.2.tgz", "integrity": "sha1-ykMJ2t7mtUzAuNJH6NfHoJdb3Js=", "dev": true } } }, "traverse": { "version": "0.6.6", "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.6.6.tgz", "integrity": "sha1-y99WD9e5r2MlAv7UD5GMFX6pcTc=", "dev": true }, "tweetnacl": { "version": "0.14.5", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=" }, "uglify-js": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-1.1.1.tgz", "integrity": "sha1-7nGpfEzv0GoamyBDfzQRiYKqA1s=", "dev": true }, "uuid": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/uuid/-/uuid-2.0.3.tgz", "integrity": "sha1-Z+LoY3lyFVMN/zGOW/nc6/1Hsho=", "dev": true }, "verror": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "requires": { "assert-plus": "^1.0.0", "core-util-is": "1.0.2", "extsprintf": "^1.2.0" } }, "yamlish": { "version": "0.0.7", "resolved": "https://registry.npmjs.org/yamlish/-/yamlish-0.0.7.tgz", "integrity": "sha1-tK+aHcxjYYhzw9bkUewyE8OaV/s=", "dev": true } } } node-http-signature-1.3.6/package.json000066400000000000000000000016341414525571300177230ustar00rootroot00000000000000{ "name": "http-signature", "description": "Reference implementation of Joyent's HTTP Signature scheme.", "version": "1.3.6", "license": "MIT", "author": "Joyent, Inc", "contributors": [ "Mark Cavage ", "David I. Lehn ", "Patrick Mooney " ], "repository": { "type": "git", "url": "git://github.com/joyent/node-http-signature.git" }, "homepage": "https://github.com/joyent/node-http-signature/", "bugs": "https://github.com/joyent/node-http-signature/issues", "keywords": [ "https", "request" ], "engines": { "node": ">=0.10" }, "main": "lib/index.js", "files": [ "lib" ], "scripts": { "test": "tap test/*.js" }, "dependencies": { "assert-plus": "^1.0.0", "jsprim": "^2.0.2", "sshpk": "^1.14.1" }, "devDependencies": { "tap": "0.4.2", "uuid": "^2.0.2" } } node-http-signature-1.3.6/test/000077500000000000000000000000001414525571300164105ustar00rootroot00000000000000node-http-signature-1.3.6/test/convert.test.js000066400000000000000000000136421414525571300214120ustar00rootroot00000000000000// Copyright 2011 Joyent, Inc. All rights reserved. var test = require('tap').test; var sshKeyFingerprint = require('../lib/index').sshKeyFingerprint; var sshKeyToPEM = require('../lib/index').sshKeyToPEM; var pemToRsaSSHKey = require('../lib/index').pemToRsaSSHKey; ///--- Globals var SSH_1024 = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAIEAvad19ePSDckmgmo6Unqmd8' + 'n2G7o1794VN3FazVhV09yooXIuUhA+7OmT7ChiHueayxSubgL2MrO/HvvF/GGVUs/t3e0u4' + '5YwRC51EVhyDuqthVJWjKrYxgDMbHru8fc1oV51l0bKdmvmJWbA/VyeJvstoX+eiSGT3Jge' + 'egSMVtc= mark@foo.local'; var PEM_1024 = '-----BEGIN PUBLIC KEY-----\n' + 'MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQC9p3X149INySaCajpSeqZ3yfYb\n' + 'ujXv3hU3cVrNWFXT3Kihci5SED7s6ZPsKGIe55rLFK5uAvYys78e+8X8YZVSz+3d\n' + '7S7jljBELnURWHIO6q2FUlaMqtjGAMxseu7x9zWhXnWXRsp2a+YlZsD9XJ4m+y2h\n' + 'f56JIZPcmB56BIxW1wIBIw==\n' + '-----END PUBLIC KEY-----\n'; var SSH_2048 = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr+isTwMYqwCAcY0Yb2F0pF' + '+/F4/wxGzcrLR2PrgoBXwjj/TnEA3tJ7v08Rru3lAd/O59B6TbXOsYbQ+2Syd82Dm8L3SJR' + 'NlZJ6DZUOAwnTOoNgkfH2CsbGS84aTPTeXjmMsw52GvQ9yWFDUglHzMIzK2iSHWNl1dAaBE' + 'iddifGmrpUTPJ5Tt7l8YS4jdaBf6klS+3CvL6xET/RjZhKGtrrgsRRYUB2XVtgQhKDu7PtD' + 'dlpy4+VISdVhZSlXFnBhya/1KxLS5UFHSAdOjdxzW1bh3cPzNtuPXZaiWUHvyIWpGVCzj5N' + 'yeDXcc7n0E20yx9ZDkAITuI8X49rnQzuCN5Q== mark@bluesnoop.local'; var PEM_2048 = '-----BEGIN PUBLIC KEY-----\n' + 'MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEAr+isTwMYqwCAcY0Yb2F0\n' + 'pF+/F4/wxGzcrLR2PrgoBXwjj/TnEA3tJ7v08Rru3lAd/O59B6TbXOsYbQ+2Syd8\n' + '2Dm8L3SJRNlZJ6DZUOAwnTOoNgkfH2CsbGS84aTPTeXjmMsw52GvQ9yWFDUglHzM\n' + 'IzK2iSHWNl1dAaBEiddifGmrpUTPJ5Tt7l8YS4jdaBf6klS+3CvL6xET/RjZhKGt\n' + 'rrgsRRYUB2XVtgQhKDu7PtDdlpy4+VISdVhZSlXFnBhya/1KxLS5UFHSAdOjdxzW\n' + '1bh3cPzNtuPXZaiWUHvyIWpGVCzj5NyeDXcc7n0E20yx9ZDkAITuI8X49rnQzuCN\n' + '5QIBIw==\n' + '-----END PUBLIC KEY-----\n'; var SSH_4096 = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAsWUdvcKBBjW4GJ8Uyo0S8U' + 'FFZbg5bqeRWPHcR2eIbo/k7M54PmWFqNL3YCIR8cRsvsFuYObnVaY01p1p/9+tpN4ezaHS5' + '9glhADTSva3uLrYuWA1FCKFi6/rXn9WkM5diSVrrTXzaQE8ZsVRA5QG6AeWhC3x/HNbiJOG' + 'd9u0xrzYnyjrhO6x7eCnSz/AtNURLyWHbZ9Q0VEY5UVQsfAmmAAownMTth1m7KRG/KgM1Oz' + '9Dc+IUHYf0pjxFLQVQgqPnOLsj8OIJEt9SbZR33n66UJezbsbm0uJ+ophA3W/OacvHzCmoL' + 'm9PaCwYEZ2pIlYlhkGGu6CFpfXhYUne61WAV8xR8pDXaIL7BqLRJZKlxPzrg9Iu278V9XeL' + 'CnandXIGpaKwC5p7N/K6JoLB+nI1xd4X1NIftaBouxmYTXJy1VK2DKkD+KyvUPtN7EXnC4G' + 'E4eDn9nibIj35GjfiDXrxcPPaJhSVzqvIIt55XcAnUEEVtiKtxICKwTSbvsojML5hL/gdeu' + 'MWnMxj1nsZzTgSurD2OFaQ22k5HGu9aC+duNvvgjXWou7BsS/vH1QbP8GbIvYKlO5xNIj9z' + 'kjINP3nCX4K1+IpW3PDkgS/DleUhUlvhxb10kc4af+9xViAGkV71WqNcoY+PAETvEbDbYpg' + 'VEBd4mwFJLl/DT2Nlbj9q0= mark@bluesnoop.local'; var PEM_4096 = '-----BEGIN PUBLIC KEY-----\n' + 'MIICIDANBgkqhkiG9w0BAQEFAAOCAg0AMIICCAKCAgEAsWUdvcKBBjW4GJ8Uyo0S\n' + '8UFFZbg5bqeRWPHcR2eIbo/k7M54PmWFqNL3YCIR8cRsvsFuYObnVaY01p1p/9+t\n' + 'pN4ezaHS59glhADTSva3uLrYuWA1FCKFi6/rXn9WkM5diSVrrTXzaQE8ZsVRA5QG\n' + '6AeWhC3x/HNbiJOGd9u0xrzYnyjrhO6x7eCnSz/AtNURLyWHbZ9Q0VEY5UVQsfAm\n' + 'mAAownMTth1m7KRG/KgM1Oz9Dc+IUHYf0pjxFLQVQgqPnOLsj8OIJEt9SbZR33n6\n' + '6UJezbsbm0uJ+ophA3W/OacvHzCmoLm9PaCwYEZ2pIlYlhkGGu6CFpfXhYUne61W\n' + 'AV8xR8pDXaIL7BqLRJZKlxPzrg9Iu278V9XeLCnandXIGpaKwC5p7N/K6JoLB+nI\n' + '1xd4X1NIftaBouxmYTXJy1VK2DKkD+KyvUPtN7EXnC4GE4eDn9nibIj35GjfiDXr\n' + 'xcPPaJhSVzqvIIt55XcAnUEEVtiKtxICKwTSbvsojML5hL/gdeuMWnMxj1nsZzTg\n' + 'SurD2OFaQ22k5HGu9aC+duNvvgjXWou7BsS/vH1QbP8GbIvYKlO5xNIj9zkjINP3\n' + 'nCX4K1+IpW3PDkgS/DleUhUlvhxb10kc4af+9xViAGkV71WqNcoY+PAETvEbDbYp\n' + 'gVEBd4mwFJLl/DT2Nlbj9q0CASM=\n' + '-----END PUBLIC KEY-----\n'; var DSA_1024 = 'ssh-dss AAAAB3NzaC1kc3MAAACBAKK5sckoM05sOPajUcTWG0zPTvyRmj6' + 'YQ1g2IgezUUrXgY+2PPy07+JrQi8SN9qr/CBP+0q0Ec48qVFf9LlkUBwu9Jf5HTUVNiKNj3c' + 'SRPFH8HqZn+nxhVsOLhnHWxgDQ8OOm48Ma61NcYVo2B0Ne8cUs8xSqLqba2EG9ze87FQZAAA' + 'AFQCVP/xpiAofZRD8L4QFwxOW9krikQAAAIACNv0EmKr+nIA13fjhpiqbYYyVXYOiWM4cmOD' + 'G/d1J8/vR4YhWHWPbAEw7LD0DEwDIHLlRZr/1jsHbFcwt4tzRs95fyHzpucpGhocmjWx43qt' + 'xEhDeJrxPlkIXHakciAEhoo+5YeRSSgRse5PrZDosdr5fA+DADs8tnto5Glf5owAAAIBHcEF' + '5ytvCRiKbsWKOgeMZ7JT/XGX+hMhS7aaJ2IspKj7YsWada1yBwoM6yYHtlpnGsq/PoPaZU8K' + '40f47psV6OhSh+/O/jgqLS/Ur2c0mQQqIb7vvkc7he/SPOQAqyDmyYFBuazuSf2s9Uy2hfvj' + 'Wgb6X+vN9W8SOb2668IL7Vg== mark@bluesnoop.local'; var DSA_1024_PEM = '-----BEGIN PUBLIC KEY-----\n' + 'MIIBtjCCASsGByqGSM44BAEwggEeAoGBAKK5sckoM05sOPajUcTWG0zPTvyRmj6Y\n' + 'Q1g2IgezUUrXgY+2PPy07+JrQi8SN9qr/CBP+0q0Ec48qVFf9LlkUBwu9Jf5HTUV\n' + 'NiKNj3cSRPFH8HqZn+nxhVsOLhnHWxgDQ8OOm48Ma61NcYVo2B0Ne8cUs8xSqLqb\n' + 'a2EG9ze87FQZAhUAlT/8aYgKH2UQ/C+EBcMTlvZK4pECgYACNv0EmKr+nIA13fjh\n' + 'piqbYYyVXYOiWM4cmODG/d1J8/vR4YhWHWPbAEw7LD0DEwDIHLlRZr/1jsHbFcwt\n' + '4tzRs95fyHzpucpGhocmjWx43qtxEhDeJrxPlkIXHakciAEhoo+5YeRSSgRse5Pr\n' + 'ZDosdr5fA+DADs8tnto5Glf5owOBhAACgYBHcEF5ytvCRiKbsWKOgeMZ7JT/XGX+\n' + 'hMhS7aaJ2IspKj7YsWada1yBwoM6yYHtlpnGsq/PoPaZU8K40f47psV6OhSh+/O/\n' + 'jgqLS/Ur2c0mQQqIb7vvkc7he/SPOQAqyDmyYFBuazuSf2s9Uy2hfvjWgb6X+vN9\n' + 'W8SOb2668IL7Vg==\n' + '-----END PUBLIC KEY-----\n'; ///--- Tests test('1024b pem to rsa ssh key', function(t) { t.equal(pemToRsaSSHKey(PEM_1024, 'mark@foo.local'), SSH_1024); t.end(); }); test('2048b pem to rsa ssh key', function(t) { t.equal(pemToRsaSSHKey(PEM_2048, 'mark@bluesnoop.local'), SSH_2048); t.end(); }); test('4096b pem to rsa ssh key', function(t) { t.equal(pemToRsaSSHKey(PEM_4096, 'mark@bluesnoop.local'), SSH_4096); t.end(); }); test('1024b rsa ssh key', function(t) { t.equal(sshKeyToPEM(SSH_1024), PEM_1024); t.end(); }); test('2048b rsa ssh key', function(t) { t.equal(sshKeyToPEM(SSH_2048), PEM_2048); t.end(); }); test('4096b rsa ssh key', function(t) { t.equal(sshKeyToPEM(SSH_4096), PEM_4096); t.end(); }); test('1024b dsa ssh key', function(t) { t.equal(sshKeyToPEM(DSA_1024), DSA_1024_PEM); t.end(); }); test('fingerprint', function(t) { var fp = sshKeyFingerprint(SSH_1024); t.equal(fp, '59:a4:61:0e:38:18:9f:0f:28:58:2a:27:f7:65:c5:87'); t.end(); }); node-http-signature-1.3.6/test/dsa_private.pem000066400000000000000000000012341414525571300214140ustar00rootroot00000000000000-----BEGIN DSA PRIVATE KEY----- MIIBuwIBAAKBgQDRBrsnNTsXWPAxsrSN7lUXgNHxFvegOa+OYf0ey2UiraalRtED CZOAWrleA2CzZO/zHee5K+lXSnQcpd/otwVL9tJqr+jDY/EHdglSOsbehWwOk9WX hbhQnc80RlO5J0ajALA5C80UeTOeBPNNzpJ8SRrYffYWBYJziqT9+AI5/wIVAKYR aHdyrbMpLDUbQNFgZ1GC7OG1AoGAQBdNIO+rotPYOLCSfnQq5wyUaxhzsx/KF7bl R7ryJje+HuUGrKfqnmUnQvUmPsrcEH4PZYlfoEOxWJqX8sMZu5ip/jZ1E62kmUN/ beg/GE16j0CuhVTUh8t1NSyc1NLMZb5zHbbR3gyQZVdHGWyos9cO8njIoTvjzVD0 s5XmjyQCgYBGdoKyqTWjFY1Ab7cGW1acImtpuQyDiuiJntTQbDyhxXirf5vpw3jd cnVAxIKMCqYEvISBWxzdi0r2ICOXp/cVfDEGt78GI0C0qpHIFUCGS8mWH2y294+n PrF2dOKORssEtpuFU4ifCNuOo/ovgq6zEK69vwYazKCiWPeQQ/2gbgIVAIFFq/st tPr/+Kzq2rK0lbJRJcvb -----END DSA PRIVATE KEY----- node-http-signature-1.3.6/test/dsa_public.pem000066400000000000000000000012161414525571300212200ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIIBtjCCASsGByqGSM44BAEwggEeAoGBANEGuyc1OxdY8DGytI3uVReA0fEW96A5 r45h/R7LZSKtpqVG0QMJk4BauV4DYLNk7/Md57kr6VdKdByl3+i3BUv20mqv6MNj 8Qd2CVI6xt6FbA6T1ZeFuFCdzzRGU7knRqMAsDkLzRR5M54E803OknxJGth99hYF gnOKpP34Ajn/AhUAphFod3KtsyksNRtA0WBnUYLs4bUCgYBAF00g76ui09g4sJJ+ dCrnDJRrGHOzH8oXtuVHuvImN74e5Qasp+qeZSdC9SY+ytwQfg9liV+gQ7FYmpfy wxm7mKn+NnUTraSZQ39t6D8YTXqPQK6FVNSHy3U1LJzU0sxlvnMdttHeDJBlV0cZ bKiz1w7yeMihO+PNUPSzleaPJAOBhAACgYBGdoKyqTWjFY1Ab7cGW1acImtpuQyD iuiJntTQbDyhxXirf5vpw3jdcnVAxIKMCqYEvISBWxzdi0r2ICOXp/cVfDEGt78G I0C0qpHIFUCGS8mWH2y294+nPrF2dOKORssEtpuFU4ifCNuOo/ovgq6zEK69vwYa zKCiWPeQQ/2gbg== -----END PUBLIC KEY----- node-http-signature-1.3.6/test/ecdsa_private.pem000066400000000000000000000003431414525571300217240ustar00rootroot00000000000000-----BEGIN EC PRIVATE KEY----- MHcCAQEEICEEsq6Rxv0c5nUIA0w6QuhGeDSo6uuJ3bPMr6LLwLFIoAoGCCqGSM49 AwEHoUQDQgAEvqAkfJTX8Ai2HOpazSfZWi5OcAkTak7abkqD3E8CgZSfKZN2WJhT lREUjk10KhAOPkUqJMhaJ65kFNBE4Py/xw== -----END EC PRIVATE KEY----- node-http-signature-1.3.6/test/ecdsa_public.pem000066400000000000000000000002621414525571300215300ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvqAkfJTX8Ai2HOpazSfZWi5OcAkT ak7abkqD3E8CgZSfKZN2WJhTlREUjk10KhAOPkUqJMhaJ65kFNBE4Py/xw== -----END PUBLIC KEY----- node-http-signature-1.3.6/test/examples.test.js000066400000000000000000000127421414525571300215500ustar00rootroot00000000000000// Copyright 2015 Joyent, Inc. All rights reserved. var fs = require('fs'); var path = require('path'); var http = require('http'); var sshpk = require('sshpk'); var assert = require('assert-plus'); var test = require('tap').test; var uuid = require('uuid'); var httpSignature = require('../lib/index'); var doc; var privKey, pubKey; var httpReqData; var signs = []; var httpReq; test('read in doc', function (t) { doc = fs.readFileSync(path.join(__dirname, '..', 'http_signing.md')); if (Buffer.isBuffer(doc)) doc = doc.toString('utf-8'); doc = doc.split('\n'); t.end(); }); test('find keys and examples', function (t) { var i = 0; for (; i < doc.length; ++i) if (/^# Appendix A/.test(doc[i])) break; if (i >= doc.length) t.fail('could not find appendix A') var pubKeyLines = []; for (; i < doc.length; ++i) if (/-BEGIN PUBLIC KEY-/.test(doc[i])) break; for (; i < doc.length; ++i) { pubKeyLines.push(doc[i]); if (/-END PUBLIC KEY-/.test(doc[i])) break; } pubKey = sshpk.parseKey(pubKeyLines. map(function (l) { return (l.replace(/^ /g, '')); }). join('\n')); var privKeyLines = []; for (; i < doc.length; ++i) if (/-BEGIN RSA PRIVATE KEY-/.test(doc[i])) break; for (; i < doc.length; ++i) { privKeyLines.push(doc[i]); if (/-END RSA PRIVATE KEY-/.test(doc[i])) break; } privKey = sshpk.parsePrivateKey(privKeyLines. map(function (l) { return (l.replace(/^ /g, '')); }). join('\n')); var reqLines = []; for (; i < doc.length; ++i) if (doc[i] === '') break; for (++i; i < doc.length; ++i) { if (doc[i] === '') break; reqLines.push(doc[i]); } httpReqData = reqLines. map(function (l) { return (l.replace(/^ /g, '')); }). join('\r\n'); var thisConfig; var lines; do { thisConfig = {}; for (; i < doc.length; ++i) { var m = doc[i].match(/^$/); if (m && m[1]) { thisConfig = JSON.parse(m[1]); break; } } for (; i < doc.length; ++i) if (doc[i] === '') break; lines = []; for (++i; i < doc.length; ++i) { if (doc[i] === '') break; if (doc[i].length > 0) lines.push(doc[i]); } thisConfig.signString = lines. map(function (l) { return (l.replace(/^ /g, '')); }). join('\n'); for (; i < doc.length; ++i) if (doc[i] === '') break; lines = []; for (++i; i < doc.length; ++i) { if (doc[i] === '') break; if (doc[i].length > 0) lines.push(doc[i]); } thisConfig.authz = lines. map(function (l) { return (l.replace(/^ /g, '')); }). join('\n'); if (thisConfig.name) signs.push(thisConfig); } while (i < doc.length); t.end(); }); /* * This is horrible, and depends on a totally private node.js interface. But * it's better than trying to write our own HTTP parser... I hope. This * interface has been pretty stable in practice, with minimal change from * 0.8 through to 4.2. */ var binding, HTTPParser, kOnHeadersComplete, methods; if (process.binding) binding = process.binding('http_parser'); if (binding) HTTPParser = binding.HTTPParser; if (HTTPParser) kOnHeadersComplete = HTTPParser.kOnHeadersComplete; if (HTTPParser && HTTPParser.methods) methods = HTTPParser.methods; else methods = ['DELETE', 'GET', 'HEAD', 'POST', 'PUT']; function DummyRequest() { } DummyRequest.prototype.getHeader = function (h) { return (this.headers[h.toLowerCase()]); }; DummyRequest.prototype.setHeader = function (h, v) { this.headers[h.toLowerCase()] = v; }; function parseHttpRequest(data, cb) { var p = new HTTPParser(); var obj = new DummyRequest(); p[kOnHeadersComplete] = onHeadersComplete; function onHeadersComplete(opts) { var versionMajorKey = 'versionMajor'; var versionMinorKey = 'versionMinor'; var headersKey = 'headers'; var urlKey = 'url'; var methodKey = 'method'; var upgradeKey = 'upgrade'; if (!(typeof opts === 'object')) { opts = [].slice.call(arguments); versionMajorKey = 0; versionMinorKey = "1"; headersKey = "2"; urlKey = "4"; methodKey = "3"; upgradeKey = "7"; } obj.httpVersionMajor = opts[versionMajorKey]; obj.httpVersionMinor = opts[versionMinorKey]; obj.httpVersion = obj.httpVersionMajor + '.' + obj.httpVersionMinor; obj.rawHeaders = opts[headersKey]; obj.headers = {}; for (var i = 0; i < obj.rawHeaders.length; i += 2) { var k = obj.rawHeaders[i].toLowerCase(); var v = obj.rawHeaders[i+1]; obj.headers[k] = v; } obj.url = opts[urlKey]; obj.path = opts[urlKey]; obj.method = methods[opts[methodKey]]; obj.upgrade = opts[upgradeKey]; assert.ok(obj.httpVersion); cb(obj); } p.execute(new Buffer(data)); } if (binding && HTTPParser && kOnHeadersComplete) { test('parse http request', function (t) { parseHttpRequest(httpReqData, function (req) { httpReq = req; t.end(); }); }); test('setup configs', function (t) { signs.forEach(function (sign) { test('example in "' + sign.name + '"', testSignConfig.bind(this, sign)); }); t.end(); }); function testSignConfig(config, t) { var opts = config.options; opts.key = privKey; delete (httpReq.headers['authorization']); httpReq._stringToSign = null; t.ok(httpSignature.signRequest(httpReq, opts)); var authz = 'Authorization: ' + httpReq.headers['authorization']; t.strictEqual(config.authz, authz); t.strictEqual(typeof (httpReq._stringToSign), 'string'); t.strictEqual(config.signString, httpReq._stringToSign); t.end(); } } node-http-signature-1.3.6/test/header.test.js000066400000000000000000000035021414525571300211540ustar00rootroot00000000000000// Copyright 2015 Joyent, Inc. All rights reserved. var crypto = require('crypto'); var fs = require('fs'); var http = require('http'); var test = require('tap').test; var uuid = require('uuid'); var httpSignature = require('../lib/index'); ///--- Globals var hmacKey = null; var httpOptions = null; var rsaPrivate = null; var signOptions = null; var server = null; var socket = null; ///--- Tests test('setup', function(t) { rsaPrivate = fs.readFileSync(__dirname + '/rsa_private.pem', 'ascii'); t.ok(rsaPrivate); socket = '/tmp/.' + uuid(); server = http.createServer(function(req, res) { res.writeHead(200); res.end(); }); server.listen(socket, function() { hmacKey = uuid(); httpOptions = { socketPath: socket, path: '/', method: 'HEAD', headers: { 'content-length': '0', 'x-foo': 'false' } }; signOptions = { key: rsaPrivate, keyId: 'unitTest', }; t.end(); }); }); test('header with 0 value', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', 'request-line', 'content-length'] }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('header with boolean-mungable value', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', 'x-foo'] }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('tear down', function(t) { server.on('close', function() { t.end(); }); server.close(); }); node-http-signature-1.3.6/test/parser.test.js000066400000000000000000000502671414525571300212320ustar00rootroot00000000000000// Copyright 2011 Joyent, Inc. All rights reserved. var http = require('http'); var test = require('tap').test; var uuid = require('uuid'); var jsprim = require('jsprim'); var httpSignature = require('../lib/index'); ///--- Globals var options = null; var server = null; var socket = null; ///--- Tests test('setup', function(t) { socket = '/tmp/.' + uuid(); options = { socketPath: socket, path: '/', headers: {} }; server = http.createServer(function(req, res) { server.tester(req, res); }); server.listen(socket, function() { t.end(); }); }); test('no authorization', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'MissingHeaderError'); } res.writeHead(200); res.end(); }; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('bad scheme', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'scheme was not "Signature"'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Basic blahBlahBlah'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('no key id', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'keyId was not specified'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature foo'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('key id no value', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'keyId was not specified'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId='; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('key id no quotes', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId=foo,algorithm=hmac-sha1,signature=aabbcc'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('key id param quotes', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature "keyId"="key"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('param name with space', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature key Id="key"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('no algorithm', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'algorithm was not specified'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('algorithm no value', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'algorithm was not specified'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm='; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('no signature', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'signature was not specified'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm="foo"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid algorithm', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'InvalidParamsError'); t.equal(e.message, 'foo is not supported'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm="foo",signature="aaabbbbcccc"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('no date header', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'MissingHeaderError'); t.equal(e.message, 'date was not in the request'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm="rsa-sha256",signature="aaabbbbcccc"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid numeric parameter', function(t) { server.tester = function(req, res) { var options = { headers: ['(created)', 'digest'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.fail(e.stack); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=123456,' + 'headers="(created) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid numeric parameter', function(t) { server.tester = function(req, res) { var options = { headers: ['(created)', 'digest'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); res.writeHead(200); res.end(); return; } t.fail("should throw error"); res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=123@456,' + 'headers="(created) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid numeric parameter - decimal', function(t) { server.tester = function(req, res) { var options = { headers: ['(created)', 'digest'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); res.writeHead(200); res.end(); return; } t.fail("should throw error"); res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=123.456,' + 'headers="(created) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid numeric parameter - signed integer', function(t) { server.tester = function(req, res) { var options = { headers: ['(created)', 'digest'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'InvalidHeaderError'); t.equal(e.message, 'bad param format'); res.writeHead(200); res.end(); return; } t.fail("should throw error"); res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=-123456,' + 'headers="(created) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('created in future', function(t) { var skew = 1000; server.tester = function(req, res) { var options = { headers: ['(created)', 'digest'], clockSkew: skew }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'ExpiredRequestError'); t.similar(e.message, new RegExp('Created lies in the future.*')); res.writeHead(200); res.end(); return; } t.fail("should throw error"); res.writeHead(200); res.end(); }; var created = Math.floor(Date.now() / 1000) + skew + 10; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=' + created + ',' + 'headers="(created) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('expires expired', function(t) { var skew = 1000; server.tester = function(req, res) { var options = { headers: ['(expires)', 'digest'], clockSkew: skew }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'ExpiredRequestError'); t.similar(e.message, new RegExp('Request expired.*')); res.writeHead(200); res.end(); return; } t.fail("should throw error"); res.writeHead(200); res.end(); }; var expires = Math.floor(Date.now() / 1000) - skew - 1; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'expires=' + expires + ',' + 'headers="(expires) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid created and expires with skew', function(t) { var skew = 1000; server.tester = function(req, res) { var options = { headers: ['(created)', '(expires)', 'digest'], clockSkew: skew }; try { httpSignature.parseRequest(req, options); } catch (e) { t.fail(e.stack); } res.writeHead(200); res.end(); }; //created is in the future but within allowed skew var created = Math.floor(Date.now() / 1000) + skew - 1; //expires is in the past but within allowed skew var expires = Math.floor(Date.now() / 1000) - skew + 10; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'created=' + created + ',' + 'expires=' + expires + ',' + 'headers="(created) (expires) dIgEsT",signature="digitalSignature"'; options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid default headers', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.fail(e.stack); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm="rsa-sha256",signature="aaabbbbcccc"'; options.headers.Date = jsprim.rfc1123(new Date()); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid custom authorizationHeaderName', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req, { authorizationHeaderName: 'x-auth' }); } catch (e) { t.fail(e.stack); } res.writeHead(200); res.end(); }; options.headers['x-auth'] = 'Signature keyId="foo",algorithm="rsa-sha256",signature="aaabbbbcccc"'; options.headers.Date = jsprim.rfc1123(new Date()); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('explicit headers missing', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'MissingHeaderError'); t.equal(e.message, 'digest was not in the request'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="foo",algorithm="rsa-sha256",' + 'headers="date digest",signature="aaabbbbcccc"'; options.headers.Date = jsprim.rfc1123(new Date()); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid explicit headers request-line', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Authorization = 'Signature keyId="fo,o",algorithm="RSA-sha256",' + 'headers="dAtE dIgEsT request-line",' + 'extensions="blah blah",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); var body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { console.log(body); var parsed = JSON.parse(body); t.ok(parsed); t.equal(parsed.scheme, 'Signature'); t.ok(parsed.params); t.equal(parsed.params.keyId, 'fo,o'); t.equal(parsed.params.algorithm, 'rsa-sha256'); t.equal(parsed.params.extensions, 'blah blah'); t.ok(parsed.params.headers); t.equal(parsed.params.headers.length, 3); t.equal(parsed.params.headers[0], 'date'); t.equal(parsed.params.headers[1], 'digest'); t.equal(parsed.params.headers[2], 'request-line'); t.equal(parsed.params.signature, 'digitalSignature'); t.ok(parsed.signingString); t.equal(parsed.signingString, ('date: ' + options.headers.Date + '\n' + 'digest: ' + options.headers['digest'] + '\n' + 'GET / HTTP/1.1')); t.equal(parsed.params.keyId, parsed.keyId); t.equal(parsed.params.algorithm.toUpperCase(), parsed.algorithm); t.end(); }); }); }); test('valid explicit headers request-line strict true', function(t) { server.tester = function(req, res) { try { httpSignature.parseRequest(req, {strict: true}); } catch (e) { t.equal(e.name, 'StrictParsingError'); t.equal(e.message, 'request-line is not a valid header with strict parsing enabled.'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="fo,o",algorithm="RSA-sha256",' + 'headers="dAtE dIgEsT request-line",' + 'extensions="blah blah",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid explicit headers request-target', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Authorization = 'Signature keyId="fo,o",algorithm="RSA-sha256",' + 'headers="dAtE dIgEsT (request-target)",' + 'extensions="blah blah",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); var body = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); res.on('end', function() { console.log(body); var parsed = JSON.parse(body); t.ok(parsed); t.equal(parsed.scheme, 'Signature'); t.ok(parsed.params); t.equal(parsed.params.keyId, 'fo,o'); t.equal(parsed.params.algorithm, 'rsa-sha256'); t.equal(parsed.params.extensions, 'blah blah'); t.ok(parsed.params.headers); t.equal(parsed.params.headers.length, 3); t.equal(parsed.params.headers[0], 'date'); t.equal(parsed.params.headers[1], 'digest'); t.equal(parsed.params.headers[2], '(request-target)'); t.equal(parsed.params.signature, 'digitalSignature'); t.ok(parsed.signingString); t.equal(parsed.signingString, ('date: ' + options.headers.Date + '\n' + 'digest: ' + options.headers['digest'] + '\n' + '(request-target): get /')); t.equal(parsed.params.keyId, parsed.keyId); t.equal(parsed.params.algorithm.toUpperCase(), parsed.algorithm); t.end(); }); }); }); test('expired', function(t) { server.tester = function(req, res) { var options = { clockSkew: 1, headers: ['date'] }; setTimeout(function() { try { httpSignature.parseRequest(req); } catch (e) { t.equal(e.name, 'ExpiredRequestError'); t.ok(/clock skew of \d\.\d+s was greater than 1s/.test(e.message)); } res.writeHead(200); res.end(); }, 1200); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'headers="dAtE dIgEsT",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('missing required header', function(t) { server.tester = function(req, res) { var options = { clockSkew: 1, headers: ['date', 'x-unit-test'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal(e.name, 'MissingHeaderError'); t.equal(e.message, 'x-unit-test was not a signed header'); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'headers="dAtE cOntEnt-MD5",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['content-md5'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid mixed case headers', function(t) { server.tester = function(req, res) { var options = { clockSkew: 1, headers: ['Date', 'Content-MD5'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.fail(e.stack); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'headers="dAtE cOntEnt-MD5",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['content-md5'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('not whitelisted algorithm', function(t) { server.tester = function(req, res) { var options = { clockSkew: 1, algorithms: ['rsa-sha1'] }; try { httpSignature.parseRequest(req, options); } catch (e) { t.equal('InvalidParamsError', e.name); t.equal('rsa-sha256 is not a supported algorithm', e.message); } res.writeHead(200); res.end(); }; options.headers.Authorization = 'Signature keyId="f,oo",algorithm="RSA-sha256",' + 'headers="dAtE dIgEsT",signature="digitalSignature"'; options.headers.Date = jsprim.rfc1123(new Date()); options.headers['digest'] = uuid(); http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('tearDown', function(t) { server.on('close', function() { t.end(); }); server.close(); }); node-http-signature-1.3.6/test/rsa_private.pem000066400000000000000000000015731414525571300214400ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u 412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI 7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== -----END RSA PRIVATE KEY----- node-http-signature-1.3.6/test/rsa_private_encrypted.pem000066400000000000000000000020621414525571300235070ustar00rootroot00000000000000-----BEGIN ENCRYPTED PRIVATE KEY----- MIIC3TBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQISkT2UHxhpiUCAggA MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBBjoylMNYUwmXeqkoJYzJdOBIIC gMi4cPwI9yUYb1MTSC067Qp8dlamntAD+T4Ol3rfx8qEU0hDawWkpmroZGzh8USb uHpDTLx0yPlxEw262Ismx1xsrRH1nhu3PvDi0KC50Qgn3+W3tqYjUmNCt4dFSk9l i7MgpvPHzVaUWryE5TK2iWKW5/QWfJ0FMXS+vzDOdmALaYhiQ2qAwZzyB4DLUFQE zAy2k1EttkJjkXG/MHkGMJ0uJWD+SCfdi9PykFswNk2Ew4EvGVEKL8/1RTaLFezQ 3llS4o1TaLPsPawiAZcLNAeS1dvOpikBiDSidMb3dXatjBV19uYYXd5KzJQ1jlq6 hD6K6dStqekk+TGamsQr2XBf9nsn/n60c05IVogDBDhewaLpjh+tSew0iBHrG6z0 z7//kyjx5v8HzqTZ/7VErTkef4scnnWLQ+/uzgK2RgBIakgxWZz2/0zN/8MhoM/B 7Es8rkB1yjDFUwaNFcjaaTMkb2++CA8PuUxKNXiGEmQ3nylT3WL9kO+fllyNG4M+ WwaPDMQAsW02f+I51Jm3LB8QycQKsyHL6Ran35aAFrF3ANsf6dzp3oIcQpdt1j1y pTWQwQ+8GlP5lTtQMdzyH+3HE/HpgkgaAMuYFfK6afByE9X8Br11S7pmZ60v0kzK 75RDwYo2m8zBLF3hQslSvNHJIDQ9u3KgdOz7xeqoMaKLSUF0JfoGNbT8qq09zE2A 2dtrwsNxA0O7jHURgvhl/SjlW0bg6fRqfKD6d8oDY085mq5N02wx1Rx9b3MLi6ok wW6cELTZy3C+NdMgA6EqYAvn4iH+tXoLKKdAMlAPu5ari6wXF9TjctjYE6NNzGcp B9AZhX+7Y9hSe5CFSIF6DE4= -----END ENCRYPTED PRIVATE KEY----- node-http-signature-1.3.6/test/rsa_public.pem000066400000000000000000000004201414525571300212320ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6 Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw oYi+1hqp1fIekaxsyQIDAQAB -----END PUBLIC KEY----- node-http-signature-1.3.6/test/rsa_public_encrypted.pem000066400000000000000000000004201414525571300233070ustar00rootroot00000000000000-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoX3N2q0OzQjA5tu2LKKtBXbZZ DJjqQzXnFUKOWJc5xo7D8xDWzETOirJLoR6qGf+1rYU+jAyR0YtW9km1wyluzeuM TerUUioeaDGCo1Sq+euSqb6BQH6xdLFaTHlynuSafgjiEsKp0QNcFWyWFrCH+mJF v0YyNiv5QX78asG8VwIDAQAB -----END PUBLIC KEY----- node-http-signature-1.3.6/test/signer.test.js000066400000000000000000000256671414525571300212330ustar00rootroot00000000000000// Copyright 2011 Joyent, Inc. All rights reserved. var crypto = require('crypto'); var fs = require('fs'); var http = require('http'); var sshpk = require('sshpk'); var test = require('tap').test; var uuid = require('uuid'); var httpSignature = require('../lib/index'); ///--- Globals var hmacKey = null; var httpOptions = null; var rsaPrivate = null; var rsaPrivateEncrypted = null; var dsaPrivate = null; var ecdsaPrivate = null; var signOptions = null; var server = null; var socket = null; ///--- Tests test('setup', function(t) { rsaPrivate = fs.readFileSync(__dirname + '/rsa_private.pem', 'ascii'); rsaPrivateEncrypted = fs.readFileSync(__dirname + '/rsa_private_encrypted.pem', 'ascii'); dsaPrivate = fs.readFileSync(__dirname + '/dsa_private.pem', 'ascii'); ecdsaPrivate = fs.readFileSync(__dirname + '/ecdsa_private.pem', 'ascii'); t.ok(rsaPrivate); t.ok(rsaPrivateEncrypted); t.ok(dsaPrivate); t.ok(ecdsaPrivate); socket = '/tmp/.' + uuid(); server = http.createServer(function(req, res) { res.writeHead(200); res.end(); }); server.listen(socket, function() { hmacKey = uuid(); httpOptions = { socketPath: socket, path: '/', method: 'GET', headers: {} }; signOptions = { key: rsaPrivate, keyId: 'unitTest' }; t.end(); }); }); test('defaults', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); req._stringToSign = null; t.ok(httpSignature.sign(req, signOptions)); var authz = req.getHeader('Authorization'); t.ok(authz); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*$/)); var key = sshpk.parsePrivateKey(rsaPrivate); var sig = key.createSign().update(req._stringToSign).sign(); t.ok(authz.indexOf(sig.toString()) !== -1); console.log('> ' + authz); req.end(); }); test('with custom authorizationHeaderName', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); req._stringToSign = null; var opts = Object.create(signOptions); opts.authorizationHeaderName = 'x-auths'; t.ok(httpSignature.sign(req, opts)); var authz = req.getHeader('x-auths'); t.ok(authz); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*$/)); var key = sshpk.parsePrivateKey(rsaPrivate); var sig = key.createSign().update(req._stringToSign).sign(); t.ok(authz.indexOf(sig.toString()) !== -1); console.log('> ' + authz); req.end(); }); test('request line strict unspecified', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', 'request-line'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\nGET \/ HTTP\/1.1$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('request line strict false', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', 'request-line'], strict: false }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.ok(!req.hasOwnProperty('_stringToSign')); t.ok(req._stringToSign === undefined); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('request line strict true', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', 'request-line'], strict: true }; t.throws(function() { httpSignature.sign(req, opts) }); req.end(); }); test('request target', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', '(request-target)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(request-target\): get \/$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('keyid', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', '(keyid)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(keyid\): unit$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('signing algorithm', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { algorithm: 'rsa-sha256', keyId: 'unit', key: rsaPrivate, headers: ['date', '(algorithm)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (opts.algorithm), 'string'); t.strictEqual(opts.algorithm, 'rsa-sha256'); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(algorithm\): [^\n]*$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('signing with unspecified algorithm', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, headers: ['date', '(algorithm)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (opts.algorithm), 'string'); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(algorithm\): [^\n]*$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('signing opaque param', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivate, opaque: 'opaque', headers: ['date', '(opaque)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (opts.algorithm), 'string'); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(opaque\): opaque$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('signing with key protected with passphrase', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: rsaPrivateEncrypted, keyPassphrase: '123', headers: ['date', '(algorithm)'] }; req._stringToSign = null; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); t.strictEqual(typeof (opts.algorithm), 'string'); t.strictEqual(typeof (req._stringToSign), 'string'); t.ok(req._stringToSign.match(/^date: [^\n]*\n\(algorithm\): [^\n]*$/)); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('request-target with dsa key', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: dsaPrivate, headers: ['date', '(request-target)'] }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('request-target with ecdsa key', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: ecdsaPrivate, headers: ['date', '(request-target)'] }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('hmac', function(t) { var req = http.request(httpOptions, function(res) { t.end(); }); var opts = { keyId: 'unit', key: uuid(), algorithm: 'hmac-sha1' }; t.ok(httpSignature.sign(req, opts)); t.ok(req.getHeader('Authorization')); console.log('> ' + req.getHeader('Authorization')); req.end(); }); test('createSigner with RSA key', function(t) { var s = httpSignature.createSigner({ keyId: 'foo', key: rsaPrivate, algorithm: 'rsa-sha1' }); s.writeTarget('get', '/'); var date = s.writeDateHeader(); s.sign(function (err, authz) { t.error(err); console.log('> ' + authz); var req = http.request(httpOptions, function(res) { t.end(); }); req.setHeader('date', date); req.setHeader('authorization', authz); req.end(); }); }); test('createSigner with RSA key, auto algo', function(t) { var s = httpSignature.createSigner({ keyId: 'foo', key: rsaPrivate }); s.writeTarget('get', '/'); var date = s.writeDateHeader(); s.sign(function (err, authz) { t.error(err); var req = http.request(httpOptions, function(res) { t.end(); }); req.setHeader('date', date); req.setHeader('authorization', authz); req.end(); }); }); test('createSigner with RSA key, auto algo, passphrase', function(t) { var s = httpSignature.createSigner({ keyId: 'foo', key: rsaPrivateEncrypted, keyPassphrase: '123' }); s.writeTarget('get', '/'); var date = s.writeDateHeader(); s.sign(function (err, authz) { t.error(err); var req = http.request(httpOptions, function(res) { t.end(); }); req.setHeader('date', date); req.setHeader('authorization', authz); req.end(); }); }); test('createSigner with HMAC key', function(t) { var s = httpSignature.createSigner({ keyId: 'foo', key: hmacKey, algorithm: 'hmac-sha256' }); var date = s.writeDateHeader(); s.writeTarget('get', '/'); s.writeHeader('x-some-header', 'bar'); s.sign(function (err, authz) { t.error(err); var req = http.request(httpOptions, function(res) { t.end(); }); req.setHeader('date', date); req.setHeader('authorization', authz); req.setHeader('x-some-header', 'bar'); req.end(); }); }); test('createSigner with sign function', function(t) { var date; var s = httpSignature.createSigner({ sign: function (data, cb) { t.ok(typeof (data) === 'string'); var m = data.match(/^date: (.+)$/); t.ok(m); t.strictEqual(m[1], date); cb(null, { keyId: 'foo', algorithm: 'hmac-sha256', signature: 'fakesig' }); } }); date = s.writeDateHeader(); s.sign(function (err, authz) { t.error(err); t.ok(authz.match(/fakesig/)); var req = http.request(httpOptions, function(res) { t.end(); }); req.setHeader('date', date); req.setHeader('authorization', authz); req.end(); }); }); test('tear down', function(t) { server.on('close', function() { t.end(); }); server.close(); }); node-http-signature-1.3.6/test/verify.test.js000066400000000000000000000362061414525571300212370ustar00rootroot00000000000000// Copyright 2011 Joyent, Inc. All rights reserved. var crypto = require('crypto'); var fs = require('fs'); var http = require('http'); var jsprim = require('jsprim'); var sshpk = require('sshpk'); var test = require('tap').test; var uuid = require('uuid'); var httpSignature = require('../lib/index'); ///--- Globals var hmacKey = null; var rawhmacKey = null; var options = null; var rsaPrivate = null; var rsaPublic = null; var dsaPrivate = null; var dsaPublic = null; var ecdsaPrivate = null; var ecdsaPublic = null; var server = null; var socket = null; ///--- Tests test('setup', function(t) { rsaPrivate = fs.readFileSync(__dirname + '/rsa_private.pem', 'ascii'); dsaPrivate = fs.readFileSync(__dirname + '/dsa_private.pem', 'ascii'); ecdsaPrivate = fs.readFileSync(__dirname + '/ecdsa_private.pem', 'ascii'); t.ok(rsaPrivate); t.ok(dsaPrivate); t.ok(ecdsaPrivate); rsaPublic = fs.readFileSync(__dirname + '/rsa_public.pem', 'ascii'); dsaPublic = fs.readFileSync(__dirname + '/dsa_public.pem', 'ascii'); ecdsaPublic = fs.readFileSync(__dirname + '/ecdsa_public.pem', 'ascii'); t.ok(rsaPublic); t.ok(dsaPublic); t.ok(ecdsaPublic); hmacKey = uuid(); rawhmacKey = crypto.randomBytes(64); socket = '/tmp/.' + uuid(); options = { socketPath: socket, path: '/', headers: {} }; server = http.createServer(function(req, res) { server.tester(req, res); }); server.listen(socket, function() { t.end(); }); }); test('invalid hmac', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(!httpSignature.verifyHMAC(parsed, hmacKey)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); options.headers.Authorization = 'Signature keyId="foo",algorithm="hmac-sha1",signature="' + uuid() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid hmac', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(httpSignature.verifyHMAC(parsed, hmacKey)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); var hmac = crypto.createHmac('sha1', hmacKey); hmac.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="foo",algorithm="hmac-sha1",signature="' + hmac.digest('base64') + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid raw hmac', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(!httpSignature.verifyHMAC(parsed, rawhmacKey)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); options.headers.Authorization = 'Signature keyId="foo",algorithm="hmac-sha1",signature="' + uuid() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid raw hmac', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(httpSignature.verifyHMAC(parsed, rawhmacKey)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); var hmac = crypto.createHmac('sha1', rawhmacKey); hmac.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="foo",algorithm="hmac-sha1",signature="' + hmac.digest('base64') + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid rsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(!httpSignature.verify(parsed, rsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); options.headers.Authorization = 'Signature keyId="foo",algorithm="rsa-sha1",signature="' + uuid() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid rsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(httpSignature.verify(parsed, rsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); var signer = crypto.createSign('RSA-SHA256'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="foo",algorithm="rsa-sha256",signature="' + signer.sign(rsaPrivate, 'base64') + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid dsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(!httpSignature.verify(parsed, dsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); options.headers.Authorization = 'Signature keyId="foo",algorithm="dsa-sha1",signature="' + uuid() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid dsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(httpSignature.verify(parsed, dsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); var key = sshpk.parsePrivateKey(dsaPrivate); var signer = key.createSign('sha256'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="foo",algorithm="dsa-sha256",signature="' + signer.sign().toString() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid ecdsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(!httpSignature.verify(parsed, ecdsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); options.headers.Authorization = 'Signature keyId="foo",algorithm="ecdsa-sha256",signature="' + uuid() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('valid ecdsa', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req); t.ok(httpSignature.verify(parsed, ecdsaPublic)); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.headers.Date = jsprim.rfc1123(new Date()); var key = sshpk.parsePrivateKey(ecdsaPrivate); var signer = key.createSign('sha512'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="foo",algorithm="ecdsa-sha512",signature="' + signer.sign().toString() + '"'; http.get(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); }); test('invalid date', function(t) { server.tester = function(req, res) { t.throws(function() { httpSignature.parseRequest(req); }); res.writeHead(400); res.end(); }; options.method = 'POST'; options.path = '/'; options.headers.host = 'example.com'; // very old, out of valid date range options.headers.Date = 'Sat, 01 Jan 2000 00:00:00 GMT'; var signer = crypto.createSign('RSA-SHA256'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="Test",algorithm="rsa-sha256",signature="' + signer.sign(rsaPrivate, 'base64') + '"'; var req = http.request(options, function(res) { t.equal(res.statusCode, 400); t.end(); }); req.end(); }); // test values from spec for simple test test('valid rsa from spec default', function(t) { server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req, { // this test uses a fixed old date so ignore clock skew clockSkew: Number.MAX_VALUE }); t.ok(httpSignature.verify(parsed, rsaPublic)); // check known signature t.ok(req.headers.authorization === 'Signature keyId="Test",algorithm="rsa-sha256",signature="ATp0r26dbMIxOopqw0OfABDT7CKMIoENumuruOtarj8n/97Q3htHFYpH8yOSQk3Z5zh8UxUym6FYTb5+A0Nz3NRsXJibnYi7brE/4tx5But9kkFGzG+xpUmimN4c3TMN7OFH//+r8hBf7BT9/GmHDUVZT2JzWGLZES2xDOUuMtA="'); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.method = 'POST'; options.path = '/'; options.headers.host = 'example.com'; // date from spec examples options.headers.Date = 'Thu, 05 Jan 2012 21:31:40 GMT'; var signer = crypto.createSign('RSA-SHA256'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="Test",algorithm="rsa-sha256",signature="' + signer.sign(rsaPrivate, 'base64') + '"'; var req = http.request(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); req.end(); }); // test values from spec for defaults test('valid rsa from spec default', function(t) { var jsonMessage = '{"hello": "world"}'; var sha256sum = crypto.createHash('sha256'); sha256sum.update(jsonMessage) server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req, { // this test uses a fixed old date so ignore clock skew clockSkew: Number.MAX_VALUE }); t.ok(httpSignature.verify(parsed, rsaPublic)); // check known signature t.ok(req.headers.authorization === 'Signature keyId="Test",algorithm="rsa-sha256",signature="jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w="'); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.method = 'POST'; options.path = '/foo?param=value&pet=dog'; options.headers.host = 'example.com'; options.headers.Date = 'Thu, 05 Jan 2014 21:31:40 GMT'; options.headers['content-type'] = 'application/json'; options.headers['digest'] = 'SHA-256=' + sha256sum.digest('base64'); options.headers['content-length'] = '' + (jsonMessage.length - 1); var signer = crypto.createSign('RSA-SHA256'); signer.update('date: ' + options.headers.Date); options.headers.Authorization = 'Signature keyId="Test",algorithm="rsa-sha256",signature="' + signer.sign(rsaPrivate, 'base64') + '"'; var req = http.request(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); req.write(jsonMessage); req.end(); }); // test values from spec for all headers test('valid rsa from spec all headers', function(t) { var jsonMessage = '{"hello": "world"}'; var sha256sum = crypto.createHash('sha256'); sha256sum.update(jsonMessage) server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req, { // this test uses a fixed old date so ignore clock skew clockSkew: Number.MAX_VALUE }); t.ok(httpSignature.verify(parsed, rsaPublic)); // check known signature t.ok(req.headers.authorization === 'Signature keyId="Test",algorithm="rsa-sha256",headers="request-line host date content-type digest content-length",signature="jgSqYK0yKclIHfF9zdApVEbDp5eqj8C4i4X76pE+XHoxugXv7qnVrGR+30bmBgtpR39I4utq17s9ghz/2QFVxlnToYAvbSVZJ9ulLd1HQBugO0jOyn9sXOtcN7uNHBjqNCqUsnt0sw/cJA6B6nJZpyNqNyAXKdxZZItOuhIs78w="'); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.method = 'POST'; options.path = '/foo?param=value&pet=dog'; options.headers.host = 'example.com'; options.headers.Date = 'Thu, 05 Jan 2014 21:31:40 GMT'; options.headers['content-type'] = 'application/json'; options.headers['digest'] = 'SHA-256=' + sha256sum.digest('base64'); options.headers['content-length'] = '' + (jsonMessage.length - 1); var signer = crypto.createSign('RSA-SHA256'); signer.update(options.method + ' ' + options.path + ' HTTP/1.1\n'); signer.update('host: ' + options.headers.host + '\n'); signer.update('date: ' + options.headers.Date + '\n'); signer.update('content-type: ' + options.headers['content-type'] + '\n'); signer.update('digest: ' + options.headers['digest'] + '\n'); signer.update('content-length: ' + options.headers['content-length']); options.headers.Authorization = 'Signature keyId="Test",algorithm="rsa-sha256",headers=' + '"request-line host date content-type digest content-length"' + ',signature="' + signer.sign(rsaPrivate, 'base64') + '"'; var req = http.request(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); req.write(jsonMessage); req.end(); }); test('valid rsa from spec all headers (request-target)', function(t) { var jsonMessage = '{"hello": "world"}'; var sha256sum = crypto.createHash('sha256'); sha256sum.update(jsonMessage); server.tester = function(req, res) { var parsed = httpSignature.parseRequest(req, { // this test uses a fixed old date so ignore clock skew clockSkew: Number.MAX_VALUE }); t.ok(httpSignature.verify(parsed, rsaPublic)); // check known signature t.ok(req.headers.authorization === 'Signature keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="Tqfe2TGMEOwrHLItN2pDnKZiV3cKDWx1dTreYvWRH/kYVT0avw975g25I0/Sig2l60CDkRKTk9ciJMkn8Eanpa7aICnRWbOu38+ozMfQrM7cc06NRSY6+UQ67dn6K4jEW0WNWxhLLwWBSXxhxuXOL3rFKYZliNCundM9FiYk5aE="'); res.writeHead(200); res.write(JSON.stringify(parsed, null, 2)); res.end(); }; options.method = 'POST'; options.path = '/foo?param=value&pet=dog'; options.headers.host = 'example.com'; options.headers.Date = 'Thu, 05 Jan 2014 21:31:40 GMT'; options.headers['content-type'] = 'application/json'; options.headers['digest'] = 'SHA-256=' + sha256sum.digest('base64'); options.headers['content-length'] = '' + (jsonMessage.length - 1); var signer = crypto.createSign('RSA-SHA256'); signer.update('(request-target): ' + options.method.toLowerCase() + ' ' + options.path + '\n'); signer.update('host: ' + options.headers.host + '\n'); signer.update('date: ' + options.headers.Date + '\n'); signer.update('content-type: ' + options.headers['content-type'] + '\n'); signer.update('digest: ' + options.headers['digest'] + '\n'); signer.update('content-length: ' + options.headers['content-length']); options.headers.Authorization = 'Signature keyId="Test",algorithm="rsa-sha256",headers=' + '"(request-target) host date content-type digest content-length"' + ',signature="' + signer.sign(rsaPrivate, 'base64') + '"'; var req = http.request(options, function(res) { t.equal(res.statusCode, 200); t.end(); }); req.write(jsonMessage); req.end(); }); test('tear down', function(t) { server.on('close', function() { t.end(); }); server.close(); }); node-http-signature-1.3.6/tools/000077500000000000000000000000001414525571300165715ustar00rootroot00000000000000node-http-signature-1.3.6/tools/jsl.node.conf000066400000000000000000000155251414525571300211640ustar00rootroot00000000000000# # Configuration File for JavaScript Lint # # This configuration file can be used to lint a collection of scripts, or to enable # or disable warnings for scripts that are linted via the command line. # ### Warnings # Enable or disable warnings based on requirements. # Use "+WarningName" to display or "-WarningName" to suppress. # +ambiguous_else_stmt # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent +ambiguous_nested_stmt # block statements containing block statements should use curly braces to resolve ambiguity +ambiguous_newline # unexpected end of line; it is ambiguous whether these lines are part of the same statement +anon_no_return_value # anonymous function does not always return value +assign_to_function_call # assignment to a function call -block_without_braces # block statement without curly braces +comma_separated_stmts # multiple statements separated by commas (use semicolons?) +comparison_type_conv # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==) +default_not_at_end # the default case is not at the end of the switch statement +dup_option_explicit # duplicate "option explicit" control comment +duplicate_case_in_switch # duplicate case in switch statement +duplicate_formal # duplicate formal argument {name} +empty_statement # empty statement or extra semicolon +identifier_hides_another # identifer {name} hides an identifier in a parent scope -inc_dec_within_stmt # increment (++) and decrement (--) operators used as part of greater statement +incorrect_version # Expected /*jsl:content-type*/ control comment. The script was parsed with the wrong version. +invalid_fallthru # unexpected "fallthru" control comment +invalid_pass # unexpected "pass" control comment +jsl_cc_not_understood # couldn't understand control comment using /*jsl:keyword*/ syntax +leading_decimal_point # leading decimal point may indicate a number or an object member +legacy_cc_not_understood # couldn't understand control comment using /*@keyword@*/ syntax +meaningless_block # meaningless block; curly braces have no impact +mismatch_ctrl_comments # mismatched control comment; "ignore" and "end" control comments must have a one-to-one correspondence +misplaced_regex # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma +missing_break # missing break statement +missing_break_for_last_case # missing break statement for last case in switch +missing_default_case # missing default case in switch statement +missing_option_explicit # the "option explicit" control comment is missing +missing_semicolon # missing semicolon +missing_semicolon_for_lambda # missing semicolon for lambda assignment +multiple_plus_minus # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs +nested_comment # nested comment +no_return_value # function {name} does not always return a value +octal_number # leading zeros make an octal number +parseint_missing_radix # parseInt missing radix parameter +partial_option_explicit # the "option explicit" control comment, if used, must be in the first script tag +redeclared_var # redeclaration of {name} +trailing_comma_in_array # extra comma is not recommended in array initializers +trailing_decimal_point # trailing decimal point may indicate a number or an object member +undeclared_identifier # undeclared identifier: {name} +unreachable_code # unreachable code -unreferenced_argument # argument declared but never referenced: {name} -unreferenced_function # function is declared but never referenced: {name} +unreferenced_variable # variable is declared but never referenced: {name} +unsupported_version # JavaScript {version} is not supported +use_of_label # use of label +useless_assign # useless assignment +useless_comparison # useless comparison; comparing identical expressions -useless_quotes # the quotation marks are unnecessary +useless_void # use of the void type may be unnecessary (void is always undefined) +var_hides_arg # variable {name} hides argument +want_assign_or_call # expected an assignment or function call +with_statement # with statement hides undeclared variables; use temporary variable instead ### Output format # Customize the format of the error message. # __FILE__ indicates current file path # __FILENAME__ indicates current file name # __LINE__ indicates current line # __COL__ indicates current column # __ERROR__ indicates error message (__ERROR_PREFIX__: __ERROR_MSG__) # __ERROR_NAME__ indicates error name (used in configuration file) # __ERROR_PREFIX__ indicates error prefix # __ERROR_MSG__ indicates error message # # For machine-friendly output, the output format can be prefixed with # "encode:". If specified, all items will be encoded with C-slashes. # # Visual Studio syntax (default): +output-format __FILE__(__LINE__): __ERROR__ # Alternative syntax: #+output-format __FILE__:__LINE__: __ERROR__ ### Context # Show the in-line position of the error. # Use "+context" to display or "-context" to suppress. # +context ### Control Comments # Both JavaScript Lint and the JScript interpreter confuse each other with the syntax for # the /*@keyword@*/ control comments and JScript conditional comments. (The latter is # enabled in JScript with @cc_on@). The /*jsl:keyword*/ syntax is preferred for this reason, # although legacy control comments are enabled by default for backward compatibility. # -legacy_control_comments ### Defining identifiers # By default, "option explicit" is enabled on a per-file basis. # To enable this for all files, use "+always_use_option_explicit" -always_use_option_explicit # Define certain identifiers of which the lint is not aware. # (Use this in conjunction with the "undeclared identifier" warning.) # # Common uses for webpages might be: +define __dirname +define clearInterval +define clearTimeout +define console +define exports +define global +define module +define process +define require +define setInterval +define setTimeout +define Buffer +define JSON +define Math ### JavaScript Version # To change the default JavaScript version: #+default-type text/javascript;version=1.5 #+default-type text/javascript;e4x=1 ### Files # Specify which files to lint # Use "+recurse" to enable recursion (disabled by default). # To add a set of files, use "+process FileName", "+process Folder\Path\*.js", # or "+process Folder\Path\*.htm". # node-http-signature-1.3.6/tools/jsstyle.conf000066400000000000000000000001051414525571300211310ustar00rootroot00000000000000indent=2 doxygen unparenthesized-return=0 blank-after-start-comment=0node-http-signature-1.3.6/tools/mk/000077500000000000000000000000001414525571300172005ustar00rootroot00000000000000node-http-signature-1.3.6/tools/mk/Makefile.defs000066400000000000000000000027361414525571300215700ustar00rootroot00000000000000# -*- mode: makefile -*- # # Copyright (c) 2012, Joyent, Inc. All rights reserved. # # Makefile.defs: common defines. # # NOTE: This makefile comes from the "eng" repo. It's designed to be dropped # into other repos as-is without requiring any modifications. If you find # yourself changing this file, you should instead update the original copy in # eng.git and then update your repo to use the new version. # # This makefile defines some useful defines. Include it at the top of # your Makefile. # # Definitions in this Makefile: # # TOP The absolute path to the project directory. The top dir. # BRANCH The current git branch. # TIMESTAMP The timestamp for the build. This can be set via # the TIMESTAMP envvar (used by MG-based builds). # STAMP A build stamp to use in built package names. # TOP := $(shell pwd) # # Mountain Gorilla-spec'd versioning. # See "Package Versioning" in MG's README.md: # # # Need GNU awk for multi-char arg to "-F". _AWK := $(shell (which gawk >/dev/null && echo gawk) \ || (which nawk >/dev/null && echo nawk) \ || echo awk) BRANCH := $(shell git symbolic-ref HEAD | $(_AWK) -F/ '{print $$3}') ifeq ($(TIMESTAMP),) TIMESTAMP := $(shell date -u "+%Y%m%dT%H%M%SZ") endif _GITDESCRIBE := g$(shell git describe --all --long --dirty | $(_AWK) -F'-g' '{print $$NF}') STAMP := $(BRANCH)-$(TIMESTAMP)-$(_GITDESCRIBE) # node-gyp will print build info useful for debugging with V=1 export V=1 node-http-signature-1.3.6/tools/mk/Makefile.deps000066400000000000000000000021741414525571300215760ustar00rootroot00000000000000# -*- mode: makefile -*- # # Copyright (c) 2012, Joyent, Inc. All rights reserved. # # Makefile.deps: Makefile for including common tools as dependencies # # NOTE: This makefile comes from the "eng" repo. It's designed to be dropped # into other repos as-is without requiring any modifications. If you find # yourself changing this file, you should instead update the original copy in # eng.git and then update your repo to use the new version. # # This file is separate from Makefile.targ so that teams can choose # independently whether to use the common targets in Makefile.targ and the # common tools here. # # # javascriptlint # JSL_EXEC ?= deps/javascriptlint/build/install/jsl JSL ?= $(JSL_EXEC) $(JSL_EXEC): | deps/javascriptlint/.git cd deps/javascriptlint && make install distclean:: if [[ -f deps/javascriptlint/Makefile ]]; then \ cd deps/javascriptlint && make clean; \ fi # # jsstyle # JSSTYLE_EXEC ?= deps/jsstyle/jsstyle JSSTYLE ?= $(JSSTYLE_EXEC) $(JSSTYLE_EXEC): | deps/jsstyle/.git # # restdown # RESTDOWN_EXEC ?= deps/restdown/bin/restdown RESTDOWN ?= python $(RESTDOWN_EXEC) $(RESTDOWN_EXEC): | deps/restdown/.git node-http-signature-1.3.6/tools/mk/Makefile.targ000066400000000000000000000212511414525571300215750ustar00rootroot00000000000000# -*- mode: makefile -*- # # Copyright (c) 2012, Joyent, Inc. All rights reserved. # # Makefile.targ: common targets. # # NOTE: This makefile comes from the "eng" repo. It's designed to be dropped # into other repos as-is without requiring any modifications. If you find # yourself changing this file, you should instead update the original copy in # eng.git and then update your repo to use the new version. # # This Makefile defines several useful targets and rules. You can use it by # including it from a Makefile that specifies some of the variables below. # # Targets defined in this Makefile: # # check Checks JavaScript files for lint and style # Checks bash scripts for syntax # Checks SMF manifests for validity against the SMF DTD # # clean Removes built files # # docs Builds restdown documentation in docs/ # # prepush Depends on "check" and "test" # # test Does nothing (you should override this) # # xref Generates cscope (source cross-reference index) # # For details on what these targets are supposed to do, see the Joyent # Engineering Guide. # # To make use of these targets, you'll need to set some of these variables. Any # variables left unset will simply not be used. # # BASH_FILES Bash scripts to check for syntax # (paths relative to top-level Makefile) # # CLEAN_FILES Files to remove as part of the "clean" target. Note # that files generated by targets in this Makefile are # automatically included in CLEAN_FILES. These include # restdown-generated HTML and JSON files. # # DOC_FILES Restdown (documentation source) files. These are # assumed to be contained in "docs/", and must NOT # contain the "docs/" prefix. # # JSL_CONF_NODE Specify JavaScriptLint configuration files # JSL_CONF_WEB (paths relative to top-level Makefile) # # Node.js and Web configuration files are separate # because you'll usually want different global variable # configurations. If no file is specified, none is given # to jsl, which causes it to use a default configuration, # which probably isn't what you want. # # JSL_FILES_NODE JavaScript files to check with Node config file. # JSL_FILES_WEB JavaScript files to check with Web config file. # # You can also override these variables: # # BASH Path to bash (default: bash) # # CSCOPE_DIRS Directories to search for source files for the cscope # index. (default: ".") # # JSL Path to JavaScriptLint (default: "jsl") # # JSL_FLAGS_NODE Additional flags to pass through to JSL # JSL_FLAGS_WEB # JSL_FLAGS # # JSSTYLE Path to jsstyle (default: jsstyle) # # JSSTYLE_FLAGS Additional flags to pass through to jsstyle # # # Defaults for the various tools we use. # BASH ?= bash BASHSTYLE ?= tools/bashstyle CP ?= cp CSCOPE ?= cscope CSCOPE_DIRS ?= . JSL ?= jsl JSSTYLE ?= jsstyle MKDIR ?= mkdir -p MV ?= mv RESTDOWN_FLAGS ?= RMTREE ?= rm -rf JSL_FLAGS ?= --nologo --nosummary ifeq ($(shell uname -s),SunOS) TAR ?= gtar else TAR ?= tar endif # # Defaults for other fixed values. # BUILD = build DISTCLEAN_FILES += $(BUILD) DOC_BUILD = $(BUILD)/docs/public # # Configure JSL_FLAGS_{NODE,WEB} based on JSL_CONF_{NODE,WEB}. # ifneq ($(origin JSL_CONF_NODE), undefined) JSL_FLAGS_NODE += --conf=$(JSL_CONF_NODE) endif ifneq ($(origin JSL_CONF_WEB), undefined) JSL_FLAGS_WEB += --conf=$(JSL_CONF_WEB) endif # # Targets. For descriptions on what these are supposed to do, see the # Joyent Engineering Guide. # # # Instruct make to keep around temporary files. We have rules below that # automatically update git submodules as needed, but they employ a deps/*/.git # temporary file. Without this directive, make tries to remove these .git # directories after the build has completed. # .SECONDARY: $($(wildcard deps/*):%=%/.git) # # This rule enables other rules that use files from a git submodule to have # those files depend on deps/module/.git and have "make" automatically check # out the submodule as needed. # deps/%/.git: git submodule update --init deps/$* # # These recipes make heavy use of dynamically-created phony targets. The parent # Makefile defines a list of input files like BASH_FILES. We then say that each # of these files depends on a fake target called filename.bashchk, and then we # define a pattern rule for those targets that runs bash in check-syntax-only # mode. This mechanism has the nice properties that if you specify zero files, # the rule becomes a noop (unlike a single rule to check all bash files, which # would invoke bash with zero files), and you can check individual files from # the command line with "make filename.bashchk". # .PHONY: check-bash check-bash: $(BASH_FILES:%=%.bashchk) $(BASH_FILES:%=%.bashstyle) %.bashchk: % $(BASH) -n $^ %.bashstyle: % $(BASHSTYLE) $^ # # The above approach can be slow when there are many files to check because it # requires that "make" invoke the check tool once for each file, rather than # passing in several files at once. For the JavaScript check targets, we define # a variable for the target itself *only if* the list of input files is # non-empty. This avoids invoking the tool if there are no files to check. # JSL_NODE_TARGET = $(if $(JSL_FILES_NODE), check-jsl-node) .PHONY: check-jsl-node check-jsl-node: $(JSL_EXEC) $(JSL) $(JSL_FLAGS) $(JSL_FLAGS_NODE) $(JSL_FILES_NODE) JSL_WEB_TARGET = $(if $(JSL_FILES_WEB), check-jsl-web) .PHONY: check-jsl-web check-jsl-web: $(JSL_EXEC) $(JSL) $(JSL_FLAGS) $(JSL_FLAGS_WEB) $(JSL_FILES_WEB) .PHONY: check-jsl check-jsl: $(JSL_NODE_TARGET) $(JSL_WEB_TARGET) JSSTYLE_TARGET = $(if $(JSSTYLE_FILES), check-jsstyle) .PHONY: check-jsstyle check-jsstyle: $(JSSTYLE_EXEC) $(JSSTYLE) $(JSSTYLE_FLAGS) $(JSSTYLE_FILES) .PHONY: check check: check-jsl $(JSSTYLE_TARGET) check-bash @echo check ok .PHONY: clean clean:: -$(RMTREE) $(CLEAN_FILES) .PHONY: distclean distclean:: clean -$(RMTREE) $(DISTCLEAN_FILES) CSCOPE_FILES = cscope.in.out cscope.out cscope.po.out CLEAN_FILES += $(CSCOPE_FILES) .PHONY: xref xref: cscope.files $(CSCOPE) -bqR .PHONY: cscope.files cscope.files: find $(CSCOPE_DIRS) -name '*.c' -o -name '*.h' -o -name '*.cc' \ -o -name '*.js' -o -name '*.s' -o -name '*.cpp' > $@ # # The "docs" target is complicated because we do several things here: # # (1) Use restdown to build HTML and JSON files from each of DOC_FILES. # # (2) Copy these files into $(DOC_BUILD) (build/docs/public), which # functions as a complete copy of the documentation that could be # mirrored or served over HTTP. # # (3) Then copy any directories and media from docs/media into # $(DOC_BUILD)/media. This allows projects to include their own media, # including files that will override same-named files provided by # restdown. # # Step (3) is the surprisingly complex part: in order to do this, we need to # identify the subdirectories in docs/media, recreate them in # $(DOC_BUILD)/media, then do the same with the files. # DOC_MEDIA_DIRS := $(shell find docs/media -type d 2>/dev/null | grep -v "^docs/media$$") DOC_MEDIA_DIRS := $(DOC_MEDIA_DIRS:docs/media/%=%) DOC_MEDIA_DIRS_BUILD := $(DOC_MEDIA_DIRS:%=$(DOC_BUILD)/media/%) DOC_MEDIA_FILES := $(shell find docs/media -type f 2>/dev/null) DOC_MEDIA_FILES := $(DOC_MEDIA_FILES:docs/media/%=%) DOC_MEDIA_FILES_BUILD := $(DOC_MEDIA_FILES:%=$(DOC_BUILD)/media/%) # # Like the other targets, "docs" just depends on the final files we want to # create in $(DOC_BUILD), leveraging other targets and recipes to define how # to get there. # .PHONY: docs docs: \ $(DOC_FILES:%.restdown=$(DOC_BUILD)/%.html) \ $(DOC_FILES:%.restdown=$(DOC_BUILD)/%.json) \ $(DOC_MEDIA_FILES_BUILD) # # We keep the intermediate files so that the next build can see whether the # files in DOC_BUILD are up to date. # .PRECIOUS: \ $(DOC_FILES:%.restdown=docs/%.html) \ $(DOC_FILES:%.restdown=docs/%json) # # We do clean those intermediate files, as well as all of DOC_BUILD. # CLEAN_FILES += \ $(DOC_BUILD) \ $(DOC_FILES:%.restdown=docs/%.html) \ $(DOC_FILES:%.restdown=docs/%.json) # # Before installing the files, we must make sure the directories exist. The | # syntax tells make that the dependency need only exist, not be up to date. # Otherwise, it might try to rebuild spuriously because the directory itself # appears out of date. # $(DOC_MEDIA_FILES_BUILD): | $(DOC_MEDIA_DIRS_BUILD) $(DOC_BUILD)/%: docs/% | $(DOC_BUILD) $(CP) $< $@ docs/%.json docs/%.html: docs/%.restdown | $(DOC_BUILD) $(RESTDOWN_EXEC) $(RESTDOWN) $(RESTDOWN_FLAGS) -m $(DOC_BUILD) $< $(DOC_BUILD): $(MKDIR) $@ $(DOC_MEDIA_DIRS_BUILD): $(MKDIR) $@ # # The default "test" target does nothing. This should usually be overridden by # the parent Makefile. It's included here so we can define "prepush" without # requiring the repo to define "test". # .PHONY: test test: .PHONY: prepush prepush: check test