Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

credentials.test.ts

68 lines2.0 KB

1import { mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, describe, expect, it } from 'vitest'
5​
6import {
7 credentialsPath,
8 loadCredentials,
9 saveCredentials,
10} from './credentials.ts'
11​
12const ORIGINAL = process.env.MODELSCHEMAS_CONFIG_DIR
13​
14afterEach(() => {
15 if (ORIGINAL === undefined) delete process.env.MODELSCHEMAS_CONFIG_DIR
16 else process.env.MODELSCHEMAS_CONFIG_DIR = ORIGINAL
17})
18​
19describe('credentials storage', () => {
20 it('round-trips credentials with 0600 permissions', () => {
21 process.env.MODELSCHEMAS_CONFIG_DIR = mkdtempSync(
22 join(tmpdir(), 'ms-cli-creds-'),
23 )
24 expect(loadCredentials()).toBeNull()
25​
26 const path = saveCredentials({
27 type: 'api-key',
28 baseUrl: 'http://localhost:3100',
29 apiKey: 'test-key',
30 })
31 expect(path).toBe(credentialsPath())
32 expect(statSync(path).mode & 0o777).toBe(0o600)
33 expect(loadCredentials()).toEqual({
34 type: 'api-key',
35 baseUrl: 'http://localhost:3100',
36 apiKey: 'test-key',
37 })
38​
39 // Agent credentials round-trip including the private key JWK.
40 saveCredentials({
41 type: 'agent',
42 baseUrl: 'http://localhost:3100',
43 agentId: 'agent-1',
44 hostId: 'host-1',
45 privateKeyJwk: { kty: 'OKP', crv: 'Ed25519', d: 'x', x: 'y' },
46 })
47 const loaded = loadCredentials()
48 expect(loaded?.type).toBe('agent')
49 if (loaded?.type === 'agent') {
50 expect(loaded.privateKeyJwk.crv).toBe('Ed25519')
51 }
52 // Raw file never readable beyond owner; sanity-check the JSON itself.
53 expect(JSON.parse(readFileSync(path, 'utf8'))).toEqual(loaded)
54 })
55​
56 it('returns null for corrupt credential files', () => {
57 process.env.MODELSCHEMAS_CONFIG_DIR = mkdtempSync(
58 join(tmpdir(), 'ms-cli-creds-'),
59 )
60 saveCredentials({
61 type: 'api-key',
62 baseUrl: 'http://x',
63 apiKey: 'k',
64 })
65 writeFileSync(credentialsPath(), 'not json')
66 expect(loadCredentials()).toBeNull()
67 })
68})