New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
@auth directive and context API #169
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
080040a
GraphQL authentication & context population
MrOrz 30c8a3e
Implement authentication, @auth directive and context field
MrOrz da8ccf6
Redundent jest.mock() as manual mocks for node modules will always load.
MrOrz f24191c
Add "manual" (auto) mock for redisClient so that all redisClient deps…
MrOrz 8dfa0c1
Prettier fix
MrOrz 5295edb
Avoid calling the real redisClient in unit tests
MrOrz 97b491d
Add userId in GraphQL context after authentication
MrOrz File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import { gql } from '../testUtils'; | ||
|
||
it('context rejects anonymous users', async () => { | ||
const result = await gql` | ||
{ | ||
context { | ||
state | ||
} | ||
} | ||
`(); | ||
expect(result).toMatchInlineSnapshot(` | ||
Object { | ||
"data": Object { | ||
"context": null, | ||
}, | ||
"errors": Array [ | ||
[GraphQLError: Invalid authentication header], | ||
], | ||
} | ||
`); | ||
}); | ||
|
||
it('Returns user context', async () => { | ||
const result = await gql` | ||
{ | ||
context { | ||
state | ||
issuedAt | ||
data { | ||
searchedText | ||
} | ||
} | ||
} | ||
`( | ||
{}, | ||
{ | ||
userId: 'U12345678', | ||
userContext: { | ||
state: 'CHOOSING_ARTICLE', | ||
issuedAt: 1586013070089, | ||
data: { | ||
searchedText: 'Foo', | ||
}, | ||
}, | ||
} | ||
); | ||
expect(result).toMatchInlineSnapshot(` | ||
Object { | ||
"data": Object { | ||
"context": Object { | ||
"data": Object { | ||
"searchedText": "Foo", | ||
}, | ||
"issuedAt": 1586013070089, | ||
"state": "CHOOSING_ARTICLE", | ||
}, | ||
}, | ||
} | ||
`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
jest.mock('src/lib/redisClient'); | ||
|
||
import { getContext } from '../'; | ||
import redis from 'src/lib/redisClient'; | ||
|
||
beforeEach(() => { | ||
redis.get.mockClear(); | ||
}); | ||
|
||
describe('getContext', () => { | ||
it('generates null context for anonymous requests', async () => { | ||
const context = await getContext({ ctx: { req: { headers: {} } } }); | ||
|
||
expect(context).toMatchInlineSnapshot(` | ||
Object { | ||
"userContext": null, | ||
"userId": "", | ||
} | ||
`); | ||
}); | ||
|
||
it('generates null context for wrong credentials', async () => { | ||
redis.get.mockImplementationOnce(() => ({ | ||
nonce: 'correctpass', | ||
})); | ||
|
||
const context = await getContext({ | ||
ctx: { | ||
req: { | ||
headers: { | ||
authorization: `basic ${Buffer.from('user1:wrongpass').toString( | ||
'base64' | ||
)}`, | ||
}, | ||
}, | ||
}, | ||
}); | ||
|
||
expect(context).toMatchInlineSnapshot(` | ||
Object { | ||
"userContext": null, | ||
"userId": "user1", | ||
} | ||
`); | ||
}); | ||
|
||
it('reads userContext for logged-in requests', async () => { | ||
redis.get.mockImplementationOnce(() => ({ | ||
nonce: 'correctpass', | ||
foo: 'bar', | ||
})); | ||
|
||
const context = await getContext({ | ||
ctx: { | ||
req: { | ||
headers: { | ||
authorization: `basic ${Buffer.from('user1:correctpass').toString( | ||
'base64' | ||
)}`, | ||
}, | ||
}, | ||
}, | ||
}); | ||
|
||
expect(context).toMatchInlineSnapshot(` | ||
Object { | ||
"userContext": Object { | ||
"foo": "bar", | ||
"nonce": "correctpass", | ||
}, | ||
"userId": "user1", | ||
} | ||
`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,3 @@ | ||
jest.mock('@line/bot-sdk'); | ||
import { | ||
mockedGetNumberOfMessageDeliveries, | ||
mockedGetNumberOfFollowers, | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { AuthenticationError } from 'apollo-server-koa'; | ||
import { SchemaDirectiveVisitor } from 'graphql-tools'; | ||
|
||
/** | ||
* When field with @auth is accessed, make sure the user is logged in (i.e. `userContext` in context). | ||
*/ | ||
class AuthDirective extends SchemaDirectiveVisitor { | ||
visitFieldDefinition(field) { | ||
const { resolve } = field; | ||
|
||
field.resolve = (...args) => { | ||
const [, , context] = args; | ||
|
||
if (!context.userId || !context.userContext) { | ||
throw new AuthenticationError('Invalid authentication header'); | ||
} | ||
|
||
return resolve(...args); | ||
}; | ||
} | ||
} | ||
|
||
export default AuthDirective; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
@@ -1,5 +1,10 @@ | ||||||||||
directive @auth on FIELD_DEFINITION | ||||||||||
|
||||||||||
type Query { | ||||||||||
insights: MessagingAPIInsight | ||||||||||
|
||||||||||
# Current user's chatbot context | ||||||||||
context: UserContext @auth | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. context is a little bit confusing with apollo context |
||||||||||
} | ||||||||||
|
||||||||||
type MessagingAPIInsight { | ||||||||||
|
@@ -123,3 +128,16 @@ enum MessagingAPIInsightStatus { | |||||||||
UNREADY | ||||||||||
OUT_OF_SERVICE | ||||||||||
} | ||||||||||
|
||||||||||
type UserContext { | ||||||||||
state: String | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggest to specify non-nullable
Suggested change
|
||||||||||
issuedAt: Float | ||||||||||
data: StateData | ||||||||||
} | ||||||||||
|
||||||||||
type StateData { | ||||||||||
searchedText: String | ||||||||||
selectedArticleId: ID | ||||||||||
selectedArticleText: String | ||||||||||
selectedReplyId: ID | ||||||||||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export default { | ||
get: jest.fn(), | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where do we generate
nonce
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's not included in this PR, plan to revisit this logic when implementing LIFF.
Actually I think I will use JWT (introduced in #172 ) to replace nonce, since
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually I found that the recommended way for LINE to make sure a request come from LIFF is via token validation:
getAccessToken
API/oauth2/v2.1/verify?access_token=
Ref: https://www.facebook.com/groups/linebot/permalink/2489421594721745/
In this way, server do not need to send any form of
nonce
/ JWT to LIFF using URL params. Instead, it is LINE server that generates a token (to LIFF) and is asked to verify (from API server).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note:
In the end I decided to use JWT, implemented in this PR: https://github.com/cofacts/rumors-line-bot/pull/178/files
The reason why I use JWT is that I need to preserve state in the JWT, it's not something that LINE server knows, thus access tokens from LINE does not meet mu need.