Skip to content
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

feat(auth): inspect access during token introspection #2788

Merged
merged 18 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 209 additions & 0 deletions packages/auth/src/access/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { v4 } from 'uuid'
import { IocContract } from '@adonisjs/fold'
import { Knex } from 'knex'
import { faker } from '@faker-js/faker'
import {
AccessItem,
AccessType,
AccessAction
} from '@interledger/open-payments'

import { AppServices } from '../app'
import { Access, toOpenPaymentsAccess } from './model'
import { Grant, GrantState, StartMethod, FinishMethod } from '../grant/model'
import { initIocContainer } from '..'
import { Config } from '../config/app'
import { createTestApp, TestContainer } from '../tests/app'
import { truncateTables } from '../tests/tableManager'
import { generateToken, generateNonce } from '../shared/utils'
import { compareRequestAndGrantAccessItems } from './utils'

describe('Access utilities', (): void => {
let deps: IocContract<AppServices>
let appContainer: TestContainer
let trx: Knex.Transaction
let identifier: string
let grant: Grant
let grantAccessItem: Access

const receiver: string =
'https://wallet.com/alice/incoming-payments/12341234-1234-1234-1234-123412341234'

beforeAll(async (): Promise<void> => {
deps = initIocContainer(Config)
appContainer = await createTestApp(deps)
})

beforeEach(async (): Promise<void> => {
identifier = `https://example.com/${v4()}`
grant = await Grant.query(trx).insertAndFetch({
state: GrantState.Processing,
startMethod: [StartMethod.Redirect],
continueToken: generateToken(),
continueId: v4(),
finishMethod: FinishMethod.Redirect,
finishUri: 'https://example.com/finish',
clientNonce: generateNonce(),
client: faker.internet.url({ appendSlash: false })
})

grantAccessItem = await Access.query(trx).insertAndFetch({
grantId: grant.id,
type: AccessType.OutgoingPayment,
actions: [AccessAction.Read, AccessAction.Create, AccessAction.List],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
})
})

afterEach(async (): Promise<void> => {
await truncateTables(appContainer.knex)
})

afterAll(async (): Promise<void> => {
await appContainer.shutdown()
})

test('Can compare an access item on a grant and an access item from a request', async (): Promise<void> => {
const requestAccessItem: AccessItem = {
type: 'outgoing-payment',
actions: ['create', 'read', 'list'],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
}

expect(
compareRequestAndGrantAccessItems(
requestAccessItem,
toOpenPaymentsAccess(grantAccessItem)
)
).toBe(true)
})

test('Can compare an access item on a grant and an access item from a request with partial actions', async (): Promise<void> => {
const requestAccessItem: AccessItem = {
type: 'outgoing-payment',
actions: ['read'],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
}

expect(
compareRequestAndGrantAccessItems(
requestAccessItem,
toOpenPaymentsAccess(grantAccessItem)
)
).toBe(true)
})

test('Can compare an access item on a grant and an access item from a request with a subaction of the grant', async (): Promise<void> => {
const grantAccessItemSuperAction = await Access.query(trx).insertAndFetch({
grantId: grant.id,
type: AccessType.OutgoingPayment,
actions: [AccessAction.ReadAll],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
})

const requestAccessItem: AccessItem = {
type: 'outgoing-payment',
actions: ['read'],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
}

expect(
compareRequestAndGrantAccessItems(
requestAccessItem,
toOpenPaymentsAccess(grantAccessItemSuperAction)
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need

Suggested change
)
).toBe(true)

or does expect() just work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it works, updated just to be sure

).toBe(true)
})

test('access comparison fails if grant action items are insufficient', async (): Promise<void> => {
const identifier = `https://example.com/${v4()}`
const receiver =
'https://wallet.com/alice/incoming-payments/12341234-1234-1234-1234-123412341234'
const requestAccessItem: AccessItem = {
type: 'outgoing-payment',
actions: ['create', 'read', 'list'],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
}

const grant = await Grant.query(trx).insertAndFetch({
state: GrantState.Processing,
startMethod: [StartMethod.Redirect],
continueToken: generateToken(),
continueId: v4(),
finishMethod: FinishMethod.Redirect,
finishUri: 'https://example.com/finish',
clientNonce: generateNonce(),
client: faker.internet.url({ appendSlash: false })
})

const grantAccessItem = await Access.query(trx).insertAndFetch({
grantId: grant.id,
type: AccessType.OutgoingPayment,
actions: [AccessAction.Read, AccessAction.Create],
identifier,
limits: {
receiver,
debitAmount: {
value: '400',
assetCode: 'USD',
assetScale: 2
}
}
})

expect(
compareRequestAndGrantAccessItems(
requestAccessItem,
toOpenPaymentsAccess(grantAccessItem)
)
).toBe(false)
})
})
47 changes: 47 additions & 0 deletions packages/auth/src/access/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { isDeepStrictEqual } from 'util'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how did I not realize this was in the node standard library? Cool.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just discovered it when completing this PR. I knew there surely was a library that could handle this but I wasn't expecting a node-native solution either!

