Beispiel #1
0
    function (err, keys) {
      var credentials = {
        id: keys.tokenId.toString('hex'),
        key: keys.reqHMACkey.toString('hex'),
        algorithm: 'sha256'
      };
      var payload = {
        publicKey: JSON.parse(publicKey),
        duration: duration
      };
      var verify = {
        credentials: credentials,
        contentType: 'application/json'
      };
      if (hashPayload) {
        verify.payload = JSON.stringify(payload);
      }
      var header = hawk.client.header('http://localhost/sign', 'POST', verify);

      this.makeRequest(
        'POST',
        '/sign',
        {
          headers: {
            Authorization: header.field,
            Host: 'localhost',
            'Content-Type': 'application/json'
          },
          payload: payload
        },
        function (res) {
          cb(null, res.result);
        }
      );
    }.bind(this)
Beispiel #2
0
consumer.getCredentials('Application B', 'http://localhost:3501/authenticate', function(err, credentials) {
    if (err) {
        console.log('Error Getting Credentials:');
        console.log(err.prepResponseBody && JSON.stringify(err.prepResponseBody()) || err);
        return;
    } else {
        console.log('The Consumer now has Credentials:');
        console.log(credentials);
    }
    /**
     *  Making a request, using HAWK to authenticate
     */
    var requestOptions = {
            uri:'http://localhost:3501/test'
            , method: 'GET'
            , headers: {}
            , json: true
        }
        , header = Hawk.client.header(requestOptions.uri, requestOptions.method, {credentials: credentials});
    ;
    requestOptions.headers.Authorization = header.field;
    request(requestOptions, function(err, resp, body) {
        if (err) {
            console.log(err);
        }
        else {
            console.log("Hawk Request complete");
            console.log(resp.statusCode);
            console.log(body);
        }
    });
});
Beispiel #3
0
  it('should call done with false when the id doesnt exist', function(testDone) {
    var testCredentials = {
      id: '321321',
      key: 'dsa',
      algorithm: 'sha256'
    };
    var authHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', 'POST', { credentials: testCredentials });
    var req = {
      headers: {
        authorization: authHeader.field,
        host: 'example.com:8080'
      },
      method: 'GET',
      url: '/resource/4?filter=a'
    };
    var res = {
      header: {}
    };

    strategy.error = function(challenge) {
      expect(challenge).to.not.be(null);
      expect(challenge.message).to.be.eql('Unknown credentials');
      testDone();
    };
    strategy.authenticate(req, res);
  });
Beispiel #4
0
    it('fails on invalid app request (bad credentials)', function (done) {

        // The app requests an app ticket using Basic authentication

        var req = {
            method: 'POST',
            url: '/oz/app',
            headers: {
                host: 'example.com',
                authorization: Hawk.client.header('http://example.com/oz/app', 'POST', { credentials: apps['social'] }).field
            }
        };

        var options = {
            encryptionPassword: encryptionPassword,
            loadAppFunc: function (id, callback) {

                callback(null, apps.network);
            }
        };

        Oz.endpoints.app(req, null, options, function (err, appTicket) {

            expect(err).to.exist;
            done();
        });
    });
Beispiel #5
0
        call: function(opts) {
            var url = 'http://'+options.apiIP+opts.url;
            var requestOptions = {
                headers: { 'content-type':'application/json'}
            };

            // Add payload
            if(opts.payload) {
                requestOptions.payload = JSON.stringify(opts.payload);
            }
            // Add auth
            var header = Hawk.client.header(url, opts.method, { credentials: opts.credentials });
            requestOptions.headers.Authorization = header.field;

            // Make call
            if(opts.method === 'POST')
            {
                Nipple.post(url, requestOptions, opts.callback)
            }
            else if(opts.method === 'PUT')
            {
                Nipple.put(url, requestOptions, opts.callback)
            }
            else
            {
                Nipple.get(url, requestOptions, opts.callback)
            }
        }
Beispiel #6
0
        server.register(require('../'), function (err) {

            expect(err).to.not.exist();
            server.auth.strategy('default', 'hawk', { getCredentialsFunc: getCredentials });
            server.route({
                method: 'POST',
                path: '/hawkPayload',
                handler: function (request, reply) {

                    reply('Success');
                },
                config: { auth: { mode: 'required', payload: 'required', strategy: 'default'  }, payload: { override: 'text/plain' } }
            });

            var payload = 'Here is my payload';
            var authHeader = Hawk.client.header('http://example.com:8080/hawkPayload', 'POST', { credentials: credentials.john.cred });
            var request = { method: 'POST', url: 'http://example.com:8080/hawkPayload', headers: { authorization: authHeader.field }, payload: payload };

            server.inject(request, function (res) {

                expect(res.statusCode).to.equal(401);
                expect(res.result.message).to.equal('Missing payload authentication');
                done();
            });
        });
