diff --git a/src/components/auth/AccountMerge.mount.test.ts b/src/components/auth/AccountMerge.mount.test.ts index 0902c45e..e7371c62 100644 --- a/src/components/auth/AccountMerge.mount.test.ts +++ b/src/components/auth/AccountMerge.mount.test.ts @@ -4,12 +4,17 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { button, click, compileClientComponent, content, flush, moduleDefault, mountApp } from '@/test/clientRender' import type { MergeStep, OtherAccount } from '@/composables/useAccountMerge' import type { MergeAccountResponse, UserInfoResponse } from '@/lib/api' +import { DEFAULT_PORTAL_CONFIG, type LoginOption, type PortalRuntimeConfig } from '@/lib/config' const step = ref('idle') const failure = ref(null) const other = shallowRef(null) const result = shallowRef(null) -const actions = { start: vi.fn(), copyVault: vi.fn(), merge: vi.fn(), attach: vi.fn(), cancel: vi.fn() } +const actions = { choose: vi.fn(), start: vi.fn(), copyVault: vi.fn(), merge: vi.fn(), attach: vi.fn(), cancel: vi.fn() } +const GFBIO: LoginOption = { name: 'GFBio SSO', description: '', logo: '', params: {}, linkParams: {}, upstream: { provider: 'gfbio', bridge: 'https://bridge.test/gfbio' } } +const LEGACY: LoginOption = { name: 'Aruna (legacy)', description: '', logo: '', params: {}, linkParams: {} } +const LOGINS: PortalRuntimeConfig = { ...DEFAULT_PORTAL_CONFIG, login: { options: [GFBIO, LEGACY], accountUrl: '' } } +let config: PortalRuntimeConfig = DEFAULT_PORTAL_CONFIG const age = ref(30) const userInfo = ref | null>(null) @@ -23,8 +28,15 @@ const Notice = defineComponent({ props: { title: String }, setup: (props, { slots }) => () => h('div', [props.title, slots.default?.()]), }) +const LoginOptions = compileClientComponent(new URL('./LoginOptions.vue', import.meta.url), { + vue: VueRuntime, + '@/components/auth/ProviderLogo.vue': moduleDefault(defineComponent(() => () => null)), + '@/lib/config': { portalConfig: () => config }, +}) const AccountMerge = compileClientComponent(new URL('./AccountMerge.vue', import.meta.url), { vue: VueRuntime, + '@/components/auth/LoginOptions.vue': moduleDefault(LoginOptions), + '@/lib/config': { portalConfig: () => config }, '@lucide/vue': new Proxy({}, { get: () => defineComponent(() => () => null) }), '@/components/ui/Button.vue': moduleDefault(Button), '@/components/ui/IconTile.vue': moduleDefault(defineComponent(() => () => null)), @@ -71,6 +83,7 @@ beforeEach(() => { result.value = null age.value = 30 userInfo.value = null + config = DEFAULT_PORTAL_CONFIG for (const action of Object.values(actions)) action.mockReset() }) @@ -85,6 +98,40 @@ describe('adding another account', () => { app.unmount() }) + it('asks for the login of the other account when logins are configured', async () => { + config = LOGINS + const { root, app } = await render() + await click(button(root, 'Add account')) + expect(actions.choose).toHaveBeenCalledTimes(1) + expect(actions.start).not.toHaveBeenCalled() + step.value = 'choose' + await flush() + expect(content(root)).toContain('Choose how you sign in with the other account.') + await click(button(root, 'GFBio SSO')) + expect(actions.start).toHaveBeenCalledWith(GFBIO) + await click(button(root, 'Aruna (legacy)')) + expect(actions.start).toHaveBeenLastCalledWith(LEGACY) + app.unmount() + }) + + it('confirms an old own login through the chosen login', async () => { + config = LOGINS + step.value = 'confirm' + other.value = account() + age.value = 400 + const { root, app } = await render() + expect(content(root)).toContain('You confirm with your own login first.') + expect(() => button(root, 'Merge')).toThrow() + await click(button(root, 'GFBio SSO')) + expect(actions.merge).toHaveBeenCalledWith(GFBIO) + step.value = 'unregistered' + await flush() + expect(() => button(root, 'Attach sign-in')).toThrow() + await click(button(root, 'Aruna (legacy)')) + expect(actions.attach).toHaveBeenCalledWith(LEGACY) + app.unmount() + }) + it('names merged accounts and falls back to the short id', async () => { userInfo.value = { merged_user_ids: ['b0@R', 'c0@R'], diff --git a/src/components/auth/AccountMerge.vue b/src/components/auth/AccountMerge.vue index 9c0a088c..d9850bcf 100644 --- a/src/components/auth/AccountMerge.vue +++ b/src/components/auth/AccountMerge.vue @@ -2,6 +2,7 @@ // Adds another account the person can sign in with: it is merged into this one, or, when the // sign-in has no account yet, attached to it. Each step waits for a click of its own. import { computed } from 'vue' +import LoginOptions from '@/components/auth/LoginOptions.vue' import Button from '@/components/ui/Button.vue' import Dialog from '@/components/ui/Dialog.vue' import DialogContent from '@/components/ui/DialogContent.vue' @@ -14,6 +15,7 @@ import Notice from '@/components/ui/Notice.vue' import Spinner from '@/components/ui/Spinner.vue' import { useAruna } from '@/composables/useAruna' import { loginFresh, useAccountMerge } from '@/composables/useAccountMerge' +import { portalConfig } from '@/lib/config' import { truncateMiddle } from '@/lib/utils' import { ArrowRight, @@ -34,7 +36,9 @@ import { import type { Component } from 'vue' const { authToken, userInfo } = useAruna() -const { step, failure, other, result, start, copyVault, merge, attach, cancel } = useAccountMerge() +const { step, failure, other, result, choose, start, copyVault, merge, attach, cancel } = useAccountMerge() +// With configured logins the person picks the login of each sign-in, otherwise the realm's own. +const hasLogins = portalConfig().login.options.length > 0 const open = computed(() => step.value !== 'idle' || failure.value !== null) const name = computed(() => other.value?.info.user.name ?? 'That account') @@ -45,6 +49,13 @@ const merged = computed( const busy = computed(() => ['signing', 'loading', 'merging'].includes(step.value)) // The merge then asks for this account's login first. const loginOld = computed(() => step.value === 'confirm' && !loginFresh(authToken.value)) +// An old own login is renewed through the login the person picks. +const ownLogin = computed(() => hasLogins && ['confirm', 'unregistered'].includes(step.value) && !loginFresh(authToken.value)) + +function add() { + if (hasLogins) choose() + else void start() +} const title = computed(() => { switch (step.value) { @@ -113,7 +124,7 @@ function close(value: boolean) {
Add another account
Sign in with it once to merge it into this one.
- +
Merged accounts
@@ -134,9 +145,11 @@ function close(value: boolean) { {{ name }} is closed afterwards. Signing in with it opens this account. + Choose how you sign in with the other account. - + +
@@ -214,6 +227,11 @@ function close(value: boolean) {

You can now sign in with it.

+ + {{ failure }} @@ -222,9 +240,9 @@ function close(value: boolean) { diff --git a/src/components/auth/LoginOptions.vue b/src/components/auth/LoginOptions.vue new file mode 100644 index 00000000..6a9c3de9 --- /dev/null +++ b/src/components/auth/LoginOptions.vue @@ -0,0 +1,33 @@ + + + diff --git a/src/components/auth/ProviderLinks.mount.test.ts b/src/components/auth/ProviderLinks.mount.test.ts index 7bbe61aa..015e5302 100644 --- a/src/components/auth/ProviderLinks.mount.test.ts +++ b/src/components/auth/ProviderLinks.mount.test.ts @@ -111,6 +111,15 @@ describe('linked logins in settings', () => { app.unmount() }) + it('offers no link for an upstream login, which the account merge joins', async () => { + login = { options: [{ ...NFDI, upstream: { provider: 'iam4nfdi', bridge: 'https://bridge.test/v3-bridge/iam4nfdi' } }], accountUrl: ACCOUNT_URL } + const { root, app } = await render() + expect(content(root)).toContain('Add another account') + expect(content(root)).not.toContain('NFDI AAI') + expect(() => button(root, 'Link')).toThrow() + app.unmount() + }) + it('stays hidden for a session from another realm', async () => { userId.value = 'u1@Other' const { root, app } = await render() diff --git a/src/components/auth/ProviderLinks.vue b/src/components/auth/ProviderLinks.vue index dc587220..2447454d 100644 --- a/src/components/auth/ProviderLinks.vue +++ b/src/components/auth/ProviderLinks.vue @@ -18,7 +18,8 @@ const { currentUser, realm } = useAruna() const { linkProvider, providerLink, stage } = useAuth() const { options, accountUrl } = portalConfig().login -const linkable = options.filter((option) => Object.keys(option.linkParams).length) +// An upstream login has no Keycloak account to link to; the account merge joins it instead. +const linkable = options.filter((option) => !option.upstream && Object.keys(option.linkParams).length) // A session from another realm has no account at this realm's Keycloak. const shown = computed(() => { const user = currentUser.value diff --git a/src/components/auth/SignInDialog.test.ts b/src/components/auth/SignInDialog.test.ts index b9a5627f..a8840793 100644 --- a/src/components/auth/SignInDialog.test.ts +++ b/src/components/auth/SignInDialog.test.ts @@ -27,6 +27,11 @@ const PickerStub = defineComponent({ setup: (props, { emit }) => () => h('button', { 'data-only': props.onlyRealmIds?.join(','), onClick: () => emit('pick', HOME) }, 'Pick home realm'), }) +const loginOptions = compileClientComponent(new URL('./LoginOptions.vue', import.meta.url), { + vue: VueRuntime, + '@/components/auth/ProviderLogo.vue': moduleDefault(defineComponent(() => () => null)), + '@/lib/config': { portalConfig: () => config }, +}) const dialog = compileClientComponent(new URL('./SignInDialog.vue', import.meta.url), { vue: VueRuntime, 'vue-router': { useRouter: () => ({ push }) }, @@ -40,12 +45,11 @@ const dialog = compileClientComponent(new URL('./SignInDialog.vue', import.meta. '@/components/ui/Notice.vue': moduleDefault(Passthrough), '@/components/ui/Spinner.vue': moduleDefault(Passthrough), '@/components/federation/RealmPicker.vue': moduleDefault(PickerStub), - '@/components/auth/ProviderLogo.vue': moduleDefault(defineComponent(() => () => null)), + '@/components/auth/LoginOptions.vue': moduleDefault(loginOptions), '@/composables/signInChoice': { signInChoice }, '@/composables/useAruna': { useAruna: () => ({ realm: ref({ id: 'here', name: 'Demo realm' }), realmInfo }) }, '@/composables/useAuth': { useAuth: () => ({ signIn }) }, '@/composables/useFederation': { loginWithRealm }, - '@/lib/config': { portalConfig: () => config }, }) function option(name: string, params: Record = {}): LoginOption { @@ -94,6 +98,15 @@ describe('sign-in dialog', () => { app.unmount() }) + it('signs in with the upstream provider of a login', async () => { + const upstream = { provider: 'lifescience', bridge: 'https://bridge.test/v3-bridge/lifescience' } + config = { ...DEFAULT_PORTAL_CONFIG, login: { options: [{ ...option('LifeScience RI'), upstream }], accountUrl: '' } } + const { root, app } = await render() + await click(button(root, 'LifeScience RI')) + expect(signIn).toHaveBeenCalledWith({ redirectTo: '/app/data', onboardingSecret: 's1', upstream }) + app.unmount() + }) + it('logs in with another realm from the last row', async () => { loginWithRealm.mockResolvedValue(null) const { root, app } = await render() diff --git a/src/components/auth/SignInDialog.vue b/src/components/auth/SignInDialog.vue index c98225b8..0d660e96 100644 --- a/src/components/auth/SignInDialog.vue +++ b/src/components/auth/SignInDialog.vue @@ -12,12 +12,12 @@ import Button from '@/components/ui/Button.vue' import Notice from '@/components/ui/Notice.vue' import Spinner from '@/components/ui/Spinner.vue' import RealmPicker from '@/components/federation/RealmPicker.vue' -import ProviderLogo from '@/components/auth/ProviderLogo.vue' +import LoginOptions from '@/components/auth/LoginOptions.vue' import { signInChoice } from '@/composables/signInChoice' import { useAruna } from '@/composables/useAruna' import { useAuth } from '@/composables/useAuth' import { loginWithRealm } from '@/composables/useFederation' -import { portalConfig, type LoginOption } from '@/lib/config' +import type { LoginOption } from '@/lib/config' import type { VerifiedRealm } from '@/lib/federation/descriptor' import { Globe2, RefreshCw } from '@lucide/vue' @@ -25,18 +25,6 @@ const { signIn } = useAuth() const { realm, realmInfo } = useAruna() const router = useRouter() -const PLAIN_SIGN_IN: LoginOption = { - name: 'Realm account', - description: 'Sign in at this realm', - logo: '/brand/providers/aruna.webp', - params: {}, - linkParams: {}, -} -const configured = portalConfig().login.options -const choices = configured.length ? configured : [PLAIN_SIGN_IN] -const rowClass = - 'flex w-full items-center justify-center gap-3 rounded-md border border-border px-4 py-2.5 text-base font-medium text-foreground transition-colors hover:bg-muted/50' - const open = computed({ get: () => signInChoice.value !== null, set: (value: boolean) => { @@ -49,7 +37,8 @@ function choose(choice: LoginOption) { if (!options) return signInChoice.value = null const params = Object.keys(choice.params).length ? choice.params : undefined - void signIn(params ? { ...options, params } : options) + const upstream = choice.upstream + void signIn({ ...options, ...(params && { params }), ...(upstream && { upstream }) }) } // Login with an account of another realm: a popup at that realm, then a session here. @@ -83,13 +72,7 @@ async function loginElsewhere(home: VerifiedRealm) { Continue login with Choose how you want to sign in. -
    -
  • - -
  • +
  • -
+
{ currentUser.value = authToken.value ? { id: 'a1@R' } : null }) -vi.mock('./popupSignIn', () => ({ popupSignIn: () => popupSignIn(), SignInCancelled: class extends Error {} })) +vi.mock('./popupSignIn', () => ({ popupSignIn: (...args: unknown[]) => popupSignIn(...args), SignInCancelled: class extends Error {} })) vi.mock('./useAruna', () => ({ useAruna: () => ({ apiBaseUrl, @@ -127,6 +127,20 @@ describe('a first sign-in that matches an account', () => { expect(storage.has('aruna.oidc.verifier')).toBe(false) }) + it('signs in with the chosen upstream login and keeps no ID token for sign-out', async () => { + await matched() + const login = { name: 'NFDI AAI', description: '', logo: '', params: {}, linkParams: {}, upstream: { provider: 'iam4nfdi', bridge: 'https://bridge.test/iam4nfdi' } } + + await expect(joinExistingAccount(login)).resolves.toBe('/app/data') + + expect(popupSignIn).toHaveBeenCalledWith(login) + expect(calls.find((call) => call.path === '/access/token' && call.bearer === EXISTING_SIGN_IN)).toBeTruthy() + const [attached] = calls.filter((call) => call.path === '/access/users/me/subjects') + expect(attached.bearer).toBe('realm-of-existing') + expect(attached.body).toEqual({ token: NEW_SIGN_IN }) + expect(storage.has('aruna.oidc.idToken')).toBe(false) + }) + it('adds the new sign-in to the existing account the person signs in with', async () => { await matched() diff --git a/src/composables/accountMatch.ts b/src/composables/accountMatch.ts index fb6d5f5e..8355fe29 100644 --- a/src/composables/accountMatch.ts +++ b/src/composables/accountMatch.ts @@ -2,6 +2,7 @@ // sign-in to that account, or create a new one anyway. import { ref, watch } from 'vue' import { ApiError, apiErrorMessage, apiRequest, attachSignIn, issueToken, signInHasNoAccount } from '@/lib/api' +import type { LoginOption } from '@/lib/config' import { useAruna } from './useAruna' import { accountMatch, adoptSession, type AccountMatch } from './useAuth' import { loginFresh, mergeFailure } from './useAccountMerge' @@ -46,10 +47,10 @@ function begin() { } /** - * Signs in with the existing account in a popup and adds the new sign-in to it. Call it in a - * click handler. Returns the route to continue to, or null when it did not finish. + * Signs in with the existing account in a popup, through `login` once chosen, and adds the new + * sign-in to it. Call it in a click handler. Returns the route to continue to, or null. */ -export async function joinExistingAccount(): Promise { +export async function joinExistingAccount(login?: LoginOption): Promise { const match = accountMatch.value if (!match || matchBusy.value) return null if (!loginFresh(match.oidcToken)) { @@ -60,7 +61,7 @@ export async function joinExistingAccount(): Promise { begin() const { baseUrl, check } = fence(match) try { - const tokens = await popupSignIn() + const tokens = await popupSignIn(login) check() const token = await issueToken(tokens.id_token ?? tokens.access_token, baseUrl).catch((error: unknown) => { if (signInHasNoAccount(error)) throw new Error('That sign-in has no account either. Choose the one you used before.') @@ -73,7 +74,8 @@ export async function joinExistingAccount(): Promise { throw new Error('Your new sign-in already has an account. Sign in with it instead.') }) check() - await adoptSession(token, tokens.id_token) + // An upstream login has no Keycloak session to end at sign-out. + await adoptSession(token, login?.upstream ? undefined : tokens.id_token) // A newer match that arrived meanwhile keeps the choice open, so nothing navigates away. if (accountMatch.value !== match) return null accountMatch.value = null diff --git a/src/composables/popupSignIn.test.ts b/src/composables/popupSignIn.test.ts index d0eeee7e..c6b49107 100644 --- a/src/composables/popupSignIn.test.ts +++ b/src/composables/popupSignIn.test.ts @@ -6,6 +6,8 @@ import { setAuthOpener } from './useAuth' const PAGE_ORIGIN = 'https://portal.test' const TOKEN_ENDPOINT = 'https://idp.test/token' +const BRIDGE = 'https://bridge.test/v3-bridge/lifescience' +const LIFESCIENCE = { name: 'LifeScience RI', description: '', logo: '', params: {}, linkParams: {}, upstream: { provider: 'lifescience', bridge: BRIDGE } } function json(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) @@ -19,7 +21,10 @@ async function setup(served: Record = {}, opened: unknown = und const tokenForms: Record[] = [] vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (url.endsWith('/system/realm')) return json({ oidc_providers: [{ audience: 'portal', discovery_url: discoveryUrl }] }) + if (url.endsWith('/system/realm')) { + const upstream = { id: 'lifescience', audience: 'ls-client', discovery_url: 'https://ls.test/discovery' } + return json({ oidc_providers: [{ id: 'keycloak', audience: 'portal', discovery_url: discoveryUrl }, upstream] }) + } if (url === discoveryUrl) { return json({ issuer: 'https://idp.test', authorization_endpoint: 'https://idp.test/authorize', token_endpoint: TOKEN_ENDPOINT }) } @@ -27,6 +32,10 @@ async function setup(served: Record = {}, opened: unknown = und tokenForms.push(Object.fromEntries(new URLSearchParams(String(init?.body)))) return json({ access_token: 'a2', id_token: 'i2', token_type: 'Bearer' }) } + if (url === `${BRIDGE}/token`) { + tokenForms.push({ endpoint: url, ...Object.fromEntries(new URLSearchParams(String(init?.body))) }) + return json({ id_token: 'ls2', token_type: 'Bearer', expires_in: 300 }) + } return json({ error: 'unexpected' }, 404) })) const replace = vi.fn() @@ -74,6 +83,36 @@ describe('popupSignIn', () => { expect(receiveCallback(new URLSearchParams({ code: 'c2', state }))).toBe(false) }) + it('signs in with an upstream login at its bridge', async () => { + const { replace, tokenForms } = await setup() + const result = popupSignIn(LIFESCIENCE) + const url = await navigated(replace) + expect(`${url.origin}${url.pathname}`).toBe(`${BRIDGE}/authorize`) + expect(url.searchParams.get('client_id')).toBe('ls-client') + expect(url.searchParams.get('redirect_uri')).toBe(`${PAGE_ORIGIN}/auth/callback`) + expect(url.searchParams.get('code_challenge_method')).toBe('S256') + expect(url.searchParams.get('code_challenge')).toBeTruthy() + expect(url.searchParams.get('prompt')).toBe('login') + const state = url.searchParams.get('state')! + expect(state).toMatch(/^popup\.[\w-]{22}$/) + + receiveCallback(new URLSearchParams({ code: 'c3', state })) + await expect(result).resolves.toMatchObject({ id_token: 'ls2' }) + expect(tokenForms).toEqual([ + expect.objectContaining({ endpoint: `${BRIDGE}/token`, client_id: 'ls-client', code: 'c3', redirect_uri: `${PAGE_ORIGIN}/auth/callback` }), + ]) + expect(tokenForms[0].code_verifier).toBeTruthy() + }) + + it('sends the params of a legacy login to the realm provider', async () => { + const { replace } = await setup() + void popupSignIn({ ...LIFESCIENCE, upstream: undefined, params: { kc_idp_hint: 'lifescience' } }).catch(() => undefined) + const url = await navigated(replace) + expect(`${url.origin}${url.pathname}`).toBe('https://idp.test/authorize') + expect(url.searchParams.get('client_id')).toBe('portal') + expect(url.searchParams.get('kc_idp_hint')).toBe('lifescience') + }) + it('reports a blocked popup', async () => { await setup({}, null) await expect(popupSignIn()).rejects.toThrow('The browser blocked the sign-in window') diff --git a/src/composables/popupSignIn.ts b/src/composables/popupSignIn.ts index 05083dc7..d45803b0 100644 --- a/src/composables/popupSignIn.ts +++ b/src/composables/popupSignIn.ts @@ -7,6 +7,7 @@ import { randomUrlSafeString, type OidcTokenResponse, } from '@/lib/oidc' +import type { LoginOption } from '@/lib/config' import { POPUP_CHANNEL, POPUP_STATE_PREFIX } from '@/lib/popupHandoff' import { beginAuthRedirect, callbackUri, oidcClient, opensOutside, signInState } from './useAuth' @@ -65,25 +66,26 @@ function waitFor(state: string): Promise { } /** - * Signs in once more and returns the provider's tokens. Call it in a click handler: the web - * popup opens before the first await. + * Signs in once more with `login`, the realm's first provider without one, and returns the + * provider's tokens. Call it in a click handler: the web popup opens before the first await. */ -export async function popupSignIn(): Promise { +export async function popupSignIn(login?: LoginOption): Promise { const outside = opensOutside() const popup = outside ? null : window.open('about:blank', '_blank', 'popup,width=560,height=760') if (!outside && !popup) throw new Error('The browser blocked the sign-in window. Allow popups for this site.') try { - const { clientId, discovery, send } = await oidcClient() + const { clientId, authorization, token, send } = await oidcClient(login?.upstream) const verifier = randomUrlSafeString(48) const state = signInState(POPUP_STATE_PREFIX) const redirectUri = callbackUri() const url = buildAuthorizationUrl({ - authorizationEndpoint: discovery.authorization_endpoint, + authorizationEndpoint: authorization, clientId, redirectUri, state, codeChallenge: await pkceChallengeS256(verifier), freshLogin: true, + params: login?.params, }) const answer = waitFor(state) if (popup) popup.location.replace(url) @@ -94,7 +96,7 @@ export async function popupSignIn(): Promise { const code = params.get('code') if (!code) throw new Error('The identity provider did not return an authorization code.') return await exchangeAuthorizationCode({ - tokenEndpoint: discovery.token_endpoint, + tokenEndpoint: token, clientId, redirectUri, code, diff --git a/src/composables/useAccountMerge.test.ts b/src/composables/useAccountMerge.test.ts index ab9aa787..1d2b327c 100644 --- a/src/composables/useAccountMerge.test.ts +++ b/src/composables/useAccountMerge.test.ts @@ -6,7 +6,7 @@ const refresh = vi.fn(async () => undefined) const replaceToken = vi.fn() vi.mock('./popupSignIn', () => ({ - popupSignIn: () => popupSignIn(), + popupSignIn: (...args: unknown[]) => popupSignIn(...args), cancelPopup: vi.fn(), SignInCancelled: class extends Error {}, })) @@ -166,6 +166,39 @@ describe('account merge', () => { expect(merge.step.value).toBe('merged') }) + it('signs in with the chosen logins and merges with the upstream sign-in', async () => { + authToken.value = OWN_STALE + const upstream = (provider: string) => ({ name: provider, description: '', logo: '', params: {}, linkParams: {}, upstream: { provider, bridge: `https://bridge.test/${provider}` } }) + const merge = useAccountMerge() + merge.choose() + expect(merge.step.value).toBe('choose') + await merge.start(upstream('gfbio')) + expect(popupSignIn).toHaveBeenLastCalledWith(upstream('gfbio')) + expect(requests('GET', '/access/token')[0].bearer).toBe(OIDC_B) + expect(merge.step.value).toBe('confirm') + const ownOidc = jwt({ sub: 'ls-a', auth_time: ageSecs(1) }) + const renewed = jwt({ sub: A, auth_time: ageSecs(1) }) + popupSignIn.mockResolvedValueOnce({ id_token: ownOidc, token_type: 'Bearer' }) + answer('GET', '/access/token', ({ bearer }) => json({ token: bearer === ownOidc ? renewed : TOKEN_B })) + answer('POST', '/access/users/me/merge', json({ user_id: A, merged_user_id: B, attributes_not_copied: [] })) + + await merge.merge(upstream('lifescience')) + + expect(popupSignIn).toHaveBeenLastCalledWith(upstream('lifescience')) + const [sent] = requests('POST', '/access/users/me/merge') + expect(sent.bearer).toBe(renewed) + expect(sent.body).toEqual({ token: TOKEN_B }) + expect(merge.step.value).toBe('merged') + }) + + it('returns to the login choice when a chosen sign-in fails', async () => { + popupSignIn.mockRejectedValueOnce(new Error('Sign-in was rejected (access_denied).')) + const merge = useAccountMerge() + await merge.start({ name: 'GFBio SSO', description: '', logo: '', params: {}, linkParams: {} }) + expect(merge.step.value).toBe('choose') + expect(merge.failure.value).toContain('access_denied') + }) + it('refuses a new login of another account than this one', async () => { authToken.value = OWN_STALE const merge = await confirmed() diff --git a/src/composables/useAccountMerge.ts b/src/composables/useAccountMerge.ts index 3a09493c..e1b7e65a 100644 --- a/src/composables/useAccountMerge.ts +++ b/src/composables/useAccountMerge.ts @@ -19,6 +19,7 @@ import { type UserInfoResponse, type UserVaultHead, } from '@/lib/api' +import type { LoginOption } from '@/lib/config' import { assertCurrentSession, refreshContext, userInfo } from './aruna/state' import { refresh, replaceToken } from './aruna/session' import { tokenClaims } from './aruna/renewal' @@ -31,6 +32,7 @@ const OTHER_TOKEN_SECS = 15 * 60 export type MergeStep = | 'idle' + | 'choose' | 'signing' | 'loading' | 'unregistered' @@ -160,27 +162,34 @@ export function useAccountMerge() { await load(id, context) } - /** Signs in with the other account; call it in a click handler. */ - async function start() { + /** Asks which login the other account uses. */ + function choose() { + reset('choose') + failure.value = null + } + + /** Signs in with the other account, through `login` once chosen; call it in a click handler. */ + async function start(login?: LoginOption) { reset('signing') failure.value = null const id = run const context = refreshContext() try { - const tokens = await popupSignIn() + const tokens = await popupSignIn(login) guard(id, context.epoch) signInToken = tokens.id_token ?? tokens.access_token await exchange(id, context) } catch (error) { - if (id === run) fail(error, 'idle') + if (id === run) fail(error, login ? 'choose' : 'idle') } } - // A login older than 5 minutes signs in again first; a token of another account is refused. - async function ownClient(id: number, context: { epoch: number; client: ApiClientOptions }) { + // A login older than 5 minutes signs in again first, through `login` once chosen; a token of + // another account is refused. + async function ownClient(id: number, context: { epoch: number; client: ApiClientOptions }, login?: LoginOption) { const token = context.client.token ?? '' if (loginFresh(token)) return context.client - const tokens = await popupSignIn() + const tokens = await popupSignIn(login) guard(id, context.epoch) const baseUrl = context.client.baseUrl ?? '' const renewed = await issueToken(tokens.id_token ?? tokens.access_token, baseUrl) @@ -231,8 +240,8 @@ export function useAccountMerge() { } } - /** Merges after the confirmation; call it in a click handler, it may sign in again. */ - async function merge() { + /** Merges after the confirmation; call it in a click handler, it may sign in again with `login`. */ + async function merge(login?: LoginOption) { if (step.value !== 'confirm') return if (!loginFresh(otherToken)) { reset() @@ -244,7 +253,7 @@ export function useAccountMerge() { failure.value = null step.value = 'merging' try { - const client = await ownClient(id, context) + const client = await ownClient(id, context, login) result.value = await mergeAccount(otherToken, client) guard(id, context.epoch) step.value = 'merged' @@ -256,8 +265,8 @@ export function useAccountMerge() { } } - /** Attaches a sign-in that has no account yet; call it in a click handler. */ - async function attach() { + /** Attaches a sign-in that has no account yet; call it in a click handler, like `merge`. */ + async function attach(login?: LoginOption) { if (step.value !== 'unregistered') return if (!loginFresh(signInToken)) { reset() @@ -269,7 +278,7 @@ export function useAccountMerge() { failure.value = null step.value = 'loading' try { - const client = await ownClient(id, context) + const client = await ownClient(id, context, login) await attachSignIn(signInToken, client) guard(id, context.epoch) reset('attached') @@ -293,5 +302,5 @@ export function useAccountMerge() { result.value = null } - return { step, failure, other, result, start, copyVault, merge, attach, cancel } + return { step, failure, other, result, choose, start, copyVault, merge, attach, cancel } } diff --git a/src/composables/useAuth.ts b/src/composables/useAuth.ts index b30bd1d2..54a968e7 100644 --- a/src/composables/useAuth.ts +++ b/src/composables/useAuth.ts @@ -4,7 +4,7 @@ import { restoring } from '@/composables/aruna/state' import { tokenClaims } from '@/composables/aruna/renewal' import { ApiError, apiRequest, issueToken, signInHasNoAccount } from '@/lib/api' import type { RealmInfoResponse } from '@/lib/api' -import { featureEnabled, portalConfig, type LoginOption } from '@/lib/config' +import { featureEnabled, portalConfig, type LoginOption, type UpstreamLogin } from '@/lib/config' import { desktopBridge } from '@/lib/desktop' import { DESKTOP_CALLBACK_URI, DESKTOP_STATE_PREFIX } from '@/lib/desktopHandoff' import { @@ -25,6 +25,7 @@ const REDIRECT_KEY = 'aruna.oidc.redirect' const ONBOARDING_KEY = 'aruna.oidc.onboardingSecret' const ID_TOKEN_KEY = 'aruna.oidc.idToken' const LINK_KEY = 'aruna.oidc.link' +const UPSTREAM_KEY = 'aruna.oidc.upstream' export type SignInStage = 'idle' | 'redirecting' | 'exchanging' | 'registering' | 'match' | 'done' | 'error' @@ -37,6 +38,8 @@ export interface SignInOptions { freshLogin?: boolean /** Extra authorization request parameters of the chosen login option. */ params?: Record + /** The upstream provider of the chosen login option, signed in through its bridge. */ + upstream?: UpstreamLogin } /** The outcome of linking another login, shown once back in Settings. */ @@ -132,13 +135,14 @@ async function discover(url: string): Promise { return native ? native.oidcDiscovery(url) : fetchDiscovery(url) } -async function resolveProvider() { +async function resolveProvider(upstream?: UpstreamLogin | null) { const { realmInfo, apiBaseUrl } = useAruna() let info = realmInfo.value if (!info) { info = await apiRequest('/system/realm', {}, { baseUrl: apiBaseUrl.value }) } - const provider = info.oidc_providers[0] + const provider = upstream ? info.oidc_providers.find((entry) => entry.id === upstream.provider) : info.oidc_providers[0] + if (!provider && upstream) throw new Error(`The realm has no OIDC provider "${upstream.provider}", sign-in is not available.`) if (!provider) { throw new Error('The realm has no OIDC provider configured, sign-in is not available.') } @@ -147,10 +151,34 @@ async function resolveProvider() { return { clientId: provider.audience, discoveryUrl: provider.discovery_url, issuer: provider.issuer } } -/** The realm's OIDC client, the provider's endpoints and the shell's token sender. */ -export async function oidcClient() { - const { clientId, discoveryUrl } = await resolveProvider() - return { clientId, discovery: await discover(discoveryUrl), send: (await nativeOidc())?.oidcToken } +/** The client, endpoints and shell token sender of a login, or of the realm's first provider. */ +export async function oidcClient(upstream?: UpstreamLogin | null) { + return { ...(await endpoints(upstream ?? null)), send: (await nativeOidc())?.oidcToken } +} + +// An upstream login uses its bridge's endpoints, any other the realm provider's discovery. +// A desktop shell posts only to a token endpoint a discovery named, so it reads the bridge's. +async function endpoints(upstream: UpstreamLogin | null) { + const { clientId, discoveryUrl } = await resolveProvider(upstream) + if (upstream) { + const native = await nativeOidc() + const token = native + ? (await native.oidcDiscovery(`${upstream.bridge}/.well-known/openid-configuration`)).token_endpoint + : `${upstream.bridge}/token` + return { clientId, authorization: `${upstream.bridge}/authorize`, token } + } + const discovery = await discover(discoveryUrl) + return { clientId, authorization: discovery.authorization_endpoint, token: discovery.token_endpoint } +} + +// The upstream login the pending sign-in started with; null for any other. +function pendingUpstream(): UpstreamLogin | null { + try { + const stored = JSON.parse(window.sessionStorage.getItem(UPSTREAM_KEY) ?? 'null') as Partial | null + return typeof stored?.provider === 'string' && typeof stored.bridge === 'string' ? { provider: stored.provider, bridge: stored.bridge } : null + } catch { + return null + } } /** Redirects the browser to the realm's Keycloak login page (code + PKCE). */ @@ -164,8 +192,8 @@ async function authorize(options: SignInOptions & { link?: string }) { stage.value = 'redirecting' stageError.value = null try { - const { clientId, discoveryUrl } = await resolveProvider() - const discovery = await discover(discoveryUrl) + const upstream = options.upstream ?? null + const { clientId, authorization } = await endpoints(upstream) const verifier = randomUrlSafeString(48) const state = signInState() if (options.link) window.sessionStorage.setItem(LINK_KEY, options.link) @@ -174,6 +202,8 @@ async function authorize(options: SignInOptions & { link?: string }) { window.sessionStorage.removeItem(ID_TOKEN_KEY) } window.sessionStorage.setItem(VERIFIER_KEY, verifier) + if (upstream) window.sessionStorage.setItem(UPSTREAM_KEY, JSON.stringify(upstream)) + else window.sessionStorage.removeItem(UPSTREAM_KEY) window.sessionStorage.setItem(STATE_KEY, state) window.sessionStorage.setItem(REDIRECT_KEY, options.redirectTo ?? '/app') if (options.onboardingSecret?.trim()) { @@ -183,7 +213,7 @@ async function authorize(options: SignInOptions & { link?: string }) { } beginAuthRedirect( buildAuthorizationUrl({ - authorizationEndpoint: discovery.authorization_endpoint, + authorizationEndpoint: authorization, clientId, redirectUri: callbackUri(), state, @@ -271,10 +301,9 @@ async function revokeHelper(token: string, baseUrl: string) { } async function redeemCode(code: string, verifier: string) { - const { clientId, discoveryUrl } = await resolveProvider() - const discovery = await discover(discoveryUrl) + const { clientId, token } = await endpoints(pendingUpstream()) return exchangeAuthorizationCode({ - tokenEndpoint: discovery.token_endpoint, + tokenEndpoint: token, clientId, redirectUri: callbackUri(), code, @@ -340,6 +369,8 @@ async function completeSignIn(params: URLSearchParams): Promise { // Aruna validates the audience against the client id, which Keycloak only // sets on the ID token; the access token is for the account API. const oidcToken = tokens.id_token ?? tokens.access_token + // An upstream login has no Keycloak session to end at sign-out. + const endSession = pendingUpstream() ? undefined : tokens.id_token stage.value = 'registering' const client = { baseUrl: aruna.apiBaseUrl.value, token: oidcToken } @@ -355,12 +386,12 @@ async function completeSignIn(params: URLSearchParams): Promise { ) } catch (err) { if (!(err instanceof ApiError && err.code === 'account_match')) throw err - accountMatch.value = { oidcToken, idToken: tokens.id_token, redirectTo: window.sessionStorage.getItem(REDIRECT_KEY) || '/app' } + accountMatch.value = { oidcToken, idToken: endSession, redirectTo: window.sessionStorage.getItem(REDIRECT_KEY) || '/app' } stage.value = 'match' return null } const issued = await apiRequest('/access/token', {}, client) - await adoptSession(issued.token, tokens.id_token) + await adoptSession(issued.token, endSession) stage.value = 'done' const redirectTo = window.sessionStorage.getItem(REDIRECT_KEY) || '/app' @@ -376,6 +407,7 @@ async function completeSignIn(params: URLSearchParams): Promise { window.sessionStorage.removeItem(REDIRECT_KEY) window.sessionStorage.removeItem(ONBOARDING_KEY) window.sessionStorage.removeItem(LINK_KEY) + window.sessionStorage.removeItem(UPSTREAM_KEY) } } } diff --git a/src/composables/useAuth.upstream.test.ts b/src/composables/useAuth.upstream.test.ts new file mode 100644 index 00000000..9565d111 --- /dev/null +++ b/src/composables/useAuth.upstream.test.ts @@ -0,0 +1,180 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { accountMatch, useAuth } from './useAuth' +import { loadPortalConfig } from '@/lib/config' +import { pkceChallengeS256 } from '@/lib/oidc' +import { shellContext } from '@/lib/desktop' + +const PAGE_ORIGIN = 'https://realm.aruna-engine.org' +const BRIDGE = 'https://bridge.test/v3-bridge/lifescience' +const UPSTREAM = { provider: 'lifescience', bridge: BRIDGE } +const KEYCLOAK = 'https://keycloak.test/realms/aruna' + +let assign: ReturnType +let storage: Map +let fetchMock: ReturnType + +// An unsigned ID token; the portal reads only its claims. +const idToken = (sub: string) => `h.${btoa(JSON.stringify({ sub, iat: 1, exp: 2 }))}.s` + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }) +} + +// The realm lists Keycloak first; the node answers the registration with an account match, +// so the flow ends right after the node got the ID token. +async function setup(stored: Record = {}) { + vi.stubGlobal('fetch', vi.fn(async () => json({}))) + await loadPortalConfig() + storage = new Map(Object.entries(stored)) + assign = vi.fn() + vi.stubGlobal('window', { + location: { origin: PAGE_ORIGIN, assign }, + sessionStorage: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), + }, + }) + const discoveryUrl = `${KEYCLOAK}/${Math.random()}/.well-known/openid-configuration` + fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/system/realm')) { + return json({ + oidc_providers: [ + { id: 'keycloak', audience: 'portal', issuer: KEYCLOAK, discovery_url: discoveryUrl }, + { id: 'lifescience', audience: 'ls-client', issuer: 'https://ls.test/oidc/', discovery_url: 'https://ls.test/discovery' }, + ], + }) + } + if (url === discoveryUrl) return json({ issuer: KEYCLOAK, authorization_endpoint: `${KEYCLOAK}/auth`, token_endpoint: `${KEYCLOAK}/token` }) + if (url === `${BRIDGE}/token`) return json({ id_token: idToken('ls-user'), token_type: 'Bearer', expires_in: 300 }) + if (url === `${KEYCLOAK}/token`) return json({ id_token: idToken('kc-user'), access_token: 'a1', token_type: 'Bearer' }) + if (url.endsWith('/access/users/register')) return json({ error: 'matches', code: 'account_match' }, 409) + return json({ error: 'unexpected' }, 500) + }) + vi.stubGlobal('fetch', fetchMock) +} + +function redirected(): URL { + expect(assign).toHaveBeenCalledTimes(1) + return new URL(assign.mock.calls[0][0] as string) +} + +function callsTo(url: string) { + return fetchMock.mock.calls.filter(([input]) => String(input) === url) +} + +function callsEnding(suffix: string) { + return fetchMock.mock.calls.filter(([input]) => String(input).endsWith(suffix)) +} + +afterEach(() => { + accountMatch.value = null + shellContext.value = null + vi.unstubAllGlobals() +}) + +describe('sign-in with an upstream login', () => { + it('sends the browser to the bridge with the provider audience and PKCE', async () => { + await setup() + await useAuth().signIn({ upstream: UPSTREAM }) + const url = redirected() + expect(`${url.origin}${url.pathname}`).toBe(`${BRIDGE}/authorize`) + expect(url.searchParams.get('client_id')).toBe('ls-client') + expect(url.searchParams.get('redirect_uri')).toBe(`${PAGE_ORIGIN}/auth/callback`) + expect(url.searchParams.get('response_type')).toBe('code') + expect(url.searchParams.get('scope')).toBe('openid profile email') + expect(url.searchParams.get('state')).toBe(storage.get('aruna.oidc.state')) + expect(url.searchParams.get('code_challenge_method')).toBe('S256') + expect(url.searchParams.get('code_challenge')).toBe(await pkceChallengeS256(storage.get('aruna.oidc.verifier')!)) + expect(JSON.parse(storage.get('aruna.oidc.upstream')!)).toEqual(UPSTREAM) + // The bridge needs no discovery, so the realm's Keycloak is not asked. + expect(fetchMock.mock.calls.some(([input]) => String(input).includes(KEYCLOAK))).toBe(false) + }) + + it('fails without a redirect when the realm lacks the provider', async () => { + await setup() + const auth = useAuth() + await auth.signIn({ upstream: { provider: 'missing', bridge: BRIDGE } }) + expect(assign).not.toHaveBeenCalled() + expect(auth.stage.value).toBe('error') + expect(auth.stageError.value).toContain('"missing"') + }) + + it('redeems the code at the bridge and hands the ID token to the node', async () => { + await setup({ + 'aruna.oidc.state': 's1', + 'aruna.oidc.verifier': 'v1', + 'aruna.oidc.upstream': JSON.stringify(UPSTREAM), + }) + const target = await useAuth().completeSignIn(new URLSearchParams({ state: 's1', code: 'c1' })) + expect(target).toBeNull() + const [token] = callsTo(`${BRIDGE}/token`) + expect(token[1]?.method).toBe('POST') + expect(Object.fromEntries(new URLSearchParams(String(token[1]?.body)))).toEqual({ + grant_type: 'authorization_code', + client_id: 'ls-client', + redirect_uri: `${PAGE_ORIGIN}/auth/callback`, + code: 'c1', + code_verifier: 'v1', + }) + expect(callsTo(`${KEYCLOAK}/token`)).toHaveLength(0) + const [register] = callsEnding('/access/users/register') + expect(new Headers(register[1]?.headers).get('Authorization')).toBe(`Bearer ${idToken('ls-user')}`) + // No Keycloak session to end later; the sign-in record is gone. + expect(accountMatch.value?.oidcToken).toBe(idToken('ls-user')) + expect(accountMatch.value?.idToken).toBeUndefined() + expect(storage.has('aruna.oidc.upstream')).toBe(false) + }) +}) + +describe('sign-in with an upstream login in Aruna Desktop', () => { + it('reads the bridge discovery natively and redeems the code through the shell', async () => { + await setup({ + 'aruna.oidc.state': 's1', + 'aruna.oidc.verifier': 'v1', + 'aruna.oidc.upstream': JSON.stringify(UPSTREAM), + }) + const invoke = vi.fn(async (command: string) => { + if (command === 'oidc_discovery') return { authorization_endpoint: `${BRIDGE}/authorize`, token_endpoint: `${BRIDGE}/token` } + if (command === 'oidc_token') return { id_token: idToken('ls-user'), token_type: 'Bearer', expires_in: 300 } + throw new Error(`unexpected ${command}`) + }) + shellContext.value = { apiBaseUrl: '/api', bridge: { invoke, version: 8 } } + await useAuth().completeSignIn(new URLSearchParams({ state: 's1', code: 'c1' })) + expect(invoke).toHaveBeenCalledWith('oidc_discovery', { url: `${BRIDGE}/.well-known/openid-configuration` }) + expect(invoke).toHaveBeenCalledWith('oidc_token', { + endpoint: `${BRIDGE}/token`, + form: { + grant_type: 'authorization_code', + client_id: 'ls-client', + redirect_uri: `${PAGE_ORIGIN}/auth/callback`, + code: 'c1', + code_verifier: 'v1', + }, + }) + // The shell posts the form; the webview itself never calls the bridge. + expect(callsTo(`${BRIDGE}/token`)).toHaveLength(0) + expect(accountMatch.value?.oidcToken).toBe(idToken('ls-user')) + }) +}) + +describe('sign-in with a legacy login', () => { + it('keeps the Keycloak endpoints and drops a stale upstream record', async () => { + await setup({ 'aruna.oidc.upstream': JSON.stringify(UPSTREAM) }) + await useAuth().signIn({ params: { kc_idp_hint: 'lifescience' } }) + const url = redirected() + expect(`${url.origin}${url.pathname}`).toBe(`${KEYCLOAK}/auth`) + expect(url.searchParams.get('client_id')).toBe('portal') + expect(url.searchParams.get('kc_idp_hint')).toBe('lifescience') + expect(storage.has('aruna.oidc.upstream')).toBe(false) + }) + + it('redeems the code at Keycloak and keeps its ID token for sign-out', async () => { + await setup({ 'aruna.oidc.state': 's1', 'aruna.oidc.verifier': 'v1' }) + await useAuth().completeSignIn(new URLSearchParams({ state: 's1', code: 'c1' })) + expect(callsTo(`${KEYCLOAK}/token`)).toHaveLength(1) + expect(callsTo(`${BRIDGE}/token`)).toHaveLength(0) + expect(accountMatch.value?.idToken).toBe(idToken('kc-user')) + }) +}) diff --git a/src/lib/config.test.ts b/src/lib/config.test.ts index 4e134724..cf118961 100644 --- a/src/lib/config.test.ts +++ b/src/lib/config.test.ts @@ -21,6 +21,25 @@ describe('portal login config', () => { expect(login.accountUrl).toBe('https://idp.example.org/account') }) + it('reads the provider and bridge of an upstream login only when both are set', () => { + const { login } = applyPortalConfig({ + login: { + options: [ + { name: 'LS', provider: ' lifescience ', bridge: 'https://bridge.example.org/v3-bridge/lifescience/' }, + { name: 'No bridge', provider: 'gfbio' }, + { name: 'No provider', bridge: 'https://bridge.example.org/v3-bridge/gfbio' }, + { name: 'Bad', provider: 1, bridge: 'https://bridge.example.org' }, + ], + }, + }) + expect(login.options.map((option) => option.upstream)).toEqual([ + { provider: 'lifescience', bridge: 'https://bridge.example.org/v3-bridge/lifescience' }, + undefined, + undefined, + undefined, + ]) + }) + it('has no options and no account page without config', () => { expect(applyPortalConfig({}).login).toEqual({ options: [], accountUrl: '' }) }) diff --git a/src/lib/config.ts b/src/lib/config.ts index e7d8bc77..2d36b316 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -22,6 +22,14 @@ export interface LoginOption { params: Record // Parameters that link this login to the signed-in account; empty means not linkable. linkParams: Record + // Signs in at a realm OIDC provider through its login bridge instead of the first provider. + upstream?: UpstreamLogin +} + +/** The `provider` id of a realm OIDC provider and the `bridge` base URL that serves its login. */ +export interface UpstreamLogin { + provider: string + bridge: string } export interface LoginConfig { @@ -136,6 +144,13 @@ function stringMap(raw: unknown): Record { return Object.fromEntries(Object.entries(raw).filter((entry): entry is [string, string] => typeof entry[1] === 'string')) } +// Both fields or none: an option with only one keeps the plain sign-in. +function upstreamLogin(option: Record): UpstreamLogin | undefined { + const provider = typeof option.provider === 'string' ? option.provider.trim() : '' + const bridge = typeof option.bridge === 'string' ? option.bridge.trim().replace(/\/+$/, '') : '' + return provider && bridge ? { provider, bridge } : undefined +} + function loginConfig(raw: unknown): LoginConfig { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { options: [], accountUrl: '' } const login = raw as Record @@ -151,6 +166,7 @@ function loginConfig(raw: unknown): LoginConfig { logoLight: typeof option.logoLight === 'string' && option.logoLight ? option.logoLight : undefined, params: stringMap(option.params), linkParams: stringMap(option.linkParams), + upstream: upstreamLogin(option), }, ] }) diff --git a/src/views/AuthCallbackView.test.ts b/src/views/AuthCallbackView.test.ts index 7066ea44..3e71b2ac 100644 --- a/src/views/AuthCallbackView.test.ts +++ b/src/views/AuthCallbackView.test.ts @@ -4,17 +4,20 @@ import * as RouterRuntime from 'vue-router' import { createMemoryHistory, createRouter, type Router } from 'vue-router' import { beforeEach, describe, expect, it, vi } from 'vitest' import { button, click, compileClientComponent, content, moduleDefault, mountApp } from '@/test/clientRender' +import { DEFAULT_PORTAL_CONFIG, type LoginOption, type PortalRuntimeConfig } from '@/lib/config' const stage = ref('idle') const stageError = ref(null) const completeSignIn = vi.fn(async (_params: URLSearchParams): Promise => '/app') const signIn = vi.fn() const requestSignIn = vi.fn() -const joinExistingAccount = vi.fn(async (): Promise => '/app') +const joinExistingAccount = vi.fn(async (_login?: LoginOption): Promise => '/app') const createNewAccount = vi.fn(async (): Promise => '/app') const matchBusy = ref(false) const matchFailure = ref(null) const matchStale = ref(false) +const NFDI: LoginOption = { name: 'NFDI AAI', description: '', logo: '', params: {}, linkParams: {}, upstream: { provider: 'iam4nfdi', bridge: 'https://bridge.test/iam4nfdi' } } +let config: PortalRuntimeConfig = DEFAULT_PORTAL_CONFIG const EmptyStub = defineComponent(() => () => null) const ButtonStub = defineComponent({ @@ -23,8 +26,15 @@ const ButtonStub = defineComponent({ }) const icons = new Proxy({}, { get: () => defineComponent(() => () => h('i')) }) +const LoginOptions = compileClientComponent(new URL('../components/auth/LoginOptions.vue', import.meta.url), { + vue: VueRuntime, + '@/components/auth/ProviderLogo.vue': moduleDefault(EmptyStub), + '@/lib/config': { portalConfig: () => config }, +}) const AuthCallbackView = compileClientComponent(new URL('./AuthCallbackView.vue', import.meta.url), { vue: VueRuntime, + '@/components/auth/LoginOptions.vue': moduleDefault(LoginOptions), + '@/lib/config': { portalConfig: () => config }, 'vue-router': RouterRuntime, '@lucide/vue': icons, '@/components/layout/AppLogo.vue': moduleDefault(EmptyStub), @@ -56,6 +66,7 @@ function codes(): string[] { beforeEach(() => { vi.clearAllMocks() + config = DEFAULT_PORTAL_CONFIG stage.value = 'idle' stageError.value = null matchFailure.value = null @@ -121,6 +132,24 @@ describe('completing a sign in', () => { mounted.app.unmount() }) + it('asks for the login of the existing account when logins are configured', async () => { + config = { ...DEFAULT_PORTAL_CONFIG, login: { options: [NFDI], accountUrl: '' } } + completeSignIn.mockImplementationOnce(async () => { + stage.value = 'match' + return null + }) + const router = await routed('/auth/callback?code=first&state=s1') + const mounted = await mountApp(AuthCallbackView, { router }) + await vi.waitFor(() => expect(content(mounted.root)).toContain('An account with this email or name already exists')) + await click(button(mounted.root, 'This is me')) + expect(joinExistingAccount).not.toHaveBeenCalled() + expect(content(mounted.root)).toContain('Choose how you sign in with it.') + await click(button(mounted.root, 'NFDI AAI')) + expect(joinExistingAccount).toHaveBeenCalledWith(NFDI) + await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('dashboard')) + mounted.app.unmount() + }) + it('asks for a new sign-in when the matched one got too old', async () => { completeSignIn.mockImplementationOnce(async () => { stage.value = 'match' diff --git a/src/views/AuthCallbackView.vue b/src/views/AuthCallbackView.vue index 2419a8bb..2023f787 100644 --- a/src/views/AuthCallbackView.vue +++ b/src/views/AuthCallbackView.vue @@ -1,12 +1,14 @@