import { AccessItem, AccessAction } from '@interledger/open-payments'

export function compareRequestAndGrantAccessItems(
requestAccessItem: AccessItem,
grantAccessItem: AccessItem
): boolean {
const { actions: requestAccessItemActions, ...restOfRequestAccessItem } =
requestAccessItem
const { actions: grantAccessItemActions, ...restOfgrantAccessItem } =
grantAccessItem

for (const actionItem of requestAccessItemActions) {
if (
!grantAccessItemActions.find(
(grantAccessAction) =>
grantAccessAction === actionItem ||
(actionItem === AccessAction.Read &&
grantAccessAction === AccessAction.ReadAll) ||
(actionItem === AccessAction.List &&
grantAccessAction === AccessAction.ListAll)
)
)
return false
}

Object.keys(restOfRequestAccessItem).forEach((key) => {
const requestAccessItemValue =
restOfRequestAccessItem[key as keyof typeof restOfRequestAccessItem]
if (
typeof requestAccessItemValue === 'object' &&
!isDeepStrictEqual(
requestAccessItemValue,
restOfgrantAccessItem[key as keyof typeof restOfgrantAccessItem]
)
) {
return false
} else if (
requestAccessItemValue !==
restOfgrantAccessItem[key as keyof typeof restOfgrantAccessItem]
) {
return false
}
})

return true
}
124 changes: 123 additions & 1 deletion packages/auth/src/accessToken/routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ import { AccessToken } from './model'
import { Access } from '../access/model'
import { AccessTokenRoutes, IntrospectContext } from './routes'
import { generateNonce, generateToken } from '../shared/utils'
import { AccessType, AccessAction } from '@interledger/open-payments'
import {
AccessType,
AccessAction,
AccessItem
} from '@interledger/open-payments'
import { GrantService } from '../grant/service'
import { AccessTokenService } from './service'
import { GNAPErrorCode } from '../shared/gnapErrors'
Expand Down Expand Up @@ -199,6 +203,124 @@ describe('Access Token Routes', (): void => {
active: false
})
})

test('Successfully introspects token with correct access', async (): Promise<void> => {
const ctx = createContext<IntrospectContext>(
{
headers: {
Accept: 'application/json'
},
url: '/',
method: 'POST'
},
{}
)

ctx.request.body = {
access_token: token.value,
access: [BASE_ACCESS as AccessItem]
}

await expect(accessTokenRoutes.introspect(ctx)).resolves.toBeUndefined()
expect(ctx.response).toSatisfyApiSpec()
expect(ctx.status).toBe(200)
expect(ctx.response.get('Content-Type')).toBe(
'application/json; charset=utf-8'
)

expect(ctx.body).toEqual({
active: true,
grant: grant.id,
access: [
{
type: access.type,
actions: access.actions,
limits: access.limits,
identifier: access.identifier
}
],
client: CLIENT
})
})

test('Successfully introspects token with partial access', async (): Promise<void> => {
const ctx = createContext<IntrospectContext>(
{
headers: {
Accept: 'application/json'
},
url: '/',
method: 'POST'
},
{}
)

ctx.request.body = {
access_token: token.value,
access: [
{
...(BASE_ACCESS as AccessItem),
actions: ['read']
}
]
}

await expect(accessTokenRoutes.introspect(ctx)).resolves.toBeUndefined()
expect(ctx.response).toSatisfyApiSpec()
expect(ctx.status).toBe(200)
expect(ctx.response.get('Content-Type')).toBe(
'application/json; charset=utf-8'
)

expect(ctx.body).toEqual({
active: true,
grant: grant.id,
access: [
{
type: access.type,
actions: access.actions,
limits: access.limits,
identifier: access.identifier
}
],
client: CLIENT
})
})

test('Cannot introspect token with incorrect access', async (): Promise<void> => {
const ctx = createContext<IntrospectContext>(
{
headers: {
Accept: 'application/json'
},
url: '/',
method: 'POST'
},
{}
)

ctx.request.body = {
access_token: token.value,
access: [
{
...BASE_ACCESS,
type: 'incoming-payment',
actions: ['read-all']
}
]
}

await expect(accessTokenRoutes.introspect(ctx)).resolves.toBeUndefined()
expect(ctx.response).toSatisfyApiSpec()
expect(ctx.status).toBe(200)
expect(ctx.response.get('Content-Type')).toBe(
'application/json; charset=utf-8'
)

expect(ctx.body).toEqual({
active: false
})
})
})

describe('Revocation', (): void => {
Expand Down
Loading
Loading