From ec7cc4ac6b046bda0696a03863bf4cf1d95eba23 Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 2 Dec 2026 10:17:09 -0500 Subject: [PATCH] feat(vscode): select org explicitly --- package.json | 9 + src/api.mts | 2 + src/auth-context-state.mts | 34 +++ src/auth.mts | 289 +++++++++++++----- src/data/editor-config.mts | 21 +- src/extension.mts | 53 ++-- src/organization-selection.mts | 37 +++ src/ui/purl-alerts-and-scores/manager.mts | 85 ++++++ test/repo/unit/api.test.mts | 6 +- test/repo/unit/auth-lifecycle.test.mts | 196 ++++++++++-- test/repo/unit/auth.test.mts | 1 + .../repo/unit/organization-selection.test.mts | 60 ++++ .../manager-cache-requests.test.mts | 71 +++++ test/stubs/vscode.mts | 19 ++ 14 files changed, 752 insertions(+), 131 deletions(-) create mode 100644 src/auth-context-state.mts create mode 100644 src/organization-selection.mts create mode 100644 test/repo/unit/organization-selection.test.mts diff --git a/package.json b/package.json index 784007dd..fd614995 100644 --- a/package.json +++ b/package.json @@ -138,6 +138,15 @@ "configuration": { "title": "Socket Security", "properties": { + "socket-security.orgSlug": { + "order": 1, + "type": "string", + "scope": "window", + "description": "Socket organization slug for your API token. Select a slug accessible to the token.", + "examples": [ + "acme" + ] + }, "socket-security.pythonInterpreter": { "order": 1, "type": "string", diff --git a/src/api.mts b/src/api.mts index 2f6f82c0..75245e67 100644 --- a/src/api.mts +++ b/src/api.mts @@ -15,6 +15,7 @@ import { export type OrgInfo = { id: string + slug: string name: string image: string | undefined // The Socket API returns an open-ended plan string (opensource, team, @@ -120,6 +121,7 @@ export async function getOrganizations( const org = orgList[i]! organizations.set(org.id, { id: org.id, + slug: typeof org.slug === 'string' ? org.slug : '', name: org.name ?? '', image: org.image ?? undefined, plan: org.plan, diff --git a/src/auth-context-state.mts b/src/auth-context-state.mts new file mode 100644 index 00000000..38be4fa6 --- /dev/null +++ b/src/auth-context-state.mts @@ -0,0 +1,34 @@ +export type Listener = (ready: boolean) => void + +let revision = 0 +let ready = true +const listeners = new Set() + +export function beginAuthContextSync(): number { + revision += 1 + ready = false + for (const listener of listeners) { + listener(false) + } + return revision +} + +export function finishAuthContextSync(syncRevision: number): boolean { + if (syncRevision !== revision) { + return false + } + ready = true + for (const listener of listeners) { + listener(true) + } + return true +} + +export function getAuthContextState(): { revision: number; ready: boolean } { + return { revision, ready } +} + +export function onAuthContextStateChange(listener: Listener): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} diff --git a/src/auth.mts b/src/auth.mts index c8954153..9d512168 100644 --- a/src/auth.mts +++ b/src/auth.mts @@ -1,12 +1,32 @@ -import crypto from 'node:crypto' +import { + authentication, + commands, + EventEmitter, + FileType, + StatusBarAlignment, + Uri, + window, + workspace, + type AuthenticationProviderAuthenticationSessionsChangeEvent, + type AuthenticationProviderSessionOptions, + type AuthenticationSession, + type Disposable, + type ExtensionContext, + type SecretStorage, + type StatusBarItem, +} from 'vscode' import os from 'node:os' import path from 'node:path' - -import * as vscode from 'vscode' - import { DIAGNOSTIC_SOURCE_STR, EXTENSION_PREFIX } from './util.mts' +import crypto from 'node:crypto' import { getOrganizations } from './api.mts' import type { OrgInfo } from './api.mts' +import { selectOrganization } from './organization-selection.mts' +import { + beginAuthContextSync, + finishAuthContextSync, + getAuthContextState, +} from './auth-context-state.mts' import { createRetiredApiTokenError, isRetiredApiToken, @@ -17,23 +37,28 @@ export type APIConfig = { apiKey: string } +export type AuthenticatedContext = { + accessToken: string + organization: OrgInfo +} + export type SettingsFile = { apiKey?: string | undefined [key: string]: unknown } -// The token lives in vscode.SecretStorage, which is backed by the OS keychain. +// The token lives in SecretStorage, which is backed by the OS keychain. export const API_TOKEN_SECRET_KEY = 'apiToken' let retiredCredentialBlocked = false let credentialStateReady = false export async function activate( - context: vscode.ExtensionContext, - disposables: vscode.Disposable[], + context: ExtensionContext, + disposables: Disposable[], ) { const { secrets } = context - const pleaseLoginStatusBar = vscode.window.createStatusBarItem( - vscode.StatusBarAlignment.Left, + const pleaseLoginStatusBar = window.createStatusBarItem( + StatusBarAlignment.Left, 100, ) pleaseLoginStatusBar.hide() @@ -42,6 +67,7 @@ export async function activate( 'Socket Security needs to login for full functionality' pleaseLoginStatusBar.command = `${EXTENSION_PREFIX}.login` + beginAuthContextSync() let legacyRetiredCredential = false retiredCredentialBlocked = false credentialStateReady = false @@ -51,27 +77,26 @@ export async function activate( //#region session sync // responsible for keeping SecretStorage and mem in sync let liveSessions: Map< - vscode.AuthenticationSession['accessToken'], - vscode.AuthenticationSession + AuthenticationSession['accessToken'], + AuthenticationSession > = new Map() let sessionRevision = 0 + let latestSessionSync: Promise | undefined const storedSessionsChanges = - new vscode.EventEmitter() + new EventEmitter() // SecretStorage is shared across windows of the same profile, so another // window logging in or out shows up here. disposables?.push( secrets.onDidChange(e => { if (e.key === API_TOKEN_SECRET_KEY) { - void syncLiveSessionFromSecretStorage().catch(() => {}) + void requestSessionSync().catch(() => {}) } }), ) - function isRetiredCredential(apiKey: string | undefined): boolean { - return isRetiredApiToken(apiKey) || (!apiKey && legacyRetiredCredential) - } async function syncLiveSessionFromSecretStorage() { const revision = ++sessionRevision + const contextRevision = beginAuthContextSync() credentialStateReady = false let apiKey: string | undefined try { @@ -80,25 +105,33 @@ export async function activate( return } const storedSessions: typeof liveSessions = new Map< - vscode.AuthenticationSession['accessToken'], - vscode.AuthenticationSession + AuthenticationSession['accessToken'], + AuthenticationSession >() - const retiredCredential = isRetiredCredential(apiKey) + const retiredCredential = + isRetiredApiToken(apiKey) || (!apiKey && legacyRetiredCredential) const organizations = apiKey && !retiredCredential ? await getOrganizations(apiKey) : undefined - const org = organizations?.organizations.values().next().value - const resolvedSession = resolveStoredSession(apiKey, org, liveSessions) - if (resolvedSession) { - storedSessions.set(resolvedSession.accessToken, resolvedSession) + if (apiKey && organizations) { + storedSessions.set( + apiKey, + sessionForOrganizationSelection( + apiKey, + organizations.organizations, + workspace.getConfiguration().get('socket-security.orgSlug'), + liveSessions.get(apiKey), + ), + ) } if (revision !== sessionRevision) { + await waitForLatestSessionSync() return } retiredCredentialBlocked = retiredCredential credentialStateReady = true - const added: vscode.AuthenticationSession[] = [] - const changed: vscode.AuthenticationSession[] = [] - const removed: vscode.AuthenticationSession[] = [] + const added: AuthenticationSession[] = [] + const changed: AuthenticationSession[] = [] + const removed: AuthenticationSession[] = [] // oxlint-disable-next-line socket/prefer-cached-for-loop -- iterating a Map's values iterator. for (const storedSession of storedSessions.values()) { // already have this access token in mem session @@ -117,11 +150,6 @@ export async function activate( removed.push(liveSessionWithoutStoredSession) } liveSessions = storedSessions - if (retiredCredential) { - pleaseLoginStatusBar.show() - } else if (storedSessions.size > 0) { - pleaseLoginStatusBar.hide() - } if (added.length + changed.length + removed.length > 0) { storedSessionsChanges.fire({ added, @@ -129,10 +157,24 @@ export async function activate( removed, }) } + updateLoginStatusBar( + pleaseLoginStatusBar, + retiredCredential, + storedSessions, + ) + finishAuthContextSync(contextRevision) + } + function requestSessionSync(): Promise { + const sync = syncLiveSessionFromSecretStorage() + latestSessionSync = sync + return sync + } + async function waitForLatestSessionSync() { + await latestSessionSync } //#endregion //#region service glue - const service = vscode.authentication.registerAuthenticationProvider( + const service = authentication.registerAuthenticationProvider( EXTENSION_PREFIX, DIAGNOSTIC_SOURCE_STR, { @@ -141,16 +183,16 @@ export async function activate( }, async getSessions( _scopes: readonly string[] | undefined, - _options: vscode.AuthenticationProviderSessionOptions, - ): Promise { + _options: AuthenticationProviderSessionOptions, + ): Promise { return Array.from(liveSessions.values()) }, async createSession( _scopes: readonly string[], - _options: vscode.AuthenticationProviderSessionOptions, - ): Promise { + _options: AuthenticationProviderSessionOptions, + ): Promise { const apiKey: string = - (await vscode.window.showInputBox({ + (await window.showInputBox({ title: 'Socket Security API Token', placeHolder: 'Leave this blank to stay logged out', ignoreFocusOut: true, @@ -175,19 +217,23 @@ export async function activate( } throwIfRetiredApiToken(apiKey) const organizations = await getOrganizations(apiKey) - const org = organizations?.organizations.values().next().value - if (!org) { - throw new Error('No organization found for the provided API key') + if (!organizations) { + throw new Error('Invalid API key') } - await secrets.store(API_TOKEN_SECRET_KEY, apiKey) + beginAuthContextSync() + try { + await secrets.store(API_TOKEN_SECRET_KEY, apiKey) + } catch (error) { + await requestSessionSync() + throw error + } + await requestSessionSync() legacyRetiredCredential = false - await syncLiveSessionFromSecretStorage() const session = liveSessions.get(apiKey) if (!session) { - throw new Error( - 'Socket credentials changed during login. Retry Socket Security Login.', - ) + throw new Error('The API token changed while logging in') } + pleaseLoginStatusBar.hide() return session }, async removeSession(sessionId: string): Promise { @@ -197,9 +243,15 @@ export async function activate( if (!session) { return } - await secrets.delete(API_TOKEN_SECRET_KEY) - legacyRetiredCredential = false - await syncLiveSessionFromSecretStorage() + beginAuthContextSync() + try { + await secrets.delete(API_TOKEN_SECRET_KEY) + legacyRetiredCredential = false + } catch (error) { + await requestSessionSync() + throw error + } + await requestSessionSync() try { pleaseLoginStatusBar.show() } catch {} @@ -207,7 +259,14 @@ export async function activate( }, ) context.subscriptions.push(service) - vscode.commands.registerCommand(`${EXTENSION_PREFIX}.login`, async () => { + context.subscriptions.push( + workspace.onDidChangeConfiguration(event => { + if (event.affectsConfiguration('socket-security.orgSlug')) { + void requestSessionSync().catch(() => {}) + } + }), + ) + commands.registerCommand(`${EXTENSION_PREFIX}.login`, async () => { // An explicit Login must always let the user re-enter a token, even when a // stale or cached session already exists. `createIfNone` only prompts when // NO session is present, so a leftover session made the command a silent @@ -216,17 +275,17 @@ export async function activate( // unused; the catch swallows the rejection VSCode raises when the user // dismisses the prompt, which is a cancel and not a command failure. try { - await vscode.authentication.getSession(EXTENSION_PREFIX, [], { + await authentication.getSession(EXTENSION_PREFIX, [], { forceNewSession: true, }) } catch {} }) try { - await syncLiveSessionFromSecretStorage() + await requestSessionSync() } catch {} let session try { - session = await vscode.authentication.getSession(EXTENSION_PREFIX, [], { + session = await authentication.getSession(EXTENSION_PREFIX, [], { createIfNone: false, }) } catch {} @@ -238,6 +297,10 @@ export async function activate( } export async function getAPIKey() { + const start = getAuthContextState() + if (!start.ready) { + return undefined + } if (!credentialStateReady) { throw new Error( 'Socket credential storage is unavailable. Retry Socket Security Login.', @@ -246,9 +309,13 @@ export async function getAPIKey() { if (retiredCredentialBlocked) { throw createRetiredApiTokenError() } - const session = await vscode.authentication.getSession(EXTENSION_PREFIX, [], { + const session = await authentication.getSession(EXTENSION_PREFIX, [], { createIfNone: false, }) + const end = getAuthContextState() + if (start.revision !== end.revision || !end.ready) { + return undefined + } if (!credentialStateReady) { throw new Error( 'Socket credential storage is unavailable. Retry Socket Security Login.', @@ -258,7 +325,56 @@ export async function getAPIKey() { throw createRetiredApiTokenError() } throwIfRetiredApiToken(session?.accessToken) - return session?.accessToken + return start.revision === end.revision && end.ready + ? session?.accessToken + : undefined +} + +export async function getAuthenticatedContext(): Promise< + AuthenticatedContext | undefined +> { + const start = getAuthContextState() + if (!start.ready) { + return undefined + } + if (!credentialStateReady) { + throw new Error( + 'Socket credential storage is unavailable. Retry Socket Security Login.', + ) + } + if (retiredCredentialBlocked) { + throw createRetiredApiTokenError() + } + const session = await authentication.getSession(EXTENSION_PREFIX, [], { + createIfNone: false, + }) + if (!session) { + return undefined + } + throwIfRetiredApiToken(session.accessToken) + if (start.revision !== getAuthContextState().revision) { + return undefined + } + const configuredSlug = workspace + .getConfiguration() + .get('socket-security.orgSlug') + const organizations = await getOrganizations(session.accessToken) + const currentSession = await authentication.getSession(EXTENSION_PREFIX, [], { + createIfNone: false, + }) + if ( + start.revision !== getAuthContextState().revision || + currentSession?.accessToken !== session.accessToken + ) { + return undefined + } + const selection = selectOrganization( + configuredSlug, + organizations?.organizations, + ) + return selection.status === 'selected' + ? { accessToken: session.accessToken, organization: selection.organization } + : undefined } /** @@ -296,18 +412,18 @@ export function getLegacySettingsPath(): string | undefined { * preserved. */ export async function migrateApiTokenToSecretStorage( - secrets: vscode.SecretStorage, + secrets: SecretStorage, ): Promise { const settingsPath = getLegacySettingsPath() if (!settingsPath) { return false } - const settingsUri = vscode.Uri.file(settingsPath) + const settingsUri = Uri.file(settingsPath) try { // Need FileType metadata for file vs. directory detection on remote. // oxlint-disable-next-line socket/prefer-exists-sync -- metadata - const stat = await vscode.workspace.fs.stat(settingsUri) - if (!(stat.type & vscode.FileType.File)) { + const stat = await workspace.fs.stat(settingsUri) + if (!(stat.type & FileType.File)) { return false } } catch { @@ -336,14 +452,14 @@ export async function migrateApiTokenToSecretStorage( delete settings['apiKey'] try { if (Object.keys(settings).length > 0) { - await vscode.workspace.fs.writeFile( + await workspace.fs.writeFile( settingsUri, new TextEncoder().encode( Buffer.from(JSON.stringify(settings)).toString('base64'), ), ) } else { - await vscode.workspace.fs.delete(settingsUri) + await workspace.fs.delete(settingsUri) } } catch { // Leaving the file in place costs a repeated migration attempt, which is @@ -356,9 +472,7 @@ export async function readLegacySettings( settingsPath: string, ): Promise { try { - const existingContent = await vscode.workspace.fs.readFile( - vscode.Uri.file(settingsPath), - ) + const existingContent = await workspace.fs.readFile(Uri.file(settingsPath)) const decoded = Buffer.from( new TextDecoder().decode(existingContent), 'base64', @@ -377,28 +491,47 @@ export async function readLegacySettings( return {} } -export function resolveStoredSession( - apiKey: string | undefined, - org: OrgInfo | undefined, - liveSessions: Map< - vscode.AuthenticationSession['accessToken'], - vscode.AuthenticationSession - >, -): vscode.AuthenticationSession | undefined { - return apiKey && org - ? sessionFromAPIKey(apiKey, org, liveSessions.get(apiKey)) - : undefined +function sessionForOrganizationSelection( + apiKey: string, + organizations: Map, + configuredSlug: unknown, + previousSession?: AuthenticationSession, +) { + const selection = selectOrganization(configuredSlug, organizations) + const organization = + selection.status === 'selected' + ? selection.organization + : { + id: 'socket-token', + slug: '', + name: 'Socket API token', + image: undefined, + plan: '', + } + return sessionFromAPIKey(apiKey, organization, previousSession) +} + +function updateLoginStatusBar( + statusBar: StatusBarItem, + retiredCredential: boolean, + storedSessions: Map, +) { + if (retiredCredential) { + statusBar.show() + } else if (storedSessions.size > 0) { + statusBar.hide() + } } export function sessionFromAPIKey( apiKey: string, org: OrgInfo, - previousSession?: vscode.AuthenticationSession | undefined, + previousSession?: AuthenticationSession | undefined, ) { throwIfRetiredApiToken(apiKey) const account = { id: org.id, - label: `${org.name} (${org.plan})`, + label: org.plan ? `${org.name} (${org.plan})` : org.name, } if ( previousSession?.account.id === account.id && @@ -406,8 +539,8 @@ export function sessionFromAPIKey( ) { return previousSession } - // The id is a bare UUID: `session.id` and `account.id` are readable far more - // widely than `accessToken`, so neither may carry the token. + // The id is a bare UUID: `session.id` and `account.id` are readable by far + // more of the editor than `accessToken` is, so neither may carry the token. return { __proto__: null, accessToken: apiKey, diff --git a/src/data/editor-config.mts b/src/data/editor-config.mts index 021d2b32..59c26023 100644 --- a/src/data/editor-config.mts +++ b/src/data/editor-config.mts @@ -1,4 +1,4 @@ -import * as vscode from 'vscode' +import { workspace, type Disposable, type ExtensionContext } from 'vscode' /** * @example @@ -14,7 +14,7 @@ import * as vscode from 'vscode' * * @returns */ -export function activate(context: vscode.ExtensionContext) { +export function activate(context: ExtensionContext) { type Callback = (data: unknown[]) => void type Listener = { sections: string[] @@ -30,8 +30,8 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.splice(i, 1) } } - onDidChangeConfigurationDisposable = - vscode.workspace.onDidChangeConfiguration(e => { + onDidChangeConfigurationDisposable = workspace.onDidChangeConfiguration( + e => { const fired = new Set() // oxlint-disable-next-line socket/prefer-cached-for-loop -- iterating a Map's keys iterator. for (const section of watchers.keys()) { @@ -49,11 +49,11 @@ export function activate(context: vscode.ExtensionContext) { } } } - }) + }, + ) context.subscriptions.push(onDidChangeConfigurationDisposable) } - let onDidChangeConfigurationDisposable: vscode.Disposable | undefined = - undefined + let onDidChangeConfigurationDisposable: Disposable | undefined = undefined function getValuesForListener(listener: Listener) { return getConfigValues(listener.sections) } @@ -67,13 +67,18 @@ export function activate(context: vscode.ExtensionContext) { function getConfigValues( sections: string[], ): RESULTS { - const root = vscode.workspace.getConfiguration() + const root = workspace.getConfiguration() return sections.map(section => { return root.get(section) }) as RESULTS } return { __proto__: null, + getOrgSlug() { + return workspace + .getConfiguration() + .get('socket-security.orgSlug') + }, getConfigValues, onDependentConfig(sections: string[], fn: Callback) { const listener: Listener = { diff --git a/src/extension.mts b/src/extension.mts index c7fffc56..5598206c 100644 --- a/src/extension.mts +++ b/src/extension.mts @@ -1,37 +1,42 @@ -// The module 'vscode' contains the VS Code extensibility API -// Import the module and reference it with the alias vscode in your code below - -import * as vscode from 'vscode' +import { + lm, + McpHttpServerDefinition, + Uri, + type ExtensionContext, + type McpServerDefinitionProvider, +} from 'vscode' import { activate as activateAuth } from './auth.mts' import { activate as activateEditorConfig } from './data/editor-config.mts' import { activate as activateFiles } from './ui/file.mts' -import { initializeCacheStorage } from './ui/purl-alerts-and-scores/manager.mts' +import { + activatePackageDataInvalidation, + initializeCacheStorage, +} from './ui/purl-alerts-and-scores/manager.mts' -export async function activate(context: vscode.ExtensionContext) { +export async function activate(context: ExtensionContext) { initializeCacheStorage(context.globalStorageUri.fsPath) activateEditorConfig(context) + activatePackageDataInvalidation(context) await activateAuth(context, context.subscriptions) activateFiles(context) - if (vscode.lm?.registerMcpServerDefinitionProvider) { - const definition: vscode.McpHttpServerDefinition = - new vscode.McpHttpServerDefinition( - '[Extension] Socket Security', - vscode.Uri.parse('https://mcp.socket.dev/'), - { - 'user-agent': `Socket Security VSCode Extension/${process.env['INLINED_EXTENSION_VERSION']}`, - }, - ) - const provider: vscode.McpServerDefinitionProvider = + if (lm?.registerMcpServerDefinitionProvider) { + const definition: McpHttpServerDefinition = new McpHttpServerDefinition( + '[Extension] Socket Security', + Uri.parse('https://mcp.socket.dev/'), { - provideMcpServerDefinitions(_token) { - return [definition] - }, - resolveMcpServerDefinition(def, _token) { - return def - }, - } - vscode.lm.registerMcpServerDefinitionProvider( + 'user-agent': `Socket Security VSCode Extension/${process.env['INLINED_EXTENSION_VERSION']}`, + }, + ) + const provider: McpServerDefinitionProvider = { + provideMcpServerDefinitions(_token) { + return [definition] + }, + resolveMcpServerDefinition(def, _token) { + return def + }, + } + lm.registerMcpServerDefinitionProvider( 'socket-security.mcp-server', provider, ) diff --git a/src/organization-selection.mts b/src/organization-selection.mts new file mode 100644 index 00000000..7c49b6ff --- /dev/null +++ b/src/organization-selection.mts @@ -0,0 +1,37 @@ +import type { OrgInfo } from './api.mts' + +export type OrganizationSelection = + | { status: 'missing' } + | { status: 'invalid' } + | { status: 'unavailable' } + | { status: 'inaccessible'; slug: string } + | { status: 'ambiguous'; slug: string } + | { status: 'selected'; organization: OrgInfo } + +export function selectOrganization( + configuredSlug: unknown, + organizations: ReadonlyMap | undefined, +): OrganizationSelection { + if (configuredSlug === undefined || configuredSlug === '') { + return { status: 'missing' } + } + if ( + typeof configuredSlug !== 'string' || + configuredSlug.trim() !== configuredSlug + ) { + return { status: 'invalid' } + } + if (!organizations) { + return { status: 'unavailable' } + } + const matches = Array.from(organizations.values()).filter( + organization => organization.slug === configuredSlug, + ) + if (matches.length === 0) { + return { status: 'inaccessible', slug: configuredSlug } + } + if (matches.length > 1) { + return { status: 'ambiguous', slug: configuredSlug } + } + return { status: 'selected', organization: matches[0]! } +} diff --git a/src/ui/purl-alerts-and-scores/manager.mts b/src/ui/purl-alerts-and-scores/manager.mts index 3ce59aa5..54f5bf33 100644 --- a/src/ui/purl-alerts-and-scores/manager.mts +++ b/src/ui/purl-alerts-and-scores/manager.mts @@ -1,4 +1,5 @@ import type { SimPURL } from '../externals/parse-externals.mts' +import { Disposable, type ExtensionContext } from 'vscode' import { logger } from '../../infra/log.mts' import path from 'node:path' import { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' @@ -11,15 +12,35 @@ import type { PackageScoreAndAlerts } from '../../api.mts' import { safeDeleteSync } from '@socketsecurity/lib/fs/safe' import { isObject } from '@socketsecurity/lib/objects/predicates' import { worstArtifactsByPurl } from './select-artifacts.mts' +import { onAuthContextStateChange } from '../../auth-context-state.mts' export let cacheDirectory: string | undefined +export function activatePackageDataInvalidation(context: ExtensionContext) { + context.subscriptions.push( + new Disposable( + onAuthContextStateChange(ready => { + if (ready) { + PURLDataCache.singleton.resume() + } else { + clearPackageData() + } + }), + ), + ) +} + export function clearCache() { if (cacheDirectory) { safeDeleteSync(cacheDirectory) } } +export function clearPackageData() { + PURLDataCache.singleton.clear(false) + clearCache() +} + export function initializeCacheStorage(globalStoragePath: string) { cacheDirectory = path.join(globalStoragePath, 'package-data') } @@ -129,6 +150,9 @@ export class PURLPackageData { watcher(this) } } + notifyContextChanged() { + this.#notifyWatchers() + } } export class PURLDataCache { static singleton: PURLDataCache = new PURLDataCache() @@ -138,7 +162,51 @@ export class PURLDataCache { #pkgsNeedingUpdate: Set = new Set() // in-flight PURLs #currentPendingUpdates: Set = new Set() + #controllers: Set = new Set() + #generation = 0 + #contextReady = true private constructor() {} + clear(requeueActive = true) { + this.#generation += 1 + if (!requeueActive) { + this.#contextReady = false + } + for (const controller of this.#controllers) { + controller.abort(new Error('Authentication context changed')) + } + this.#controllers.clear() + this.#pkgsNeedingUpdate.clear() + this.#currentPendingUpdates.clear() + const activePurls = Array.from(this.#pkgData.keys()) + for (const data of this.#pkgData.values()) { + data.pkgData = undefined + data.error = undefined + data.mtime = -Infinity + data.notifyContextChanged() + const filePath = data.filepath() + if (filePath) { + try { + safeDeleteSync(filePath) + } catch {} + } + } + if (requeueActive) { + for (let i = 0, { length } = activePurls; i < length; i += 1) { + this.queueUpdate(activePurls[i]!) + } + } + } + resume() { + if (this.#contextReady) { + return + } + this.#contextReady = true + const pendingPurls = Array.from(this.#pkgsNeedingUpdate) + this.#pkgsNeedingUpdate.clear() + for (const purl of new Set([...this.#pkgData.keys(), ...pendingPurls])) { + this.queueUpdate(purl) + } + } watch(purl: SimPURL): PURLPackageData { let pkgDataForPURL = this.#pkgData.get(purl) if (!pkgDataForPURL) { @@ -158,16 +226,26 @@ export class PURLDataCache { } const thisIsTheBusForTheseUpdates = this.#pkgsNeedingUpdate.size === 0 this.#pkgsNeedingUpdate.add(purl) + if (!this.#contextReady) { + return + } // logger.info(`is bus`, thisIsTheBusForTheseUpdates, `for`, purl, `pending updates:`, this.#currentPendingUpdates.size, `queued updates:`, this.#pkgsNeedingUpdate.size); if (!thisIsTheBusForTheseUpdates) { return // already scheduled a bus trip } const controller = new AbortController() + const generation = this.#generation + this.#controllers.add(controller) const abort = controller.abort.bind(controller) const timer = setTimeout(abort, this.timeout) void (async () => { await Promise.resolve() + if (generation !== this.#generation) { + this.#controllers.delete(controller) + clearTimeout(timer) + return + } const thesePendingUpdates = new Set(Array.from(this.#pkgsNeedingUpdate)) this.#pkgsNeedingUpdate.clear() // oxlint-disable-next-line socket/prefer-cached-for-loop -- iterating a Set. @@ -192,12 +270,18 @@ export class PURLDataCache { } controller.signal.addEventListener('abort', () => { clearTimeout(timer) + if (generation !== this.#generation) { + return + } bailPendingCacheEntries( controller.signal.reason || new Error('Aborted'), ) }) try { const apiKey = await getAPIKey() + if (controller.signal.aborted || generation !== this.#generation) { + return + } // logger.info(`Requesting Socket API for PURLs: ${[...thesePendingUpdates].join(', ')}`) // Bound the SDK request with the same ceiling the AbortController timer // uses so a hung connection can't leave entries pending forever. @@ -256,6 +340,7 @@ export class PURLDataCache { bailPendingCacheEntries(reason) } finally { clearTimeout(timer) + this.#controllers.delete(controller) } })() } diff --git a/test/repo/unit/api.test.mts b/test/repo/unit/api.test.mts index 6bfa25e9..388adfa3 100644 --- a/test/repo/unit/api.test.mts +++ b/test/repo/unit/api.test.mts @@ -84,6 +84,7 @@ describe('api getOrganizations', () => { name: 'Acme', image: 'https://img/acme.png', plan: 'enterprise', + slug: 'acme', }, ], ]), @@ -105,6 +106,7 @@ describe('api getOrganizations', () => { expect(result?.organizations.get('org-2')).toEqual({ id: 'org-2', + slug: 'nully', name: '', image: undefined, plan: 'some-future-plan', @@ -315,7 +317,9 @@ describe('api streamPackageScores', () => { const scope = nock(PURL_ORIGIN) .post('/batch') .query({ alerts: 'true', compact: 'false' }) - .reply(status, { error: { message: `Authorization: Bearer ${TOKEN}` } }) + .reply(status, { + error: { message: `Authorization: Bearer ${TOKEN}` }, + }) const result = collectPackageScores(streamPackageScores(TOKEN, [purl])) await expect(result).rejects.toMatchObject({ diff --git a/test/repo/unit/auth-lifecycle.test.mts b/test/repo/unit/auth-lifecycle.test.mts index fb5e6ed2..6597c1dd 100644 --- a/test/repo/unit/auth-lifecycle.test.mts +++ b/test/repo/unit/auth-lifecycle.test.mts @@ -1,28 +1,50 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest' -import * as vscode from 'vscode' +import { + authentication, + Disposable, + EventEmitter, + window, + workspace, + type AuthenticationProvider, + type ExtensionContext, + type SecretStorageChangeEvent, +} from 'vscode' import { getOrganizations } from '../../../src/api.mts' -import { activate, API_TOKEN_SECRET_KEY } from '../../../src/auth.mts' -import { resetStubAuthState } from '../../stubs/vscode.mts' +import { + activate, + API_TOKEN_SECRET_KEY, + getAPIKey, + getAuthenticatedContext, +} from '../../../src/auth.mts' +import { getAuthContextState } from '../../../src/auth-context-state.mts' +import { + fireStubConfigurationChange, + resetStubConfigurationChanges, + resetStubAuthState, + setStubGetSessionResult, + setStubWorkspaceState, +} from '../../stubs/vscode.mts' import type { OrganizationsRecord } from '../../../src/api.mts' vi.mock('../../../src/api.mts', () => ({ getOrganizations: vi.fn() })) vi.mock('vscode', async importOriginal => { - const actual = await importOriginal() + const actual = await importOriginal() return { ...actual, window: { ...actual.window, showInputBox: vi.fn() }, } }) -const EXAMPLE_TOKEN = 'sktsec_example_existing_token' +const EXAMPLE_TOKEN = 'sktsec_test_token' const exampleOrganizations: OrganizationsRecord = { organizations: new Map([ [ 'example-org', { id: 'example-org', + slug: 'example-org', image: undefined, name: 'Example Organization', plan: 'enterprise', @@ -33,7 +55,7 @@ const exampleOrganizations: OrganizationsRecord = { class LifecycleSecretStorage { token: string | undefined = EXAMPLE_TOKEN - readonly changes = new vscode.EventEmitter() + readonly changes = new EventEmitter() readonly onDidChange = this.changes.event readonly get = vi.fn(async () => this.token) readonly store = vi.fn(async (key: string, value: string) => { @@ -48,11 +70,15 @@ class LifecycleSecretStorage { beforeEach(() => { resetStubAuthState() + resetStubConfigurationChanges() + setStubWorkspaceState({ + configuration: { 'socket-security.orgSlug': 'example-org' }, + }) vi.mocked(getOrganizations) .mockReset() .mockResolvedValue(exampleOrganizations) - vi.mocked(vscode.window.showInputBox).mockReset() - vi.spyOn(vscode.workspace.fs, 'stat').mockRejectedValue( + vi.mocked(window.showInputBox).mockReset() + vi.spyOn(workspace.fs, 'stat').mockRejectedValue( Object.assign(new Error('Missing example settings'), { code: 'ENOENT' }), ) }) @@ -63,16 +89,15 @@ afterEach(() => { }) async function activateProvider(secrets: LifecycleSecretStorage) { - let provider: vscode.AuthenticationProvider | undefined - vi.spyOn( - vscode.authentication, - 'registerAuthenticationProvider', - ).mockImplementation((...[, , registered]) => { - provider = registered - return new vscode.Disposable(() => {}) - }) + let provider: AuthenticationProvider | undefined + vi.spyOn(authentication, 'registerAuthenticationProvider').mockImplementation( + (...[, , registered]) => { + provider = registered + return new Disposable(() => {}) + }, + ) await activate( - { secrets, subscriptions: [] } as unknown as vscode.ExtensionContext, + { secrets, subscriptions: [] } as unknown as ExtensionContext, [], ) if (!provider) { @@ -100,9 +125,10 @@ describe('authentication lifecycle', () => { lookup.resolve({ organizations: new Map([ [ - 'example-updated-org', + 'example-org', { id: 'example-updated-org', + slug: 'example-org', image: undefined, name: 'Updated Example Organization', plan: 'free', @@ -147,6 +173,100 @@ describe('authentication lifecycle', () => { expect(changes).not.toHaveBeenCalled() }) + test('keeps token-only legacy sessions when no organization is configured', async () => { + setStubWorkspaceState({ configuration: {} }) + const provider = await activateProvider(new LifecycleSecretStorage()) + + const [session] = await provider.getSessions(undefined, {}) + + expect(session?.accessToken).toBe(EXAMPLE_TOKEN) + expect(session?.account).toEqual({ + id: 'socket-token', + label: 'Socket API token', + }) + setStubGetSessionResult(() => + Promise.resolve({ accessToken: EXAMPLE_TOKEN }), + ) + await expect(getAuthenticatedContext()).resolves.toBeUndefined() + }) + + test('refreshes provider account details when the configured org changes', async () => { + const secrets = new LifecycleSecretStorage() + const provider = await activateProvider(secrets) + const [session] = await provider.getSessions(undefined, {}) + const changes = vi.fn() + provider.onDidChangeSessions(changes) + setStubWorkspaceState({ + configuration: { 'socket-security.orgSlug': 'missing-org' }, + }) + fireStubConfigurationChange('socket-security.orgSlug') + await vi.waitFor(async () => { + expect((await provider.getSessions(undefined, {}))[0]?.account).toEqual({ + id: 'socket-token', + label: 'Socket API token', + }) + }) + + expect(changes).toHaveBeenCalledWith({ + added: [], + changed: [ + expect.objectContaining({ + account: { id: 'socket-token', label: 'Socket API token' }, + }), + ], + removed: [], + }) + expect(session).toBeDefined() + }) + + test('rejects an organization lookup after the credential changes', async () => { + const secrets = new LifecycleSecretStorage() + await activateProvider(secrets) + setStubGetSessionResult(() => + Promise.resolve({ accessToken: EXAMPLE_TOKEN }), + ) + const lookup = Promise.withResolvers() + vi.mocked(getOrganizations).mockImplementationOnce(() => lookup.promise) + + const context = getAuthenticatedContext() + await vi.waitFor(() => { + expect(getOrganizations).toHaveBeenCalled() + }) + secrets.changes.fire({ key: API_TOKEN_SECRET_KEY }) + lookup.resolve(exampleOrganizations) + + await expect(context).resolves.toBeUndefined() + }) + + test('hides the previous credential until a replacement sync finishes', async () => { + const secrets = new LifecycleSecretStorage() + await activateProvider(secrets) + setStubGetSessionResult(() => + Promise.resolve({ accessToken: EXAMPLE_TOKEN }), + ) + const replacementLookup = Promise.withResolvers< + OrganizationsRecord | undefined + >() + const started = Promise.withResolvers() + vi.mocked(getOrganizations).mockImplementationOnce(() => { + started.resolve() + return replacementLookup.promise + }) + + secrets.changes.fire({ key: API_TOKEN_SECRET_KEY }) + await started.promise + + await expect(getAuthenticatedContext()).resolves.toBeUndefined() + replacementLookup.resolve(exampleOrganizations) + await replacementLookup.promise + await vi.waitFor(async () => { + expect(await getAuthenticatedContext()).toEqual({ + accessToken: EXAMPLE_TOKEN, + organization: exampleOrganizations.organizations.get('example-org'), + }) + }) + }) + test('keeps the current session when a stale session is removed', async () => { const secrets = new LifecycleSecretStorage() const provider = await activateProvider(secrets) @@ -179,15 +299,16 @@ describe('authentication lifecycle', () => { }) test('validates the submitted token independently of input validation', async () => { + setStubWorkspaceState({ configuration: {} }) const secrets = new LifecycleSecretStorage() const provider = await activateProvider(secrets) const sessions = await provider.getSessions(undefined, {}) vi.mocked(getOrganizations).mockImplementation(async token => token === EXAMPLE_TOKEN ? exampleOrganizations : undefined, ) - vi.mocked(vscode.window.showInputBox).mockImplementation(async options => { + vi.mocked(window.showInputBox).mockImplementation(async options => { await options?.validateInput?.(EXAMPLE_TOKEN) - return 'sktsec_example_submitted_token' + return 'example_submitted_token' }) await expect(provider.createSession([], {})).rejects.toBeInstanceOf(Error) @@ -196,6 +317,40 @@ describe('authentication lifecycle', () => { expect(await provider.getSessions(undefined, {})).toEqual(sessions) }) + test('waits for the store-triggered session sync before completing login', async () => { + const secrets = new LifecycleSecretStorage() + const provider = await activateProvider(secrets) + const token = 'example_new_token' + const syncLookup = Promise.withResolvers() + const syncStarted = Promise.withResolvers() + let lookupCount = 0 + vi.mocked(getOrganizations).mockImplementation(async requestedToken => { + if (requestedToken !== token) { + return undefined + } + lookupCount += 1 + if (lookupCount === 1) { + return exampleOrganizations + } + syncStarted.resolve() + return syncLookup.promise + }) + vi.mocked(window.showInputBox).mockResolvedValue(token) + + const login = provider.createSession([], {}) + await syncStarted.promise + + expect(getAuthContextState().ready).toBe(false) + await expect(getAPIKey()).resolves.toBeUndefined() + + syncLookup.resolve(exampleOrganizations) + const session = await login + + expect(getAuthContextState().ready).toBe(true) + expect(session.accessToken).toBe(token) + expect((await provider.getSessions(undefined, {}))[0]).toBe(session) + }) + test('removes a session when its token has no organizations', async () => { const secrets = new LifecycleSecretStorage() const provider = await activateProvider(secrets) @@ -233,5 +388,6 @@ describe('authentication lifecycle', () => { expect(secrets.token).toBeUndefined() expect(await provider.getSessions(undefined, {})).toEqual([]) + expect(getAuthContextState().ready).toBe(true) }) }) diff --git a/test/repo/unit/auth.test.mts b/test/repo/unit/auth.test.mts index 8eedab8e..2dea25c2 100644 --- a/test/repo/unit/auth.test.mts +++ b/test/repo/unit/auth.test.mts @@ -161,6 +161,7 @@ describe('legacy token migration', () => { describe('session identifiers', () => { const org: OrgInfo = { id: 'org-1', + slug: 'acme', image: undefined, name: 'Acme', plan: 'enterprise', diff --git a/test/repo/unit/organization-selection.test.mts b/test/repo/unit/organization-selection.test.mts new file mode 100644 index 00000000..eb45c912 --- /dev/null +++ b/test/repo/unit/organization-selection.test.mts @@ -0,0 +1,60 @@ +import { describe, expect, test } from 'vitest' + +import { selectOrganization } from '../../../src/organization-selection.mts' +import type { OrgInfo } from '../../../src/api.mts' + +const organization: OrgInfo = { + id: 'org-id', + slug: 'acme', + name: 'Acme', + image: undefined, + plan: 'enterprise', +} + +describe('selectOrganization', () => { + test('requires an explicit slug', () => { + expect( + selectOrganization(undefined, new Map([['org-id', organization]])), + ).toEqual({ status: 'missing' }) + expect(selectOrganization('', new Map([['org-id', organization]]))).toEqual( + { status: 'missing' }, + ) + expect( + selectOrganization(' ', new Map([['org-id', organization]])), + ).toEqual({ status: 'invalid' }) + }) + + test('selects only an exact accessible slug', () => { + const organizations = new Map([['org-id', organization]]) + expect(selectOrganization('acme', organizations)).toEqual({ + status: 'selected', + organization, + }) + expect(selectOrganization('org-id', organizations)).toEqual({ + status: 'inaccessible', + slug: 'org-id', + }) + expect(selectOrganization('Acme', organizations)).toEqual({ + status: 'inaccessible', + slug: 'Acme', + }) + }) + + test('reports unavailable, inaccessible, and ambiguous choices', () => { + expect(selectOrganization('acme', undefined)).toEqual({ + status: 'unavailable', + }) + expect( + selectOrganization('other', new Map([['org-id', organization]])), + ).toEqual({ status: 'inaccessible', slug: 'other' }) + expect( + selectOrganization( + 'acme', + new Map([ + ['org-id', organization], + ['org-id-2', { ...organization, id: 'org-id-2' }], + ]), + ), + ).toEqual({ status: 'ambiguous', slug: 'acme' }) + }) +}) diff --git a/test/repo/unit/ui/purl-alerts-and-scores/manager-cache-requests.test.mts b/test/repo/unit/ui/purl-alerts-and-scores/manager-cache-requests.test.mts index 4b3d5daf..ab5cf5e1 100644 --- a/test/repo/unit/ui/purl-alerts-and-scores/manager-cache-requests.test.mts +++ b/test/repo/unit/ui/purl-alerts-and-scores/manager-cache-requests.test.mts @@ -263,4 +263,75 @@ describe('PURLDataCache request lifecycle', () => { await flushRequests() expect(entry.pkgData).toEqual(packageScore(purl)) }) + + test('notifies live entries and keeps them bound during context reset', async () => { + const purl = 'pkg:npm/example-context-reset@1.0.0' + const entry = cache.watch(purl) + await flushRequests() + const watcher = vi.fn() + entry.subscribe(watcher) + + cache.clear() + + expect(entry.pkgData).toBeUndefined() + expect(entry.isStale()).toBe(true) + expect(watcher).toHaveBeenCalledTimes(1) + await flushRequests() + expect(entry.pkgData).toEqual(packageScore(purl)) + }) + + test('does not let an old queue drain work from a new generation', async () => { + const firstPurl = 'pkg:npm/example-old-generation@1.0.0' + const secondPurl = 'pkg:npm/example-new-generation@1.0.0' + cache.watch(firstPurl) + cache.clear() + cache.watch(secondPurl) + await flushRequests() + + expect(streamPackageScores).toHaveBeenCalledTimes(1) + const requestedPurls = streamPackageScores.mock.calls[0]?.[1] + expect(requestedPurls).toContain(firstPurl) + expect(requestedPurls).toContain(secondPurl) + expect(streamPackageScores.mock.calls[0]?.[2]?.signal?.aborted).toBe(false) + }) + + test('holds active PURLs until the authentication context is ready', async () => { + const purl = 'pkg:npm/example-auth-pending@1.0.0' + const entry = cache.watch(purl) + await flushRequests() + streamPackageScores.mockClear() + + cache.clear(false) + cache.watch(purl) + await flushRequests() + expect(streamPackageScores).not.toHaveBeenCalled() + + cache.resume() + await flushRequests() + + expect(streamPackageScores).toHaveBeenCalledTimes(1) + expect(streamPackageScores.mock.calls[0]?.[1]).toContain(purl) + expect(entry.pkgData).toEqual(packageScore(purl)) + }) + + test('ignores a held response from the invalidated credential', async () => { + const oldResponse = Promise.withResolvers() + streamPackageScores.mockImplementationOnce(async function* () { + yield await oldResponse.promise + }) + const purl = 'pkg:npm/example-invalidated-credential@1.0.0' + const entry = cache.watch(purl) + await flushRequests() + + cache.clear(false) + cache.resume() + await flushRequests() + expect(entry.pkgData).toEqual(packageScore(purl)) + + oldResponse.resolve(packageScore(purl, 1)) + await flushRequests() + + expect(entry.pkgData).toEqual(packageScore(purl)) + expect(entry.pkgData?.score.overall).toBe(90) + }) }) diff --git a/test/stubs/vscode.mts b/test/stubs/vscode.mts index 28a4707e..02028552 100644 --- a/test/stubs/vscode.mts +++ b/test/stubs/vscode.mts @@ -25,6 +25,20 @@ const state: StubWorkspaceState = { isTrusted: true, workspaceFolders: undefined, } +let configurationChanges: EventEmitter<{ + affectsConfiguration(section: string): boolean +}> + +export function fireStubConfigurationChange(section: string): void { + configurationChanges.fire({ + affectsConfiguration: candidate => candidate === section, + }) +} + +export function resetStubConfigurationChanges(): void { + configurationChanges.dispose() + configurationChanges = new EventEmitter() +} export function setStubWorkspaceState(next: Partial): void { state.configuration = next.configuration ?? {} @@ -155,6 +169,8 @@ export class EventEmitter { } } +configurationChanges = new EventEmitter() + // oxlint-disable-next-line socket/const-enum-shape -- VS Code API export const ConfigurationTarget = { // oxlint-disable-next-line socket/const-enum-shape -- VS Code API @@ -213,6 +229,9 @@ export const workspace = { get isTrusted(): boolean { return state.isTrusted }, + get onDidChangeConfiguration() { + return configurationChanges.event + }, onDidGrantWorkspaceTrust(_listener: () => void): Disposable { return new Disposable(() => {}) },