Beispiel #7
0
 .then((token) => {
   url = client.api.baseURL + '/account/device'
   const method = 'POST'
   const payload = {
     name: 'my cool device',
     type: 'desktop'
   }
   const verify = {
     credentials: token,
     payload: JSON.stringify(payload),
     timestamp: Math.floor(Date.now() / 1000)
   }
   const headers = {
     Authorization: hawk.client.header(url, method, verify).field
   }
   payload.name = 'my stealthily-changed device name'
   return request(
     {
       method: method,
       url: url,
       headers: headers,
       body: JSON.stringify(payload)
     })
     .spread((res) => {
       const body = JSON.parse(res.body)
       assert.equal(res.statusCode, 401, 'the request was rejected')
       assert.equal(body.errno, 109, 'the errno indicates an invalid signature')
     })
 })
Beispiel #8
0
        server.register(require('../'), function (err) {

            expect(err).to.not.exist();
            server.auth.strategy('default', 'hawk', { getCredentialsFunc: getCredentials });
            server.route({
                method: 'POST',
                path: '/hawkPayload',
                handler: function (request, reply) {

                    reply('Success');
                },
                config: { auth: { mode: 'required', payload: 'required', strategy: 'default'  }, payload: { override: 'text/plain' } }
            });

            var payload = 'application text formatted payload';
            var authHeader = Hawk.client.header('http://example.com:8080/hawkPayload', 'POST', { credentials: credentials.john.cred, payload: payload, contentType: 'text/plain' });
            var request = {
                method: 'POST',
                url: 'http://example.com:8080/hawkPayload',
                headers: { authorization: authHeader.field, 'content-type': 'text/plain' },
                payload: payload,
                simulate: { split: true }
            };

            server.inject(request, function (res) {

                expect(res.statusCode).to.equal(200);
                expect(res.result).to.equal('Success');
                done();
            });
        });
Beispiel #9
0
    var hawkHeader = function (id, path) {

        if (credentials[id] && credentials[id].cred) {
            return Hawk.client.header('http://example.com:8080' + path, 'POST', { credentials: credentials[id].cred });
        }
        return '';
    };
    request(reqOpt, function(error, response, body) {
      if (error) {
        metrics.apkSigningFailed(path);
        logError(log, 'apk signer request error ', error);
        return cb(new Error('SIGNER_REQUEST_FAILED'));
      }

      // Make sure that the signer thinks *our* request is valid.
      if (response.statusCode !== 200) {
        metrics.apkSigningFailed(path);
        log.error('signer system error response: ' +
          response.statusCode + ' ' + response.body);
        return cb(new Error('SIGNER_REFUSED_REQUEST'));
      }

      var isValid = hawk.client.authenticate(response,
        config.hawk,
        hdr.artifacts, {
          payload: body,
          require: true
        });

      if (isValid) {
        metrics.apkSigningFinished(path, new Date() - start);
        return cb(null, body);
      } else {
        metrics.apkSigningFailed(path);
        return cb(new Error('INVALID_SIGNER_RESPONSE'));
      }
    });
  it('can answer authenticateHawk requests', async function (done) {
    let credentials = helper.cfg.taskcluster.credentials;

    this.timeout(30*1000);

    let data = {
      method:         'get',
      resource:       '/',
      host:           'test.taskcluster.net',
      port:           443
    };
    /*
    hawk.client.header('https://'+data.header+data.resource, data.method, req_credentials).field
    */
    data.authorization = hawk.client.header(
        'https://' + data.host + data.resource, data.method, {
          credentials: {
            id: credentials.clientId,
            key: credentials.accessToken,
            algorithm: 'sha256',
          },
          payload: '{}'
        }).field;
    try {
      let result = await auth.authenticateHawk(data);
      debug("Result: ",result);
      assume(result.status).equals('auth-success');
      assume(result.hash).equals('XtNvx1FqrUYVOLlne3l2WzcyRfj9QeC6YtmhMKKFMGY=');
      return done();
    } catch (err) {
      return done(err);
    }
  });
