Skip to content
49 changes: 48 additions & 1 deletion src/components/auth/AccountMerge.mount.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MergeStep>('idle')
const failure = ref<string | null>(null)
const other = shallowRef<OtherAccount | null>(null)
const result = shallowRef<MergeAccountResponse | null>(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<Partial<UserInfoResponse> | null>(null)

Expand All @@ -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)),
Expand Down Expand Up @@ -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()
})

Expand All @@ -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'],
Expand Down
28 changes: 23 additions & 5 deletions src/components/auth/AccountMerge.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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,
Expand All @@ -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')
Expand All @@ -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) {
Expand Down Expand Up @@ -113,7 +124,7 @@ function close(value: boolean) {
<div class="text-sm font-medium text-foreground">Add another account</div>
<div class="text-xs text-muted-foreground">Sign in with it once to merge it into this one.</div>
</div>
<Button size="sm" variant="outline" :disabled="open" @click="start">Add account</Button>
<Button size="sm" variant="outline" :disabled="open" @click="add">Add account</Button>
</div>
<div v-if="merged.length" class="border-t border-border px-5 py-3">
<div class="type-label">Merged accounts</div>
Expand All @@ -134,9 +145,11 @@ function close(value: boolean) {
<DialogDescription v-if="step === 'confirm' || step === 'merging'">
{{ name }} is closed afterwards. Signing in with it opens this account.
</DialogDescription>
<DialogDescription v-else-if="step === 'choose'">Choose how you sign in with the other account.</DialogDescription>
</DialogHeader>

<Spinner v-if="step === 'signing'" show-label label="Sign in with the other account in the new window." />
<LoginOptions v-if="step === 'choose'" @choose="start" />
<Spinner v-else-if="step === 'signing'" show-label label="Sign in with the other account in the new window." />
<Spinner v-else-if="step === 'loading'" show-label label="Reading the other account…" />
<div v-else-if="stepTile && step !== 'attached'" class="flex items-start gap-3">
<IconTile :icon="stepTile.icon" :tone="stepTile.tone" />
Expand Down Expand Up @@ -214,6 +227,11 @@ function close(value: boolean) {
<p class="text-sm text-muted-foreground">You can now sign in with it.</p>
</div>

<template v-if="ownLogin">
<Notice v-if="step === 'unregistered'">You confirm with your own login first.</Notice>
<LoginOptions @choose="(login) => (step === 'unregistered' ? attach(login) : merge(login))" />
</template>

<Notice v-if="failure" tone="error">{{ failure }}</Notice>

<DialogFooter>
Expand All @@ -222,9 +240,9 @@ function close(value: boolean) {
</template>
<template v-else>
<Button variant="outline" @click="cancel">{{ step === 'vault-blocked' || step === 'idle' ? 'Close' : 'Cancel' }}</Button>
<Button v-if="step === 'unregistered'" @click="attach">Attach sign-in</Button>
<Button v-if="step === 'unregistered' && !ownLogin" @click="attach()">Attach sign-in</Button>
<Button v-else-if="step === 'copy-vault'" @click="copyVault">Copy vault</Button>
<Button v-else-if="step === 'confirm' || step === 'merging'" :disabled="busy" @click="merge">
<Button v-else-if="(step === 'confirm' || step === 'merging') && !ownLogin" :disabled="busy" @click="merge()">
<Spinner v-if="step === 'merging'" class="text-current" aria-hidden="true" /> Merge
</Button>
</template>
Expand Down
33 changes: 33 additions & 0 deletions src/components/auth/LoginOptions.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<script setup lang="ts">
// The login rows of the sign-in chooser: the configured logins, or the realm's plain sign-in.
// The default slot adds rows of its own in the same style.
import ProviderLogo from '@/components/auth/ProviderLogo.vue'
import { portalConfig, type LoginOption } from '@/lib/config'

defineProps<{ disabled?: boolean }>()
const emit = defineEmits<{ choose: [option: LoginOption] }>()

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'
</script>

<template>
<ul class="flex flex-col gap-2.5">
<li v-for="choice in choices" :key="choice.name">
<button type="button" :title="choice.description || undefined" :class="rowClass" :disabled="disabled" @click="emit('choose', choice)">
<ProviderLogo :logo="choice.logo" :logo-light="choice.logoLight" />
<span class="w-44 text-left">{{ choice.name }}</span>
</button>
</li>
<slot :row-class="rowClass" />
</ul>
</template>
9 changes: 9 additions & 0 deletions src/components/auth/ProviderLinks.mount.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion src/components/auth/ProviderLinks.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 15 additions & 2 deletions src/components/auth/SignInDialog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) },
Expand All @@ -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<string, string> = {}): LoginOption {
Expand Down Expand Up @@ -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()
Expand Down
29 changes: 6 additions & 23 deletions src/components/auth/SignInDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,19 @@ 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'

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) => {
Expand All @@ -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.
Expand Down Expand Up @@ -83,13 +72,7 @@ async function loginElsewhere(home: VerifiedRealm) {
<DialogTitle class="text-center">Continue login with</DialogTitle>
<DialogDescription class="sr-only">Choose how you want to sign in.</DialogDescription>
</DialogHeader>
<ul class="flex flex-col gap-2.5">
<li v-for="choice in choices" :key="choice.name">
<button type="button" :title="choice.description || undefined" :class="rowClass" @click="choose(choice)">
<ProviderLogo :logo="choice.logo" :logo-light="choice.logoLight" />
<span class="w-44 text-left">{{ choice.name }}</span>
</button>
</li>
<LoginOptions v-slot="{ rowClass }" @choose="choose">
<li v-if="accepted.mode !== 'none'">
<button
type="button"
Expand All @@ -105,7 +88,7 @@ async function loginElsewhere(home: VerifiedRealm) {
<span class="w-44 text-left">Another Aruna realm</span>
</button>
</li>
</ul>
</LoginOptions>
<div v-if="pickerOpen && !federating && accepted.mode !== 'none'" class="rounded-lg border border-border bg-muted/30 p-1">
<RealmPicker
action-label="Choose"
Expand Down
16 changes: 15 additions & 1 deletion src/composables/accountMatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const refresh = vi.fn(async () => {
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,
Expand Down Expand Up @@ -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()

Expand Down
Loading
Loading