-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathmiddleware.ts
162 lines (154 loc) · 4.33 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { RequestLike, validateSignature } from 'http-signature-utils'
import Koa from 'koa'
import { Limits, parseLimits } from '../payment/outgoing/limits'
import { HttpSigContext, PaymentPointerContext } from '../../app'
import { AccessAction, AccessType } from 'open-payments'
import { TokenInfo } from 'token-introspection'
import { isActiveTokenInfo } from 'token-introspection'
export type RequestAction = Exclude<AccessAction, 'read-all' | 'list-all'>
export const RequestAction: Record<string, RequestAction> = Object.freeze({
Create: 'create',
Read: 'read',
Complete: 'complete',
List: 'list'
})
export interface Grant {
id: string
limits?: Limits
}
export interface Access {
type: string
actions: AccessAction[]
identifier?: string
}
function contextToRequestLike(ctx: HttpSigContext): RequestLike {
return {
url: ctx.href,
method: ctx.method,
headers: ctx.headers,
body: ctx.request.body ? JSON.stringify(ctx.request.body) : undefined
}
}
export function createTokenIntrospectionMiddleware({
requestType,
requestAction
}: {
requestType: AccessType
requestAction: RequestAction
}) {
return async (
ctx: PaymentPointerContext,
next: () => Promise<unknown>
): Promise<void> => {
const config = await ctx.container.use('config')
try {
const parts = ctx.request.headers.authorization?.split(' ')
if (parts?.length !== 2 || parts[0] !== 'GNAP') {
ctx.throw(401, 'Unauthorized')
}
const token = parts[1]
const tokenIntrospectionClient = await ctx.container.use(
'tokenIntrospectionClient'
)
let tokenInfo: TokenInfo
try {
tokenInfo = await tokenIntrospectionClient.introspect({
access_token: token
})
} catch (err) {
ctx.throw(401, 'Invalid Token')
}
if (!isActiveTokenInfo(tokenInfo)) {
ctx.throw(403, 'Inactive Token')
}
ctx.clientKey = tokenInfo.key.jwk
// TODO
// https://github.com/interledger/rafiki/issues/835
const access = tokenInfo.access.find((access: Access) => {
if (
access.type !== requestType ||
(access.identifier && access.identifier !== ctx.paymentPointer.url)
) {
return false
}
if (
requestAction === AccessAction.Read &&
access.actions.includes(AccessAction.ReadAll)
) {
return true
}
if (
requestAction === AccessAction.List &&
access.actions.includes(AccessAction.ListAll)
) {
return true
}
return access.actions.find((tokenAction: AccessAction) => {
if (isActiveTokenInfo(tokenInfo) && tokenAction === requestAction) {
// Unless the relevant token action is ReadAll/ListAll add the
// clientId to ctx for Read/List filtering
ctx.clientId = tokenInfo.client_id
return true
}
return false
})
})
if (!access) {
ctx.throw(403, 'Insufficient Grant')
}
if (
requestType === AccessType.OutgoingPayment &&
requestAction === AccessAction.Create
) {
ctx.grant = {
id: tokenInfo.grant,
limits: access['limits'] ? parseLimits(access['limits']) : undefined
}
}
await next()
} catch (err) {
if (err && err['status'] === 401) {
ctx.status = 401
ctx.message = err['message']
ctx.set('WWW-Authenticate', `GNAP as_uri=${config.authServerGrantUrl}`)
} else {
throw err
}
}
}
}
export const httpsigMiddleware = async (
ctx: HttpSigContext,
next: () => Promise<unknown>
): Promise<void> => {
// TODO: look up client jwks.json
// https://github.com/interledger/rafiki/issues/737
if (!ctx.clientKey) {
const logger = await ctx.container.use('logger')
logger.warn(
{
grant: ctx.grant
},
'missing grant key'
)
ctx.throw(500)
}
try {
if (!(await validateSignature(ctx.clientKey, contextToRequestLike(ctx)))) {
ctx.throw(401, 'Invalid signature')
}
} catch (err) {
if (err instanceof Koa.HttpError) {
throw err
}
const logger = await ctx.container.use('logger')
logger.warn(
{
err
},
'httpsig error'
)
ctx.throw(401, `Invalid signature`)
}
await next()
}