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
7 changes: 6 additions & 1 deletion src/FaableAuthClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,11 @@ export class FaableAuthClient extends Base {
(...args) => this._debug(...args)
)
this.audience = config.audience
// The default scope of every authorize this client starts. Never assigned
// up to 3.8.0: an SPA asking for an RBAC Api's permissions got a token
// with an empty `permissions` claim (Auth grants requested ∩ catalog ∩
// role grants), and nothing said why.
this.scope = config.scope

this.api = new FaableAuthApi(this.domainUrl, { debug })

Expand Down Expand Up @@ -2741,7 +2746,7 @@ export class FaableAuthClient extends Base {
options.redirectTo || this.redirectUri || window?.location.origin,
response_type: resolveResponseType(options, isBrowser()),
audience: options.audience ?? this.audience,
scope: options.scope,
scope: options.scope || this.scope,
connection: options.connection,
// Space-delimited, per OIDC Core §3.1.2.1.
acr_values: Array.isArray(options.acr_values)
Expand Down
19 changes: 13 additions & 6 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,11 @@ export interface AuthorizationParams {
acr_values?: string

/**
* The default scope to be used on authentication requests.
* The scope to request, space-separated.
*
* This defaults to `profile email` if not set. If you are setting extra scopes and require
* `profile` and `email` to be included then you must include them in the provided scope.
*
* Note: The `openid` scope is **always applied** regardless of this setting.
* It replaces the default (`openid profile email`) instead of adding to it:
* include `openid`, `profile` and `email` yourself when you still want them
* alongside extra scopes such as an Api's permissions.
*/
scope?: string

Expand Down Expand Up @@ -441,7 +440,15 @@ export type FaableAuthClientConfig = {
clientId: string

// Optional
/** Space-separated scopes. Defaults to `openid profile email`. */
/**
* Default space-separated scope of the authorize requests this client
* starts (`signIn`, `signInWithOauthConnection`, `buildAuthorizeUrl`,
* `getTokenSilently`…); a `scopes`/`scope` passed to a call overrides it.
* Unset, they ask for `openid profile email` (`buildAuthorizeUrl` sends
* none and leaves it to the server). It replaces that default rather than
* extending it, so include `openid profile email` along with extra scopes —
* e.g. the permissions of an RBAC Api set as `audience`.
*/
scope?: string
/**
* Default API audience the access tokens issued for this client should be
Expand Down
105 changes: 105 additions & 0 deletions tests/unit/configScope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { FaableAuthClient } from '../../src/FaableAuthClient'
import type { SupportedStorage } from '../../src/lib/types'

// `createClient({ scope })` es el scope por defecto de cada /authorize. Hasta
// 3.8.0 el constructor no lo asignaba y viajaba siempre `openid profile
// email`: una SPA con `audience` de una Api con RBAC recibía un access token
// con `permissions` vacío (Auth concede pedidos ∩ catálogo ∩ roles).

const h = vi.hoisted(() => {
const loc = {
href: 'https://app.example.com/admin',
origin: 'https://app.example.com'
}
return {
loc,
fakeWindow: {
location: loc,
history: { state: null, replaceState: () => {} },
addEventListener: () => {},
removeEventListener: () => {}
}
}
})

vi.mock('../../src/lib/globals', () => ({
window: h.fakeWindow,
document: {},
fetch: async () => ({ ok: true, status: 200, json: async () => ({}) })
}))

const inMemoryStorage = (): SupportedStorage => {
const store = new Map<string, string>()
return {
getItem: k => store.get(k) ?? null,
setItem: (k, v) => void store.set(k, v),
removeItem: k => void store.delete(k)
}
}

const SCOPE = 'openid profile email instances:admin bookings:read'

const client = (scope?: string) =>
new FaableAuthClient({
domain: 'https://tenant.auth.faable.link',
clientId: 'test-client',
storage: inMemoryStorage(),
autoRefreshToken: false,
audience: 'https://api.example.com',
...(scope !== undefined ? { scope } : {})
} as any)

const authorizeUrl = async (
auth: FaableAuthClient,
call: 'signIn' | 'signInWithOauthConnection',
scopes?: string
) => {
const { data } = await auth[call]({
skipBrowserRedirect: true,
...(scopes ? { scopes } : {})
})
return new URL(data!.url!)
}

beforeEach(() => {
vi.restoreAllMocks()
vi.stubGlobal('document', {})
vi.stubGlobal('window', h.fakeWindow)
})

describe('scope de createClient', () => {
it.each(['signIn', 'signInWithOauthConnection'] as const)(
'%s pide el scope configurado',
async call => {
const url = await authorizeUrl(client(SCOPE), call)

expect(url.searchParams.get('scope')).toBe(SCOPE)
expect(url.searchParams.get('audience')).toBe('https://api.example.com')
}
)

it('el `scopes` de la llamada manda sobre el configurado', async () => {
const url = await authorizeUrl(client(SCOPE), 'signIn', 'openid')

expect(url.searchParams.get('scope')).toBe('openid')
})

it('sin scope configurado sigue pidiendo openid profile email', async () => {
const url = await authorizeUrl(client(), 'signIn')

expect(url.searchParams.get('scope')).toBe('openid profile email')
})

it('buildAuthorizeUrl también usa el scope configurado', () => {
const url = new URL(client(SCOPE).buildAuthorizeUrl())

expect(url.searchParams.get('scope')).toBe(SCOPE)
})

it('buildAuthorizeUrl sin scope configurado no añade ninguno', () => {
const url = new URL(client().buildAuthorizeUrl())

expect(url.searchParams.has('scope')).toBe(false)
})
})
Loading