Skip to content

Commit

Permalink
Merge 315e491 into 1ee9b22
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Nov 24, 2018
2 parents 1ee9b22 + 315e491 commit 15478ed
Show file tree
Hide file tree
Showing 8 changed files with 225 additions and 14 deletions.
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at opensource+octokit@github.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
29 changes: 27 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
> GitHub App Authentication client for JavaScript
[![@latest](https://img.shields.io/npm/v/@octokit/app.svg)](https://www.npmjs.com/package/@octokit/app)
[![Build Status](https://travis-ci.org/octokit/app.js.svg?branch=master)](https://travis-ci.org/octokit/app.js)
[![Build Status](https://travis-ci.com/octokit/app.js.svg?branch=master)](https://travis-ci.com/octokit/app.js)
[![Coverage Status](https://coveralls.io/repos/github/octokit/app.js/badge.svg)](https://coveralls.io/github/octokit/app.js)
[![Greenkeeper](https://badges.greenkeeper.io/octokit/app.js.svg)](https://greenkeeper.io/)

Expand Down Expand Up @@ -40,7 +40,7 @@ const installationId = body.data.id

## Authenticating as an Installation

Once you have authenticated as a GitHub App, you can use that in order to request an installation access token. Calling `requestToken()` automatically performs the app authentication for you. This token is scoped for your specific app and expires after an hour. See also the [GitHub Developer Docs](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation).
Once you have authenticated as a GitHub App, you can use that in order to request an installation access token. Calling `requestToken()` automatically performs the app authentication for you. See also the [GitHub Developer Docs](https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#authenticating-as-an-installation).

```js
const App = require('@octokit/app')
Expand All @@ -64,6 +64,31 @@ await request('POST /repos/:owner/:repo/issues', {
})
```

## Caching installation tokens

Installation tokens expire after an hour. By default, `@octokit/app` is caching up to 15000 tokens simultaneously using [`lru-cache`](https://github.com/isaacs/node-lru-cache). You can pass your own cache implementation by passing `options.cache.{get,set}` to the constructor.

```js
const App = require('@octokit/app')
const APP_ID = 1
const PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY-----\n...'

const CACHE = {}

const app = new App({
id: APP_ID,
privateKey: PRIVATE_KEY,
cache: {
get (key) {
return CACHE[key]
},
set (key, value) {
CACHE[key] = value
}
}
})
```

## License

[MIT](LICENSE)
8 changes: 5 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
module.exports = App

const getSignedJsonWebToken = require('./lib/get-signed-json-web-token')
const getCache = require('./lib/get-cache')
const getInstallationAccesToken = require('./lib/get-installation-access-token')
const getSignedJsonWebToken = require('./lib/get-signed-json-web-token')

function App ({ id, privateKey }) {
function App ({ id, privateKey, cache }) {
const state = {
id,
privateKey
privateKey,
cache: cache || getCache()
}
const api = {
getSignedJsonWebToken: getSignedJsonWebToken.bind(null, state),
Expand Down
13 changes: 13 additions & 0 deletions lib/get-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = getCache

// https://github.com/isaacs/node-lru-cache#readme
const LRU = require('lru-cache')

function getCache () {
return new LRU({
// cache max. 15000 tokens, that will use less than 10mb memory
max: 15000,
// Cache for 1 minute less than GitHub expiry
maxAge: 1000 * 60 * 59
})
}
13 changes: 11 additions & 2 deletions lib/get-installation-access-token.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ const getSignedJsonWebToken = require('./get-signed-json-web-token')

// https://developer.github.com/v3/apps/#create-a-new-installation-token
function getInstallationAccesToken (state, { installationId }) {
return request('POST /app/installations/:installation_id/access_tokens', {
const token = state.cache.get(installationId)
if (token) {
return Promise.resolve(token)
}

return request({
method: 'POST',
url: '/app/installations/:installation_id/access_tokens',
installation_id: installationId,
headers: {
accept: 'application/vnd.github.machine-man-preview+json',
// TODO: cache the installation token if it's been less than 60 minutes
authorization: `bearer ${getSignedJsonWebToken(state)}`
}
}).then(response => {
state.cache.set(installationId, response.data.token)
return response.data.token
})
.then(response => response.data.token)
}
21 changes: 20 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,18 @@
"homepage": "https://github.com/octokit/app.js#readme",
"dependencies": {
"@octokit/request": "^2.1.2",
"jsonwebtoken": "^8.3.0"
"jsonwebtoken": "^8.3.0",
"lru-cache": "^5.1.1"
},
"devDependencies": {
"chai": "^4.1.2",
"coveralls": "^3.0.2",
"lolex": "^2.7.4",
"lolex": "^2.7.5",
"mocha": "^5.2.0",
"nock": "^9.4.0",
"nyc": "^13.1.0",
"standard": "^12.0.1",
"semantic-release": "^15.12.1"
"semantic-release": "^15.12.1",
"simple-mock": "^0.8.0",
"standard": "^12.0.1"
}
}
99 changes: 97 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
/* global describe, beforeEach, it */

const { expect } = require('chai')
const nock = require('nock')
const lolex = require('lolex')
const nock = require('nock')
const simple = require('simple-mock')

const App = require('..')
const APP_ID = 1
Expand Down Expand Up @@ -39,7 +40,7 @@ const BEARER = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjAsImV4cCI6NjAsIml
// simulate the beginning of unix time so that Date.now() returns 0
// that way the signed token is always the same
// Documentation: https://git.io/fASyr
lolex.install({ now: 0, toFake: ['Date'] })
const clock = lolex.install({ now: 0, toFake: ['Date', 'setTimeout'] })

describe('app.js', () => {
let app
Expand Down Expand Up @@ -74,4 +75,98 @@ describe('app.js', () => {
expect(token).to.equal('foo')
})
})

it('gets installation token from cache', () => {
nock('https://api.github.com')
.post('/app/installations/123/access_tokens')
.reply(201, {
token: 'foo'
})

return app.getInstallationAccesToken({ installationId: 123 })
.then(token => {
expect(token).to.equal('foo')

return app.getInstallationAccesToken({ installationId: 123 })
})
.then(token => {
expect(token).to.equal('foo')
})
})

it('caches based on installation id', () => {
nock('https://api.github.com')
.post('/app/installations/123/access_tokens')
.reply(201, {
token: 'foo'
})
.post('/app/installations/456/access_tokens')
.reply(201, {
token: 'bar'
})

return app.getInstallationAccesToken({ installationId: 123 })
.then(token => {
expect(token).to.equal('foo')

return app.getInstallationAccesToken({ installationId: 456 })
})
.then(token => {
expect(token).to.equal('bar')
})
})

const oneHourInMs = 1000 * 60 * 60
it('request installation again after timeout', () => {
const mock = nock('https://api.github.com')
.post('/app/installations/123/access_tokens')
.reply(201, {
token: 'foo'
})
.post('/app/installations/123/access_tokens')
.reply(201, {
token: 'bar'
})

return app.getInstallationAccesToken({ installationId: 123 })
.then(token => {
expect(token).to.equal('foo')

return new Promise(resolve => {
setTimeout(resolve, oneHourInMs)
clock.tick(oneHourInMs)
})
})
.then(() => {
return app.getInstallationAccesToken({ installationId: 123 })
})
.then(token => {
expect(token).to.equal('bar')
expect(mock.pendingMocks()).to.deep.equal([])
})
}).timeout(oneHourInMs + 2000)

it('supports custom cache', () => {
nock('https://api.github.com')
.post('/app/installations/123/access_tokens')
.reply(201, {
token: 'foo'
})

const options = {
id: APP_ID,
privateKey: PRIVATE_KEY,
cache: {
get: simple.stub(),
set: simple.stub()
}
}
const appWithCustomCache = new App(options)

return appWithCustomCache.getInstallationAccesToken({ installationId: 123 })
.then(token => {
expect(options.cache.get.callCount).to.equal(1)
expect(options.cache.set.callCount).to.equal(1)
})
})
})

0 comments on commit 15478ed

Please sign in to comment.