pinokiod 8.3.1 → 8.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ const test = require('node:test')
4
4
 
5
5
  const GitBin = require('../kernel/bin/git')
6
6
 
7
- function createGitBin(platform, packages) {
7
+ function createGitBin(platform, packages, executed = []) {
8
8
  const git = new GitBin()
9
9
  git.kernel = {
10
10
  platform,
@@ -15,45 +15,60 @@ function createGitBin(platform, packages) {
15
15
  conda: new Set(packages),
16
16
  conda_versions: { git: '2.51.0' },
17
17
  },
18
+ exec: async (req) => {
19
+ executed.push(req.message)
20
+ },
18
21
  },
19
22
  }
20
23
  return git
21
24
  }
22
25
 
23
- test('Git bin installs Git Credential Manager with the Git bundle', () => {
26
+ test('Git bin installs Git, Git LFS and GitHub CLI without Git Credential Manager', () => {
24
27
  assert.equal(
25
28
  createGitBin('darwin', []).cmd(),
26
- '"git>=2.51.0" git-lfs git-credential-manager=2.7.3 gh=2.82.1'
29
+ '"git>=2.51.0" git-lfs gh=2.82.1'
27
30
  )
28
31
  assert.equal(
29
32
  createGitBin('linux', []).cmd(),
30
- '"git>=2.51.0" git-lfs git-credential-manager=2.7.3 gh=2.82.1'
33
+ '"git>=2.51.0" git-lfs gh=2.82.1'
31
34
  )
32
35
  assert.equal(
33
36
  createGitBin('win32', []).cmd(),
34
- '"git>=2.51.0" git-lfs git-credential-manager=2.7.3 gh=2.82.1 m2-base'
37
+ '"git>=2.51.0" git-lfs gh=2.82.1 m2-base'
35
38
  )
36
39
  })
37
40
 
38
- test('Git bin readiness requires Git Credential Manager and GitHub CLI', async () => {
41
+ test('Git bin readiness requires Git and GitHub CLI', async () => {
39
42
  assert.equal(
40
43
  await createGitBin('darwin', ['git', 'git-lfs']).installed(),
41
44
  false
42
45
  )
43
46
  assert.equal(
44
- await createGitBin('darwin', ['git', 'git-lfs', 'git-credential-manager']).installed(),
45
- false
46
- )
47
- assert.equal(
48
- await createGitBin('darwin', ['git', 'git-lfs', 'git-credential-manager', 'gh']).installed(),
47
+ await createGitBin('darwin', ['git', 'git-lfs', 'gh']).installed(),
49
48
  true
50
49
  )
51
50
  assert.equal(
52
- await createGitBin('win32', ['git', 'git-lfs', 'git-credential-manager', 'gh']).installed(),
51
+ await createGitBin('win32', ['git', 'git-lfs', 'gh']).installed(),
53
52
  false
54
53
  )
55
54
  assert.equal(
56
- await createGitBin('win32', ['git', 'git-lfs', 'git-credential-manager', 'gh', 'm2-base']).installed(),
55
+ await createGitBin('win32', ['git', 'git-lfs', 'gh', 'm2-base']).installed(),
57
56
  true
58
57
  )
59
58
  })
59
+
60
+ test('Git bin treats a leftover Git Credential Manager as not installed so it gets removed', async () => {
61
+ assert.equal(
62
+ await createGitBin('darwin', ['git', 'git-lfs', 'gh', 'git-credential-manager']).installed(),
63
+ false
64
+ )
65
+
66
+ const executed = []
67
+ await createGitBin('darwin', ['git', 'git-lfs', 'gh', 'git-credential-manager'], executed).install({}, () => {})
68
+ assert.equal(executed[0], 'conda remove -y git-credential-manager')
69
+ assert.match(executed[executed.length - 1].join('\n'), /conda install -y -c conda-forge "git>=2\.51\.0" git-lfs gh=2\.82\.1/)
70
+
71
+ const fresh = []
72
+ await createGitBin('darwin', [], fresh).install({}, () => {})
73
+ assert.equal(fresh.some((message) => /git-credential-manager/.test(String(message))), false)
74
+ })
@@ -22,6 +22,7 @@ async function withTempHome(fn) {
22
22
  function createKernel(homedir) {
23
23
  return {
24
24
  homedir,
25
+ platform: process.platform,
25
26
  path: (...parts) => path.resolve(homedir, ...parts),
26
27
  }
27
28
  }
@@ -30,43 +31,60 @@ function githubCredentialSection(config) {
30
31
  return config['credential "https://github'] && config['credential "https://github']['com"']
31
32
  }
32
33
 
33
- test('Git defaults configure Git Credential Manager for new Pinokio gitconfig files', async () => {
34
+ test('Git defaults point new Pinokio gitconfig files at the GitHub CLI credential helper', async () => {
34
35
  await withTempHome(async (homedir) => {
35
- const git = new KernelGit(createKernel(homedir))
36
+ const kernel = createKernel(homedir)
37
+ const git = new KernelGit(kernel)
36
38
 
37
39
  await git.ensureDefaults()
38
40
 
39
- const config = ini.parse(await fs.readFile(path.join(homedir, 'gitconfig'), 'utf8'))
40
- assert.equal(config.credential.helper, 'manager')
41
- assert.equal(config.credential.gitHubAuthModes, 'oauth')
42
- assert.equal(config.credential.namespace, 'pinokio')
43
- assert.equal(githubCredentialSection(config).helper, 'manager')
44
- assert.equal(githubCredentialSection(config).provider, 'github')
41
+ const content = await fs.readFile(path.join(homedir, 'gitconfig'), 'utf8')
42
+ assert.doesNotMatch(content, /manager/)
43
+ const config = ini.parse(content)
44
+ assert.equal(config.credential, undefined)
45
+ assert.equal(githubCredentialSection(config).helper, '!gh auth git-credential')
46
+ assert.equal(githubCredentialSection(config).provider, undefined)
47
+ const { stdout } = await execFileAsync('git', ['config', '--file', path.join(homedir, 'gitconfig'), '--get', 'credential.https://github.com.helper'])
48
+ assert.equal(stdout.trim(), '!gh auth git-credential')
45
49
  })
46
50
  })
47
51
 
48
- test('Git defaults migrate the legacy gh GitHub helper to Git Credential Manager', async () => {
52
+ test('Git defaults migrate Git Credential Manager settings to the GitHub CLI helper', async () => {
49
53
  await withTempHome(async (homedir) => {
50
54
  await fs.writeFile(path.join(homedir, 'gitconfig'), [
55
+ '[credential]',
56
+ ' helper = manager',
57
+ ' gitHubAuthModes = oauth',
58
+ ' namespace = pinokio',
51
59
  '[credential "https://github.com"]',
52
- ' helper = !gh auth git-credential',
60
+ ' helper = manager',
61
+ ' provider = github',
53
62
  '[user]',
54
63
  ' name = custom',
55
64
  ' email = custom@example.test',
56
65
  '',
57
66
  ].join('\n'))
58
- const git = new KernelGit(createKernel(homedir))
67
+ const kernel = createKernel(homedir)
68
+ const git = new KernelGit(kernel)
59
69
 
60
70
  await git.ensureDefaults()
61
71
 
62
- const config = ini.parse(await fs.readFile(path.join(homedir, 'gitconfig'), 'utf8'))
63
- assert.equal(config.credential.helper, 'manager')
64
- assert.equal(config.credential.gitHubAuthModes, 'oauth')
65
- assert.equal(config.credential.namespace, 'pinokio')
66
- assert.equal(githubCredentialSection(config).helper, 'manager')
67
- assert.equal(githubCredentialSection(config).provider, 'github')
72
+ const content = await fs.readFile(path.join(homedir, 'gitconfig'), 'utf8')
73
+ assert.doesNotMatch(content, /manager/)
74
+ assert.doesNotMatch(content, /gitHubAuthModes/)
75
+ const config = ini.parse(content)
76
+ assert.equal(config.credential, undefined)
77
+ assert.equal(githubCredentialSection(config).helper, '!gh auth git-credential')
78
+ assert.equal(githubCredentialSection(config).provider, undefined)
68
79
  assert.equal(config.user.name, 'custom')
69
80
  assert.equal(config.user.email, 'custom@example.test')
81
+
82
+ // running again leaves the file untouched
83
+ const before = await fs.stat(path.join(homedir, 'gitconfig'))
84
+ await new Promise((resolve) => setTimeout(resolve, 20))
85
+ await git.ensureDefaults()
86
+ const after = await fs.stat(path.join(homedir, 'gitconfig'))
87
+ assert.equal(after.mtimeMs, before.mtimeMs)
70
88
  })
71
89
  })
72
90
 
@@ -100,17 +118,18 @@ test('Git defaults reset credential sections to built-in defaults before Git rea
100
118
  ' email = custom@example.test',
101
119
  '',
102
120
  ].join('\n'))
103
- const git = new KernelGit(createKernel(caseHome))
121
+ const kernel = createKernel(caseHome)
122
+ const git = new KernelGit(kernel)
104
123
 
105
124
  await git.ensureDefaults()
106
125
 
107
126
  const content = await fs.readFile(gitconfigPath, 'utf8')
108
- assert.doesNotMatch(content, /git-credential/i)
127
+ assert.doesNotMatch(content, /custom-helper|gh\.exe|Any Folder/)
109
128
  const { stdout } = await execFileAsync('git', ['config', '--file', gitconfigPath, '--list'])
110
- assert.match(stdout, /credential\.helper=manager/)
111
- assert.match(stdout, /credential\.githubauthmodes=oauth/)
112
- assert.match(stdout, /credential\.namespace=pinokio/)
113
- assert.match(stdout, /credential\.https:\/\/github\.com\.helper=manager/)
129
+ assert.match(stdout, /credential\.https:\/\/github\.com\.helper=!gh auth git-credential$/m)
130
+ assert.doesNotMatch(stdout, /^credential\.helper=/m)
131
+ assert.doesNotMatch(stdout, /credential\.githubauthmodes/)
132
+ assert.doesNotMatch(stdout, /credential\.namespace/)
114
133
  assert.doesNotMatch(stdout, /credential\.https:\/\/gist\.github\.com/)
115
134
  assert.doesNotMatch(stdout, /credential\.https:\/\/enterprise\.example/)
116
135
  const config = ini.parse(content)
@@ -120,7 +139,7 @@ test('Git defaults reset credential sections to built-in defaults before Git rea
120
139
  })
121
140
  })
122
141
 
123
- test('Git isomorphic auth callback returns GCM credentials for GitHub URLs', async () => {
142
+ test('Git isomorphic auth callback returns stored credentials for GitHub URLs', async () => {
124
143
  const git = new KernelGit(createKernel('/tmp/pinokio'))
125
144
  let requestedUrl = ''
126
145
  git.getCredentialForUrl = async (url) => {
@@ -140,7 +159,7 @@ test('Git isomorphic auth callback returns GCM credentials for GitHub URLs', asy
140
159
  })
141
160
  })
142
161
 
143
- test('Git isomorphic auth callback stays anonymous when GCM has no credential', async () => {
162
+ test('Git isomorphic auth callback stays anonymous when no credential is stored', async () => {
144
163
  const git = new KernelGit(createKernel('/tmp/pinokio'))
145
164
  git.getCredentialForUrl = async () => null
146
165
 
@@ -0,0 +1,431 @@
1
+ const assert = require('node:assert/strict')
2
+ const { execFile } = require('node:child_process')
3
+ const fs = require('node:fs/promises')
4
+ const os = require('node:os')
5
+ const path = require('node:path')
6
+ const test = require('node:test')
7
+ const YAML = require('yaml')
8
+
9
+ const GithubAuth = require('../kernel/github_auth')
10
+ const KernelGit = require('../kernel/git')
11
+
12
+ async function withTempHome(fn) {
13
+ const homedir = await fs.mkdtemp(path.join(os.tmpdir(), 'pinokio-github-auth-'))
14
+ try {
15
+ await fn(homedir)
16
+ } finally {
17
+ await fs.rm(homedir, { recursive: true, force: true })
18
+ }
19
+ }
20
+
21
+ function createKernel(homedir) {
22
+ return {
23
+ homedir,
24
+ platform: process.platform,
25
+ path: (...parts) => path.resolve(homedir, ...parts),
26
+ }
27
+ }
28
+
29
+ function jsonResponse(body, status = 200) {
30
+ return { status, text: async () => JSON.stringify(body), json: async () => body }
31
+ }
32
+
33
+ // A fake GitHub: hands out a device code, stays pending for `pendingPolls` polls, then approves.
34
+ // `userGate` lets a test hold the /user lookup open until it decides to release it.
35
+ function fakeGithub({ pendingPolls = 1, login = 'octocat', token = 'gho_test_token', finalError = null, userGate = null, deviceGate = null } = {}) {
36
+ const calls = []
37
+ let polls = 0
38
+ const fetch = async (url, init = {}) => {
39
+ calls.push({ url, body: String(init.body || ''), headers: init.headers || {} })
40
+ if (url === 'https://github.com/login/device/code') {
41
+ if (deviceGate) await deviceGate.opened
42
+ return jsonResponse({
43
+ device_code: 'device-code-1',
44
+ user_code: 'ABCD-1234',
45
+ verification_uri: 'https://github.com/login/device',
46
+ expires_in: 900,
47
+ interval: 0,
48
+ })
49
+ }
50
+ if (url === 'https://github.com/login/oauth/access_token') {
51
+ polls += 1
52
+ if (polls <= pendingPolls) {
53
+ return jsonResponse({ error: 'authorization_pending' })
54
+ }
55
+ if (finalError) {
56
+ return jsonResponse({ error: finalError })
57
+ }
58
+ return jsonResponse({ access_token: token, token_type: 'bearer', scope: 'repo,workflow' })
59
+ }
60
+ if (url === 'https://api.github.com/user') {
61
+ if (userGate) await userGate.opened
62
+ return login ? jsonResponse({ login }) : jsonResponse({ message: 'Bad credentials' }, 401)
63
+ }
64
+ throw new Error(`unexpected fetch ${url}`)
65
+ }
66
+ return { fetch, calls }
67
+ }
68
+
69
+ function gate() {
70
+ const g = { reached: null, opened: null }
71
+ g.reachedPromise = new Promise((resolve) => { g.reached = resolve })
72
+ g.opened = new Promise((resolve) => { g.open = resolve })
73
+ return g
74
+ }
75
+
76
+ async function waitFor(predicate, timeout = 5000) {
77
+ const started = Date.now()
78
+ while (Date.now() - started < timeout) {
79
+ if (await predicate()) return
80
+ await new Promise((resolve) => setTimeout(resolve, 20))
81
+ }
82
+ throw new Error('timed out waiting for condition')
83
+ }
84
+
85
+ const hostsPath = (homedir) => path.join(homedir, 'config/gh/hosts.yml')
86
+ const readHosts = async (homedir) => YAML.parse(await fs.readFile(hostsPath(homedir), 'utf8'))
87
+
88
+ test('GitHub device login stores the token in the gh hosts file and keeps other hosts and accounts', async () => {
89
+ await withTempHome(async (homedir) => {
90
+ await fs.mkdir(path.dirname(hostsPath(homedir)), { recursive: true })
91
+ await fs.writeFile(hostsPath(homedir), YAML.stringify({
92
+ 'ghe.example.com': { oauth_token: 'ghe_token', user: 'enterprise-user', git_protocol: 'ssh' },
93
+ 'github.com': { users: { 'other-user': { oauth_token: 'gho_other' } }, oauth_token: 'gho_other', user: 'other-user' },
94
+ }))
95
+ const github = fakeGithub({ pendingPolls: 2 })
96
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
97
+
98
+ // the pre-existing gh login already counts as connected
99
+ assert.deepEqual(await auth.status(), { connected: true, saved: true, login: 'other-user', display: 'github.com: other-user', source: 'pinokio', session: null })
100
+
101
+ const session = await auth.startLogin()
102
+ assert.equal(session.status, 'pending')
103
+ assert.equal(session.user_code, 'ABCD-1234')
104
+ assert.equal(session.verification_uri, 'https://github.com/login/device')
105
+ assert.match(github.calls[0].body, /client_id=Ov23cthkE6o0xkxngT2r/)
106
+ assert.match(github.calls[0].body, /scope=repo\+workflow/)
107
+
108
+ // a second start while pending reuses the same code instead of asking GitHub again
109
+ const again = await auth.startLogin()
110
+ assert.equal(again.user_code, 'ABCD-1234')
111
+ assert.equal(github.calls.filter((call) => call.url.endsWith('/device/code')).length, 1)
112
+
113
+ await waitFor(async () => (await auth.status()).login === 'octocat')
114
+
115
+ const status = await auth.status()
116
+ assert.equal(status.connected, true)
117
+ assert.equal(status.session.status, 'connected')
118
+ assert.deepEqual(await auth.connection(), { connected: true, saved: true, login: 'octocat', display: 'github.com: octocat', source: 'pinokio' })
119
+
120
+ const tokenCall = github.calls.find((call) => call.url.endsWith('/access_token'))
121
+ assert.match(tokenCall.body, /grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code/)
122
+ assert.match(tokenCall.body, /device_code=device-code-1/)
123
+
124
+ const hosts = await readHosts(homedir)
125
+ assert.deepEqual(hosts['ghe.example.com'], { oauth_token: 'ghe_token', user: 'enterprise-user', git_protocol: 'ssh' })
126
+ assert.equal(hosts['github.com'].oauth_token, 'gho_test_token')
127
+ assert.equal(hosts['github.com'].user, 'octocat')
128
+ assert.equal(hosts['github.com'].git_protocol, 'https')
129
+ assert.deepEqual(hosts['github.com'].users, {
130
+ 'other-user': { oauth_token: 'gho_other' },
131
+ octocat: { oauth_token: 'gho_test_token' },
132
+ })
133
+ if (process.platform !== 'win32') {
134
+ assert.equal((await fs.stat(hostsPath(homedir))).mode & 0o777, 0o600)
135
+ }
136
+ assert.deepEqual(await fs.readdir(path.dirname(hostsPath(homedir))), ['hosts.yml'])
137
+ })
138
+ })
139
+
140
+ test('GitHub device login reports denial and expiry as session errors', async () => {
141
+ await withTempHome(async (homedir) => {
142
+ for (const [finalError, message] of [
143
+ ['access_denied', /cancelled/],
144
+ ['expired_token', /expired/],
145
+ ]) {
146
+ const github = fakeGithub({ pendingPolls: 0, finalError })
147
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
148
+ await auth.startLogin()
149
+ await waitFor(async () => (await auth.status()).session.status === 'error')
150
+ const status = await auth.status()
151
+ assert.equal(status.connected, false)
152
+ assert.match(status.session.error, message)
153
+ }
154
+ })
155
+ })
156
+
157
+ test('GitHub device login saves nothing when the account lookup fails', async () => {
158
+ await withTempHome(async (homedir) => {
159
+ const github = fakeGithub({ pendingPolls: 0, login: '' })
160
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
161
+ await auth.startLogin()
162
+ await waitFor(async () => (await auth.status()).session.status === 'error')
163
+ const status = await auth.status()
164
+ assert.equal(status.connected, false)
165
+ assert.match(status.session.error, /account name/)
166
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
167
+ })
168
+ })
169
+
170
+ test('GitHub logout removes only the github.com entry, and the file once it is empty', async () => {
171
+ await withTempHome(async (homedir) => {
172
+ await fs.mkdir(path.dirname(hostsPath(homedir)), { recursive: true })
173
+ await fs.writeFile(hostsPath(homedir), YAML.stringify({ 'ghe.example.com': { oauth_token: 'ghe_token', user: 'enterprise-user' } }))
174
+ const github = fakeGithub({ pendingPolls: 0 })
175
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
176
+ await auth.startLogin()
177
+ await waitFor(async () => (await auth.status()).connected)
178
+
179
+ await auth.logout()
180
+ assert.deepEqual(await auth.status(), { connected: false, saved: false, login: null, display: '', source: null, session: null })
181
+ assert.deepEqual(await readHosts(homedir), { 'ghe.example.com': { oauth_token: 'ghe_token', user: 'enterprise-user' } })
182
+
183
+ await fs.writeFile(hostsPath(homedir), YAML.stringify({ 'github.com': { oauth_token: 'x', user: 'octocat' } }))
184
+ await auth.logout()
185
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
186
+ assert.deepEqual(await auth.connection(), { connected: false, saved: false, login: null, display: '', source: null })
187
+ })
188
+ })
189
+
190
+ test('GitHub logout during a finishing login leaves no token behind', async () => {
191
+ await withTempHome(async (homedir) => {
192
+ // logout while the account lookup is still in flight
193
+ const userGate = gate()
194
+ const github = fakeGithub({ pendingPolls: 0, userGate })
195
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
196
+ await auth.startLogin()
197
+ await waitFor(async () => github.calls.some((call) => call.url.endsWith('/user')))
198
+ await auth.logout()
199
+ userGate.open()
200
+ await auth.queue
201
+ await new Promise((resolve) => setTimeout(resolve, 50))
202
+ assert.equal(await auth.read(), null)
203
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
204
+
205
+ // logout while the hosts file write itself is still in flight
206
+ const slow = fakeGithub({ pendingPolls: 0 })
207
+ const auth2 = new GithubAuth(createKernel(homedir), { fetch: slow.fetch, minInterval: 0 })
208
+ let writing
209
+ const writeHosts = auth2.writeHosts.bind(auth2)
210
+ auth2.writeHosts = (hosts) => {
211
+ writing = new Promise((resolve) => setTimeout(resolve, 100)).then(() => writeHosts(hosts))
212
+ return writing
213
+ }
214
+ await auth2.startLogin()
215
+ await waitFor(async () => Boolean(writing))
216
+ await auth2.logout()
217
+ assert.equal(await auth2.read(), null)
218
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
219
+ })
220
+ })
221
+
222
+ test('GitHub logout refuses to touch a hosts file it cannot parse', async () => {
223
+ await withTempHome(async (homedir) => {
224
+ await fs.mkdir(path.dirname(hostsPath(homedir)), { recursive: true })
225
+ const broken = 'ghe.example.com: {oauth_token: ghe_token\n user: [unterminated\n'
226
+ await fs.writeFile(hostsPath(homedir), broken)
227
+ const auth = new GithubAuth(createKernel(homedir), { fetch: fakeGithub().fetch, minInterval: 0 })
228
+ await assert.rejects(() => auth.logout())
229
+ assert.equal(await fs.readFile(hostsPath(homedir), 'utf8'), broken)
230
+ assert.deepEqual(await auth.status(), { connected: false, saved: false, login: null, display: '', source: null, session: null })
231
+ })
232
+ })
233
+
234
+ test('GitHub login start is shared between concurrent callers and discarded by a logout during it', async () => {
235
+ await withTempHome(async (homedir) => {
236
+ const deviceGate = gate()
237
+ const github = fakeGithub({ pendingPolls: 0, deviceGate })
238
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
239
+
240
+ const first = auth.startLogin()
241
+ const second = auth.startLogin()
242
+ await waitFor(async () => github.calls.length === 1)
243
+ await auth.logout()
244
+ deviceGate.open()
245
+ await assert.rejects(first, /cancelled/)
246
+ await assert.rejects(second, /cancelled/)
247
+ assert.equal(github.calls.filter((call) => call.url.endsWith('/device/code')).length, 1)
248
+
249
+ await new Promise((resolve) => setTimeout(resolve, 50))
250
+ assert.deepEqual(await auth.status(), { connected: false, saved: false, login: null, display: '', source: null, session: null })
251
+ assert.equal(github.calls.some((call) => call.url.endsWith('/access_token')), false)
252
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
253
+
254
+ // a fresh start afterwards works normally
255
+ const session = await auth.startLogin()
256
+ assert.equal(session.status, 'pending')
257
+ await waitFor(async () => (await auth.status()).connected)
258
+ })
259
+ })
260
+
261
+ test('GitHub login started right after a logout does not reuse the cancelled request', async () => {
262
+ await withTempHome(async (homedir) => {
263
+ const deviceGate = gate()
264
+ const github = fakeGithub({ pendingPolls: 0, deviceGate })
265
+ const auth = new GithubAuth(createKernel(homedir), { fetch: github.fetch, minInterval: 0 })
266
+
267
+ const first = auth.startLogin()
268
+ await waitFor(async () => github.calls.length === 1)
269
+ await auth.logout()
270
+ const second = auth.startLogin() // a new request, not the cancelled one
271
+ await waitFor(async () => github.calls.filter((call) => call.url.endsWith('/device/code')).length === 2)
272
+ deviceGate.open()
273
+ await assert.rejects(first, /cancelled/)
274
+ const session = await second
275
+ assert.equal(session.status, 'pending')
276
+ assert.equal(auth.session.status, 'pending')
277
+ await waitFor(async () => (await auth.status()).connected)
278
+ })
279
+ })
280
+
281
+ test('GitHub auth can be constructed before a home exists and reports not connected', async () => {
282
+ const auth = new GithubAuth({ homedir: undefined, platform: process.platform }, { fetch: fakeGithub().fetch })
283
+ assert.deepEqual(await auth.status(), { connected: false, saved: false, login: null, display: '', source: null, session: null })
284
+ assert.deepEqual(await auth.connection(), { connected: false, saved: false, login: null, display: '', source: null })
285
+ })
286
+
287
+ test('GitHub login finishing after a home switch writes to the home it started in', async () => {
288
+ await withTempHome(async (homedir) => {
289
+ const oldHome = path.join(homedir, 'old')
290
+ const newHome = path.join(homedir, 'new')
291
+ await fs.mkdir(path.dirname(hostsPath(newHome)), { recursive: true })
292
+ const enterprise = { 'ghe.example.com': { oauth_token: 'ghe_token', user: 'enterprise-user' } }
293
+ await fs.writeFile(hostsPath(newHome), YAML.stringify(enterprise))
294
+
295
+ const kernel = createKernel(oldHome)
296
+ const old = new GithubAuth(kernel, { fetch: fakeGithub({ pendingPolls: 0 }).fetch, minInterval: 0 })
297
+ let writing
298
+ const writeHosts = old.writeHosts.bind(old)
299
+ old.writeHosts = (hosts) => {
300
+ writing = new Promise((resolve) => setTimeout(resolve, 100)).then(() => writeHosts(hosts))
301
+ return writing
302
+ }
303
+ await old.startLogin()
304
+ await waitFor(async () => Boolean(writing))
305
+
306
+ // the kernel re-initializes with another home while that write is pending
307
+ kernel.homedir = newHome
308
+ old.cancelLogin()
309
+ const fresh = new GithubAuth(kernel, { fetch: fakeGithub().fetch, minInterval: 0 })
310
+ await writing
311
+
312
+ assert.deepEqual(await readHosts(newHome), enterprise)
313
+ assert.equal((await readHosts(oldHome))['github.com'].user, 'octocat')
314
+ assert.deepEqual(await fresh.connection(), { connected: false, saved: false, login: null, display: '', source: null })
315
+ })
316
+ })
317
+
318
+ test('GitHub logout on a new instance waits for a write still running on the old one', async () => {
319
+ await withTempHome(async (homedir) => {
320
+ const kernel = createKernel(homedir)
321
+ const old = new GithubAuth(kernel, { fetch: fakeGithub({ pendingPolls: 0 }).fetch, minInterval: 0 })
322
+ let writing
323
+ const writeHosts = old.writeHosts.bind(old)
324
+ old.writeHosts = (hosts) => {
325
+ writing = new Promise((resolve) => setTimeout(resolve, 100)).then(() => writeHosts(hosts))
326
+ return writing
327
+ }
328
+ await old.startLogin()
329
+ await waitFor(async () => Boolean(writing))
330
+
331
+ // what the kernel does on re-initialization, then a logout through the new instance
332
+ old.cancelLogin()
333
+ const fresh = new GithubAuth(kernel, { fetch: fakeGithub().fetch, minInterval: 0 })
334
+ await fresh.logout()
335
+ await writing
336
+ assert.equal(await fresh.read(), null)
337
+ await assert.rejects(() => fs.stat(hostsPath(homedir)), { code: 'ENOENT' })
338
+ })
339
+ })
340
+
341
+ test('GitHub hosts file write leaves no temp file behind when the rename fails', async () => {
342
+ await withTempHome(async (homedir) => {
343
+ // a non-empty directory in the way makes the rename fail
344
+ await fs.mkdir(path.join(hostsPath(homedir), 'blocker'), { recursive: true })
345
+ await fs.writeFile(path.join(hostsPath(homedir), 'blocker', 'x'), 'x')
346
+ const auth = new GithubAuth(createKernel(homedir), { fetch: fakeGithub().fetch, minInterval: 0 })
347
+ await assert.rejects(() => auth.save('gho_secret', 'octocat'))
348
+ assert.deepEqual(await fs.readdir(path.dirname(hostsPath(homedir))), ['hosts.yml'])
349
+ })
350
+ })
351
+
352
+ test('GitHub connection reports a login git found outside Pinokio, and an environment override', async () => {
353
+ await withTempHome(async (homedir) => {
354
+ const kernel = createKernel(homedir)
355
+ let credential = null
356
+ let lookupOptions
357
+ kernel.git = { getCredentialForUrl: async (url, options) => { lookupOptions = options; return credential } }
358
+ const auth = new GithubAuth(kernel, { fetch: fakeGithub().fetch, minInterval: 0 })
359
+
360
+ assert.deepEqual(await auth.connection({ timeout: 2500 }), { connected: false, saved: false, login: null, display: '', source: null })
361
+ assert.equal(lookupOptions.timeout, 2500)
362
+
363
+ credential = { username: 'x-access-token', password: 'gho_from_keyring' }
364
+ const outside = await auth.connection()
365
+ assert.equal(outside.connected, true)
366
+ assert.equal(outside.saved, false)
367
+ assert.equal(outside.source, 'system')
368
+ assert.match(outside.display, /outside Pinokio/)
369
+
370
+ await auth.save('gho_pinokio', 'octocat')
371
+ credential = { username: 'octocat', password: 'gho_pinokio' }
372
+ assert.deepEqual(await auth.connection(), { connected: true, saved: true, login: 'octocat', display: 'github.com: octocat', source: 'pinokio' })
373
+
374
+ credential = { username: 'x-access-token', password: 'gho_env' }
375
+ const overridden = await auth.connection()
376
+ assert.equal(overridden.source, 'system')
377
+ assert.equal(overridden.saved, true)
378
+ assert.equal(overridden.login, 'octocat')
379
+ assert.match(overridden.display, /GH_TOKEN/)
380
+ const status = await auth.status()
381
+ assert.equal(status.saved, true)
382
+ assert.equal(status.source, 'system')
383
+ })
384
+ })
385
+
386
+ const hasGh = () => new Promise((resolve) => execFile('gh', ['--version'], (error) => resolve(!error)))
387
+
388
+ test('git credential fill gets the stored token through gh with the Pinokio gitconfig', async (t) => {
389
+ if (!(await hasGh())) {
390
+ t.skip('gh is not installed')
391
+ return
392
+ }
393
+ await withTempHome(async (homedir) => {
394
+ const kernel = createKernel(homedir)
395
+ await new KernelGit(kernel).ensureDefaults()
396
+ await new GithubAuth(kernel).save('gho_fill_token', 'octocat')
397
+
398
+ // gh also honours GH_TOKEN / GITHUB_TOKEN from the environment; keep the test to the hosts file
399
+ const env = {
400
+ ...process.env,
401
+ GH_TOKEN: '',
402
+ GITHUB_TOKEN: '',
403
+ GH_ENTERPRISE_TOKEN: '',
404
+ GITHUB_ENTERPRISE_TOKEN: '',
405
+ GIT_CONFIG_GLOBAL: path.join(homedir, 'gitconfig'),
406
+ GIT_CONFIG_NOSYSTEM: '1',
407
+ GIT_TERMINAL_PROMPT: '0',
408
+ GIT_ASKPASS: '',
409
+ GH_CONFIG_DIR: path.join(homedir, 'config/gh'),
410
+ }
411
+ const fill = async (input) => new Promise((resolve) => {
412
+ const child = execFile('git', ['credential', 'fill'], { env, cwd: homedir }, (error, stdout, stderr) => {
413
+ resolve({ error, stdout: String(stdout || ''), stderr: String(stderr || '') })
414
+ })
415
+ child.stdin.end(input)
416
+ })
417
+
418
+ const github = await fill('protocol=https\nhost=github.com\n\n')
419
+ assert.match(github.stdout, /^username=octocat$/m)
420
+ assert.match(github.stdout, /^password=gho_fill_token$/m)
421
+
422
+ // other hosts never see the token; git has no other helper and no terminal, so fill fails
423
+ const other = await fill('protocol=https\nhost=gitlab.com\n\n')
424
+ assert.doesNotMatch(other.stdout, /gho_fill_token/)
425
+
426
+ // after logout the Pinokio token is gone (gh may still fall back to a token in the OS keyring)
427
+ await new GithubAuth(kernel).logout()
428
+ const anonymous = await fill('protocol=https\nhost=github.com\n\n')
429
+ assert.doesNotMatch(anonymous.stdout, /gho_fill_token|username=octocat/)
430
+ })
431
+ })