Beispiel #12
0
  RequestProto.hawk = function(credential, moreOptions) {
    var url = this.url;
    var method = this.method;

    var contentType;
    if (this.getHeader && this.getHeader instanceof Function)
      contentType = this.getHeader('content-type');
    else if (this.get && this.get instanceof Function)
      contentType = this.get('content-type');

    var isJSON = this._data &&
                 this._data instanceof Object &&
                 contentType === 'application/json';

    var data = (isJSON) ? JSON.stringify(this._data) : this._data;

    var options = {
      credentials: credential,
      contentType: contentType,
      payload: data
    };

    if (options && typeof options == 'object')
      options = extend(options, moreOptions);

    this.set('Authorization',
      hawk.client.header(url, method, options).field);

    return this;
  };
Beispiel #13
0
    it('returns an error with payload validation when the payload hash is not included and payload validation is required', async () => {

        const server = Hapi.server();
        await server.register(require('../'));

        server.auth.strategy('default', 'hawk', { getCredentialsFunc });
        server.route({
            method: 'POST',
            path: '/hawkPayload',
            handler: function (request, h) {

                return 'Success';
            },
            options: { auth: { mode: 'required', payload: 'required', strategy: 'default' }, payload: { override: 'text/plain' } }
        });

        const payload = 'Here is my payload';
        const authHeader = Hawk.client.header('http://example.com:8080/hawkPayload', 'POST', { credentials: credentials.john.cred });
        const request = { method: 'POST', url: 'http://example.com:8080/hawkPayload', headers: { authorization: authHeader.header }, payload };

        const res = await server.inject(request);

        expect(res.statusCode).to.equal(401);
        expect(res.result.message).to.equal('Missing payload authentication');
    });
    retrieveFromToken(ikm, info, salt, length, (id, key) => {

        const algorithm = clientToken.algorithm;

        const hawkCredentials = {
            id: id,
            key: key,
            algorithm: algorithm
        };

        const protocol = request.connection.info.protocol;
        const url = protocol
            + '://'
            + request.info.host + request.path;
        const method = request.method;

        server.log('hawkPreAuth url: ' + url);

        request.raw.req.url = url;

        const header = Hawk.client.header(url,
            method,
            {credentials: hawkCredentials, ext: 'some-app-data'});

        request.raw.req.headers.authorization = header.field;

        return reply.continue();
    });
Beispiel #15
0
    it('returns a reply on successful auth when auth is optional and when payload validation is required', async () => {

        const server = Hapi.server();
        await server.register(require('../'));

        server.auth.strategy('default', 'hawk', { getCredentialsFunc });
        server.route({
            method: 'POST',
            path: '/hawkOptionalPayload',
            config: {
                handler: (request, h) => 'Success',
                auth: { mode: 'optional', payload: 'required', strategy: 'default' },
                payload: { override: 'text/plain' }
            }
        });

        const payload = 'Here is my payload';
        const authHeader = Hawk.client.header('http://example.com:8080/hawkOptionalPayload', 'POST', { credentials: credentials.john.cred, payload });
        const request = { method: 'POST', url: 'http://example.com:8080/hawkOptionalPayload', headers: { authorization: authHeader.header }, payload };

        const res = await server.inject(request);

        expect(res.statusCode).to.equal(200);
        expect(res.result).to.equal('Success');
    });
Beispiel #16
0
    it('returns a reply on successful auth when the payload is tampered with and the route has disabled validation', async () => {

        const server = Hapi.server();
        await server.register(require('../'));

        server.auth.strategy('default', 'hawk', { getCredentialsFunc });
        server.route({
            method: 'POST',
            path: '/hawkPayloadNone',
            handler: function (request, h) {

                return 'Success';
            },
            options: { auth: { mode: 'required', payload: false, strategy: 'default' }, payload: { override: 'text/plain' } }
        });

        let payload = 'Here is my payload';
        const authHeader = Hawk.client.header('http://example.com:8080/hawkPayloadNone', 'POST', { credentials: credentials.john.cred, payload });
        payload += 'HACKED';
        const request = { method: 'POST', url: 'http://example.com:8080/hawkPayloadNone', headers: { authorization: authHeader.header }, payload };

        const res = await server.inject(request);

        expect(res.statusCode).to.equal(200);
        expect(res.result).to.equal('Success');
    });
Beispiel #17
0
    it('returns a reply on successful auth and payload validation', async () => {

        const server = Hapi.server();
        await server.register(require('../'));

        server.auth.strategy('default', 'hawk', { getCredentialsFunc });
        server.route({
            method: 'POST',
            path: '/hawkPayload',
            handler: function (request, h) {

                return 'Success';
            },
            options: { auth: { mode: 'required', payload: 'required', strategy: 'default' }, payload: { override: 'text/plain' } }
        });

        const payload = 'application text formatted payload';
        const authHeader = Hawk.client.header('http://example.com:8080/hawkPayload', 'POST', { credentials: credentials.john.cred, payload, contentType: 'text/plain' });
        const request = {
            method: 'POST',
            url: 'http://example.com:8080/hawkPayload',
            headers: { authorization: authHeader.header, 'content-type': 'text/plain' },
            payload,
            simulate: { split: true }
        };

        const res = await server.inject(request);

        expect(res.statusCode).to.equal(200);
        expect(res.result).to.equal('Success');
    });
