Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
42 changes: 26 additions & 16 deletions server/test/monitoring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,31 +69,41 @@ describe('obpRoleCheck', () => {
})
afterEach(() => vi.unstubAllGlobals())

const answer = (status: number, modes: string[] = []) =>
Promise.resolve(new Response(JSON.stringify({ allowed_for_auth_modes: modes }), { status }))

it('allows a token OBP-API allows for UserOrApplication, asking at SYS', async () => {
fetchMock.mockReturnValueOnce(answer(200, ['ApplicationOnly', 'UserOrApplication']))
const answer = (status: number, allowed = false) =>
Promise.resolve(new Response(JSON.stringify({ allowed }), { status }))
// what an older OBP-API said instead of `allowed`
const answerOld = (modes: string[]) =>
Promise.resolve(new Response(JSON.stringify({ allowed_for_auth_modes: modes }), { status: 200 }))

it('allows a token OBP-API allows, asking at SYS', async () => {
fetchMock.mockReturnValueOnce(answer(200, true))
expect(await tokenMayUseAnyRole('http://obp', 't', ['CanGetTelemetry'])).toBe('allowed')
expect(fetchMock.mock.calls[0][0]).toBe('http://obp/obp/v7.0.0/banks/SYS/my/roles/CanGetTelemetry')
expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer t')
})

it('tries the next Role when one is not allowed', async () => {
fetchMock.mockReturnValueOnce(answer(200, ['UserOnly'])).mockReturnValueOnce(answer(200, ['UserOrApplication']))
fetchMock.mockReturnValueOnce(answer(200, false)).mockReturnValueOnce(answer(200, true))
expect(await tokenMayUseAnyRole('http://obp', 't', ['CanGetSystemLogCacheError', 'CanGetSystemLogCacheAll'])).toBe('allowed')
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('refuses when no Role is allowed, and says unauthorized when OBP-API rejects the token', async () => {
fetchMock.mockReturnValueOnce(answer(200, [])).mockReturnValueOnce(answer(404))
fetchMock.mockReturnValueOnce(answer(200, false)).mockReturnValueOnce(answer(404))
expect(await tokenMayUseAnyRole('http://obp', 't', ['A', 'B'])).toBe('forbidden')
fetchMock.mockReturnValueOnce(answer(401))
expect(await tokenMayUseAnyRole('http://obp', 'bad', ['A'])).toBe('unauthorized')
})

it('still understands the allowed_for_auth_modes of an older OBP-API', async () => {
fetchMock.mockReturnValueOnce(answerOld(['ApplicationOnly', 'UserOrApplication']))
expect(await tokenMayUseAnyRole('http://obp', 't', ['A'])).toBe('allowed')
fetchMock.mockReturnValueOnce(answerOld(['UserOnly']))
expect(await tokenMayUseAnyRole('http://obp', 't2', ['A'])).toBe('forbidden')
})

it('reuses an answer for a minute', async () => {
fetchMock.mockImplementation(() => answer(200, ['UserOrApplication']))
fetchMock.mockImplementation(() => answer(200, true))
await tokenMayUseAnyRole('http://obp', 't', ['A'], 0)
await tokenMayUseAnyRole('http://obp', 't', ['A'], 59_999)
expect(fetchMock).toHaveBeenCalledTimes(1)
Expand All @@ -104,19 +114,19 @@ describe('obpRoleCheck', () => {

describe('monitoring endpoints', () => {
// A fake OBP-API: what each token may do, as GET /banks/SYS/my/roles/ROLE answers it.
const tokens: Record<string, Record<string, string[]>> = {
'error-reader': { CanGetSystemLogCacheError: ['UserOrApplication'] },
'all-reader': { CanGetSystemLogCacheAll: ['UserOrApplication'] },
'telemetry-reader': { CanGetTelemetry: ['UserOrApplication'] },
'user-only': { CanGetSystemLogCacheAll: ['UserOnly'], CanGetTelemetry: ['UserOnly'] },
const tokens: Record<string, Record<string, boolean>> = {
'error-reader': { CanGetSystemLogCacheError: true },
'all-reader': { CanGetSystemLogCacheAll: true },
'telemetry-reader': { CanGetTelemetry: true },
'user-only': { CanGetSystemLogCacheAll: false, CanGetTelemetry: false },
'no-roles': {}
}
const fakeObpApi = vi.fn(async (url: string, init: any) => {
const token = init.headers.Authorization.slice('Bearer '.length)
if (!url.startsWith('http://obp/obp/v7.0.0/banks/SYS/my/roles/')) return new Response('{}', { status: 404 })
if (!(token in tokens)) return new Response('{}', { status: 401 })
const role = decodeURIComponent(url.split('/').pop()!)
return new Response(JSON.stringify({ allowed_for_auth_modes: tokens[token][role] ?? [] }), { status: 200 })
return new Response(JSON.stringify({ allowed: tokens[token][role] ?? false }), { status: 200 })
})

// Stands in for the session middleware: a header X-Test-Session-Token puts that token in the session.
Expand Down Expand Up @@ -151,7 +161,7 @@ describe('monitoring endpoints', () => {
const capitalised = (level: string) => level.charAt(0).toUpperCase() + level.slice(1)

it.each(levels)('returns the %s log cache to a token allowed its level Role or the All Role', async (level) => {
tokens[`${level}-only`] = { [`CanGetSystemLogCache${capitalised(level)}`]: ['UserOrApplication'] }
tokens[`${level}-only`] = { [`CanGetSystemLogCache${capitalised(level)}`]: true }
for (const token of [`${level}-only`, 'all-reader']) {
const res = await get(`/api/monitoring/log-cache/${level}`, token)
expect(res.status).toBe(200)
Expand All @@ -161,7 +171,7 @@ describe('monitoring endpoints', () => {

it.each(levels)('refuses the %s log cache to tokens without its Roles, returning no lines', async (level) => {
for (const token of ['no-roles', 'telemetry-reader', 'user-only', level === 'error' ? 'all-but-error' : 'error-reader']) {
tokens['all-but-error'] = { CanGetSystemLogCacheInfo: ['UserOrApplication'] }
tokens['all-but-error'] = { CanGetSystemLogCacheInfo: true }
const res = await get(`/api/monitoring/log-cache/${level}`, token)
expect(res.status).toBe(403)
expect(res.body.entries).toBeUndefined()
Expand Down
5 changes: 4 additions & 1 deletion server/utils/obpRoleCheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ import type { NextFunction, Request, Response } from 'express'

// Whether an OBP-API token may see what this server guards with an OBP Role. OBP-API answers, through
// GET /obp/v7.0.0/banks/SYS/my/roles/ROLE_NAME, with the same rules its own endpoints use: the token's
// User holds the Role, or its Consumer holds it as a Scope (auth mode UserOrApplication).
// User holds the Role as an Entitlement, or an application acting as itself holds it as a Scope on its Consumer.
// OBP-API v7.0.0 answers with `allowed` (true or false). An older OBP-API answered with `allowed_for_auth_modes`,
// the endpoint auth modes that would let the caller in; that is still understood.

export type RoleCheck = 'allowed' | 'unauthorized' | 'forbidden'

Expand All @@ -52,6 +54,7 @@ async function checkRole(obpApiHost: string, token: string, role: string): Promi
return 'forbidden'
}
const body = await response.json()
if (typeof body.allowed === 'boolean') return body.allowed ? 'allowed' : 'forbidden'
return body.allowed_for_auth_modes?.includes('UserOrApplication') ? 'allowed' : 'forbidden'
}

Expand Down
Loading