File size: 6,374 Bytes
83a59ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createPinia, setActivePinia } from 'pinia'
import { ref } from 'vue'
import type { User as FirebaseUser } from 'firebase/auth'
import { useApi, setAuthHeader, setApiKey } from '../composables/useApi'
import { useAuthStore } from './auth'

interface UserResponse {
  data: { id: string; api_key: string }
}

function deferred<T>() {
  let resolve!: (value: T) => void
  const promise = new Promise<T>((done) => {
    resolve = done
  })
  return { promise, resolve }
}

function firebaseUser(id: string, token = Promise.resolve(`token-${id}`)) {
  return {
    uid: id,
    email: null,
    displayName: null,
    getIdToken: () => token,
  } as FirebaseUser
}

function setupStore() {
  const calls: Headers[] = []
  let response = Promise.resolve<UserResponse>({
    data: { id: 'account-a', api_key: 'key-a' },
  })
  Object.assign(globalThis, {
    ref,
    useApi,
    useRuntimeConfig: () => ({
      public: { apiBaseUrl: 'https://api.example.test' },
    }),
    $fetch: {
      create:
        (config: {
          headers: HeadersInit
          onRequest: (context: { options: { headers: Headers } }) => void
        }) =>
        async () => {
          const options = { headers: new Headers(config.headers) }
          config.onRequest({ options })
          calls.push(options.headers)
          return response
        },
    },
    usePhonesStore: () => ({
      activePhone: { id: 'phone-a' },
      loadPhones: async () => {},
    }),
  })
  setAuthHeader(null)
  setApiKey(null)
  setActivePinia(createPinia())
  const store = useAuthStore()
  return {
    store,
    calls,
    respondWith: (next: Promise<UserResponse>) => {
      response = next
    },
  }
}

test('loading a user sends its API key alongside bearer auth on shared requests', async () => {
  const { store, calls, respondWith } = setupStore()
  const client = useApi().apiFetch
  await store.onAuthStateChanged(firebaseUser('account-a'))
  await store.loadUser()
  await client('/v1/messages')

  assert.equal(calls.at(-1)?.get('Authorization'), 'Bearer token-account-a')
  assert.equal(calls.at(-1)?.get('x-api-key'), 'key-a')

  respondWith(
    Promise.resolve({ data: { id: 'account-a', api_key: 'new-key-a' } }),
  )
  await store.loadUser()
  await client('/v1/messages')
  assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key-a')
})

for (const logout of ['reset', 'auth callback', 'token callback'] as const) {
  test(`a pending user load cannot restore credentials after ${logout}`, async () => {
    const { store, calls, respondWith } = setupStore()
    await store.onAuthStateChanged(firebaseUser('account-a'))
    await store.loadUser()
    const pending = deferred<UserResponse>()
    respondWith(pending.promise)
    const load = store.loadUser()

    if (logout === 'reset') store.resetState()
    if (logout === 'auth callback') await store.onAuthStateChanged(null)
    if (logout === 'token callback') await store.onIdTokenChanged(null)
    pending.resolve({ data: { id: 'account-a', api_key: 'old-key-a' } })
    await load
    await useApi().apiFetch('/v1/messages')

    assert.equal(store.user, null)
    assert.equal(store.authUser, null)
    assert.equal(calls.at(-1)?.has('Authorization'), false)
    assert.equal(calls.at(-1)?.has('x-api-key'), false)
  })
}

for (const switchAccount of ['firebase', 'action'] as const) {
  test(`switching accounts through ${switchAccount} clears old keys and discards pending loads`, async () => {
    const { store, calls, respondWith } = setupStore()
    await store.onAuthStateChanged(firebaseUser('account-a'))
    await store.loadUser()
    const pending = deferred<UserResponse>()
    respondWith(pending.promise)
    const oldLoad = store.loadUser()
    respondWith(
      Promise.resolve({ data: { id: 'account-b', api_key: 'key-b' } }),
    )

    if (switchAccount === 'firebase') {
      await store.onAuthStateChanged(firebaseUser('account-b'))
      await store.loadUser()
    } else {
      await store.setAuthUserAction({
        id: 'account-b',
        email: null,
        displayName: null,
      })
    }
    assert.equal(calls.at(-1)?.has('x-api-key'), false)
    pending.resolve({ data: { id: 'account-a', api_key: 'old-key-a' } })
    await oldLoad
    await useApi().apiFetch('/v1/messages')

    assert.equal(store.user?.id, 'account-b')
    assert.equal(calls.at(-1)?.get('x-api-key'), 'key-b')
  })
}

test('logging back into the same account does not revive an earlier session response', async () => {
  const { store, calls, respondWith } = setupStore()
  await store.onAuthStateChanged(firebaseUser('account-a'))
  const pending = deferred<UserResponse>()
  respondWith(pending.promise)
  const oldLoad = store.loadUser()
  store.resetState()
  await store.onAuthStateChanged(firebaseUser('account-a'))
  respondWith(
    Promise.resolve({ data: { id: 'account-a', api_key: 'new-key-a' } }),
  )
  await store.loadUser()
  pending.resolve({ data: { id: 'account-a', api_key: 'old-key-a' } })
  await oldLoad
  await useApi().apiFetch('/v1/messages')

  assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key-a')
})

for (const operation of ['update', 'rotate'] as const) {
  test(`a pending ${operation} cannot restore credentials after logout`, async () => {
    const { store, calls, respondWith } = setupStore()
    await store.onAuthStateChanged(firebaseUser('account-a'))
    const pending = deferred<UserResponse>()
    respondWith(pending.promise)
    const request =
      operation === 'update'
        ? store.updateUser({ timezone: 'UTC' })
        : store.rotateApiKey('account-a')
    store.resetState()
    pending.resolve({ data: { id: 'account-a', api_key: 'old-key-a' } })
    await request
    await useApi().apiFetch('/v1/messages')

    assert.equal(store.user, null)
    assert.equal(calls.at(-1)?.has('x-api-key'), false)
  })
}

test('a pending Firebase token cannot restore credentials after logout', async () => {
  const { store, calls } = setupStore()
  const token = deferred<string>()
  const login = store.onAuthStateChanged(
    firebaseUser('account-a', token.promise),
  )
  store.resetState()
  token.resolve('old-token-a')
  await login
  await useApi().apiFetch('/v1/messages')

  assert.equal(store.authUser, null)
  assert.equal(calls.at(-1)?.has('Authorization'), false)
})