Beispiel #18
0
exports.header = function (uri, method, ticket, options) {

    var settings = Hoek.clone(options || {});
    settings.credentials = ticket;
    settings.app = ticket.app;
    settings.dlg = ticket.dlg;

    return Hawk.client.header(uri, method, settings);
};
Beispiel #19
0
internals.hawkHeader = function (id, path, server) {

    if (internals.credentials[id]) {
        return Hawk.client.header(server.info.uri + path, 'GET', { credentials: internals.credentials[id] }).field;
    }
    else {
        return '';
    }
};
  withConfig(function(config) {
    if (undefined === log) {
      log = require('../lib/logging')(config);
    }
    var reqOpt = {
      uri: config.signerUrl + path,
      method: 'POST',
      body: body,
      headers: {
        'Content-Length': Buffer.byteLength(body),
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    var hdr = hawk.client.header(reqOpt.uri,
      reqOpt.method, {
        credentials: config.hawk,
        payload: body,
        contentType: 'application/x-www-form-urlencoded'
      });
    if (hdr.err) {
      metrics.apkSigningFailed(apkPath);
      logError(log, 'request header error', hdr.err);
      return cb(new Error('INTERNAL_REQUEST_ERROR'));
    }
    reqOpt.headers.Authorization = hdr.field;

    request(reqOpt, function(error, response, body) {
      if (error) {
        metrics.apkSigningFailed(apkPath);
        logError(log, 'request error', error);
        return cb(new Error('SIGNER_REQUEST_FAILED'));
      }

      // Make sure that the signer thinks *our* request is valid.
      if (response.statusCode !== 200) {
        metrics.apkSigningFailed(apkPath);
        log.error('signer system error response: ' +
          response.statusCode + ' ' + response.body);
        return cb(new Error('SIGNER_REFUSED_REQUEST'));
      }

      var isValid = hawk.client.authenticate(response,
        config.hawk,
        hdr.artifacts, {
          payload: body,
          require: true
        });

      if (isValid) {
        metrics.apkSigningFinished(apkPath, new Date() - start);
        return cb(null, body);
      } else {
        metrics.apkSigningFailed(apkPath);
        return cb(new Error('INVALID_SIGNER_RESPONSE'));
      }
    });
  });
Beispiel #21
0
function hawkHeader(token, method, url, payload) {
  var verify = {
    credentials: token
  }
  if (payload) {
    verify.contentType = 'application/json'
    verify.payload = JSON.stringify(payload)
  }
  return hawk.client.header(url, method, verify).field
}
		request : function(request, config) {
			request.headers = request.headers || {};
			var method = request.method || (request.entity ? 'POST' : 'GET');
			var header = Hawk.client.header(request.path, method, config.hawk);
			request.headers.Authorization = header.field;
			if (log.isDebugEnabled()) {
				log.debug('request(): Authorization : ' + request.headers.Authorization);
			}
			return request;
		}
Beispiel #23
0
 function hawkHeader(token, method, url, payload, offset) {
   const verify = {
     credentials: token
   };
   if (payload) {
     verify.contentType = 'application/json';
     verify.payload = JSON.stringify(payload);
   }
   if (offset) {
     verify.localtimeOffsetMsec = offset;
   }
   return hawk.client.header(url, method, verify).header;
 }
Beispiel #24
0
test('validate request', coTape(function*(a){
  a.plan(4);
  yield server.start(3000);
  var unauthorized = yield request(url);
  a.equal(unauthorized.statusCode, 401);
  
  var header = Hawk.client.header(url, 'GET', { credentials: credentials, ext: 'some-app-data' });
  var opts = { uri: url, method: 'GET', headers: {} };
  opts.headers.Authorization = header.field;
  
  var authorized = yield request(opts);
  var validresponse = Hawk.client.authenticate(authorized, credentials, header.artifacts, { payload: authorized.body });
  a.equal(authorized.statusCode, 200);
  a.ok(validresponse, 'server response is authenticated');
  
  credentials.key += 'x';
  var badheader = Hawk.client.header(url, 'GET', { credentials: credentials, ext: 'some-app-data' });
  var badopts = { uri: url, method: 'GET', headers: {} };
  badopts.headers.Authorization = badheader.field;
  var misauthorized = yield request(badopts);
  a.equal(misauthorized.statusCode, 500);
  yield server.stop();
}));
Beispiel #25
0
Client.prototype.withSession = function withSession(method, path, data) {
  if (!this.sessionToken) {
    return P.reject(boom.forbidden('Missing session token'));
  }
  var credentials = hawkCredentials.derive(new Buffer(this.sessionToken, 'hex'), 'sessionToken');
  var requestOpts = {
    headers: {}
  };
  var headerOpts = {
    credentials: credentials
  };
  if (arguments.length > 2) {
    var payload = JSON.stringify(data);
    if (payload) {
      requestOpts.headers['content-type'] = headerOpts.contentType = 'application/json';
      requestOpts.payload = headerOpts.payload = payload;
    }
  }
  var requestURL = this.baseURL.resolve(path);
  var header = hawk.client.header(requestURL, method, headerOpts);
  requestOpts.headers.authorization = header.field;
  return this.request(method, path, requestOpts).then(function afterBody(response) {
    return readResponse(response, {
      json: true
    }).then(function afterRead(payload) {
      var authOpts = {
        payload: payload
      };
      var isValid = hawk.client.authenticate(
        response,
        credentials,
        header.artifacts,
        authOpts
      );
      if (!isValid) {
        return P.reject(boom.forbidden('Invalid response payload signature'));
      }
      if (!isSuccessStatus(response.statusCode)) {
        var error = boom.create(
          response.statusCode,
          'Unexpected response status code',
          payload
        );
        return P.reject(error);
      }
      return payload;
    });
  });
};
Beispiel #26
0
Request(requestOptions, function (err, res, body) {
  if (err) { console.log(err); }

  var isValid =
    Hawk.client.authenticate(
      res,
      Conf.credentials,
      header.artifacts,
      { payload: body });

  if (Conf.debug)
    console.log(res.statusCode+': '+body+
                  (isValid ? ' (valid)' : ' (invalid)'));

});
Beispiel #27
0
    handler: function (request, reply) {
        var url = this.options.serviceUri + '/users/' + request.session.get('user') + '/todos/' + request.params.id;

        Nipple.get(url, {
            headers: {
                authorization: Hawk.client.header( url, 'GET', { credentials: this.credentials } ).field
            }
        }, function(err, res, payload){
            if(err){
                reply(Boom.wrap(err));
            } else {
                reply(payload).code(res.statusCode);
            }
        });
    }
 it('can authenticate a request with a correct header', function(testDone) {
   var header = Hawk.client.header('http://example.com:8080/resource/4?filter=a', 'GET', { credentials: credentials });  
   var req = {
     headers: {
       authorization: header.field,
       host: 'example.com:8080'
     },
     method: 'GET',
     url: '/resource/4?filter=a'
   };    
   strategy.success = function(user) {
     user.should.eql('tito');
     testDone();
   };
   strategy.authenticate(req);
 });
 it('should properly fail with correct challenge code when using different url', function(testDone) {
   var header = Hawk.client.header('http://example.com:8080/resource/4?filter=a', 'GET', { credentials: credentials });    
   var req = {
     headers: {
       authorization: header.field,
       host: 'example.com:9090'
     },
     method: 'GET',
     url: '/resource/4?filter=a'
   };
   strategy.error = function(challenge) {
     challenge.message.should.eql('Bad mac');
     testDone();
   };
   strategy.authenticate(req);
 });
Beispiel #30
0
var makeRequest = function(client, method, url, payload, query) {
  // Add query to url if present
  if (query) {
    query = querystring.stringify(query);
    if (query.length > 0) {
      url += '?' + query;
    }
  }

  // Construct request object
  var req = request(method.toUpperCase(), url);
  // Set the http agent for this request, if supported in the current
  // environment (browser environment doesn't support http.Agent)
  if (req.agent) {
    req.agent(client._httpAgent);
  }

  // Timeout for each individual request.
  req.timeout(client._timeout);

  // Send payload if defined
  if (payload !== undefined) {
    req.send(payload);
  }

  // Authenticate, if credentials are provided
  if (client._options.credentials &&
      client._options.credentials.clientId &&
      client._options.credentials.accessToken) {
    // Create hawk authentication header
    var header = hawk.client.header(url, method.toUpperCase(), {
      credentials: {
        id:         client._options.credentials.clientId,
        key:        client._options.credentials.accessToken,
        algorithm:  'sha256'
      },
      ext:          client._extData
    });
    req.set('Authorization', header.field);
  }

  // Return request
  return req;
};