Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions packages/worker/src/app/handlers/account-secrets.node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,3 +230,83 @@ test('connect oauth returns direct host approval links for saved token secrets',
}),
)
})

test('connect oauth omits direct host approval links when hosts are already approved', async () => {
mockModule.listSecrets.mockResolvedValueOnce([
{
name: 'teslaAccessToken',
scope: 'user',
description: '',
appId: null,
allowedHosts: [
'auth.tesla.com',
'fleet-api.prd.na.vn.cloud.tesla.com',
'fleet-auth.prd.vn.cloud.tesla.com',
],
allowedCapabilities: [],
createdAt: new Date(0).toISOString(),
updatedAt: new Date(0).toISOString(),
ttlMs: null,
},
{
name: 'teslaRefreshToken',
scope: 'user',
description: '',
appId: null,
allowedHosts: [
'auth.tesla.com',
'fleet-api.prd.na.vn.cloud.tesla.com',
'fleet-auth.prd.vn.cloud.tesla.com',
],
allowedCapabilities: [],
createdAt: new Date(0).toISOString(),
updatedAt: new Date(0).toISOString(),
ttlMs: null,
},
])

const handler = createAccountSecretsApiHandler(createEnv())
const response = await handler.action({
request: new Request('https://example.com/account/secrets.json', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'connect_oauth',
provider: 'Tesla',
tokenUrl: 'https://auth.tesla.com/oauth2/v3/token',
apiBaseUrl: 'https://fleet-api.prd.na.vn.cloud.tesla.com',
flow: 'pkce',
clientIdValueName: 'tesla-client-id',
accessTokenSecretName: 'teslaAccessToken',
refreshTokenSecretName: 'teslaRefreshToken',
allowedHosts: [
'fleet-api.prd.na.vn.cloud.tesla.com',
'fleet-auth.prd.vn.cloud.tesla.com',
],
tokenPayload: {
access_token: 'access-token',
refresh_token: 'refresh-token',
},
}),
}),
params: {},
} as never)

expect(response.status).toBe(200)
const payload = await response.json()
expect(payload).toMatchObject({
ok: true,
accessTokenSaved: true,
refreshTokenSaved: true,
hostApprovalLinks: [],
connectorName: 'Tesla',
})
expect(payload.allowedHosts).toEqual(
expect.arrayContaining([
'auth.tesla.com',
'fleet-api.prd.na.vn.cloud.tesla.com',
'fleet-auth.prd.vn.cloud.tesla.com',
]),
)
expect(mockModule.createSecretHostApprovalToken).not.toHaveBeenCalled()
})
41 changes: 35 additions & 6 deletions packages/worker/src/app/handlers/account-secrets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,16 @@ async function handleConnectOauthAction(input: {
)
}

const approvedHostsBySecretName = new Map(
(
await listSecrets({
env: input.env,
userId: input.user.mcpUser.userId,
scope: 'user',
storageContext: null,
})
).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
)
Comment on lines +318 to +327

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Preload failure can now block the entire OAuth connect flow.

Line 318 runs listSecrets outside the existing fallback try/catch (Line 387+), so a transient read failure now fails connect_oauth before token save/update work runs. This was previously non-blocking behavior for link generation.

Suggested fix
-	const approvedHostsBySecretName = new Map(
-		(
-			await listSecrets({
-				env: input.env,
-				userId: input.user.mcpUser.userId,
-				scope: 'user',
-				storageContext: null,
-			})
-		).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
-	)
+	let approvedHostsBySecretName: Map<string, Set<string>> | undefined
+	try {
+		approvedHostsBySecretName = new Map(
+			(
+				await listSecrets({
+					env: input.env,
+					userId: input.user.mcpUser.userId,
+					scope: 'user',
+					storageContext: null,
+				})
+			).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
+		)
+	} catch (error) {
+		console.error('Failed to preload approved OAuth hosts.', {
+			userId: input.user.mcpUser.userId,
+			error,
+		})
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const approvedHostsBySecretName = new Map(
(
await listSecrets({
env: input.env,
userId: input.user.mcpUser.userId,
scope: 'user',
storageContext: null,
})
).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
)
let approvedHostsBySecretName: Map<string, Set<string>> | undefined
try {
approvedHostsBySecretName = new Map(
(
await listSecrets({
env: input.env,
userId: input.user.mcpUser.userId,
scope: 'user',
storageContext: null,
})
).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
)
} catch (error) {
console.error('Failed to preload approved OAuth hosts.', {
userId: input.user.mcpUser.userId,
error,
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/app/handlers/account-secrets.ts` around lines 318 - 327,
The preloading call to listSecrets that builds approvedHostsBySecretName can
throw and currently runs outside the existing fallback try/catch, which allows
transient failures to block the connect_oauth flow; wrap the listSecrets call in
a try/catch (or move it inside the existing fallback block) and on error log the
failure and fall back to an empty Map for approvedHostsBySecretName so token
save/update and link generation still proceed; refer to the
approvedHostsBySecretName variable and the listSecrets invocation when making
this change.

const accessSaved = await saveSecret({
env: input.env,
userId: input.user.mcpUser.userId,
Expand Down Expand Up @@ -381,6 +391,7 @@ async function handleConnectOauthAction(input: {
userId: input.user.mcpUser.userId,
allowedHosts,
secretNames: approvalSecretNames,
approvedHostsBySecretName,
})
} catch (error) {
console.error('Failed to build OAuth host approval links.', {
Expand All @@ -406,6 +417,7 @@ async function buildConnectOauthHostApprovalLinks(input: {
userId: string
allowedHosts: Array<string>
secretNames: Array<string>
approvedHostsBySecretName?: Map<string, Set<string>>
}) {
const uniqueHosts = Array.from(new Set(input.allowedHosts)).slice(
0,
Expand All @@ -415,13 +427,28 @@ async function buildConnectOauthHostApprovalLinks(input: {
0,
maxConnectOauthApprovalSecrets,
)
const approvedHostsBySecretName =
input.approvedHostsBySecretName ??
new Map(
(
await listSecrets({
env: input.env,
userId: input.userId,
scope: 'user',
storageContext: null,
})
).map((secret) => [secret.name, new Set(secret.allowedHosts)]),
)
const baseUrl = getAppBaseUrl({
env: input.env,
requestUrl: input.request.url,
})
const links = await Promise.all(
uniqueSecretNames.flatMap((secretName) =>
uniqueHosts.map(async (host) => {
if (approvedHostsBySecretName.get(secretName)?.has(host)) {
return null
}
const token = await createSecretHostApprovalToken(input.env, {
userId: input.userId,
name: secretName,
Expand All @@ -444,12 +471,14 @@ async function buildConnectOauthHostApprovalLinks(input: {
}),
),
)
return links.sort((left, right) => {
return (
left.secretName.localeCompare(right.secretName) ||
left.host.localeCompare(right.host)
)
})
return links
.filter((link): link is ConnectOauthHostApprovalLink => link !== null)
.sort((left, right) => {
return (
left.secretName.localeCompare(right.secretName) ||
left.host.localeCompare(right.host)
)
})
}

async function handleOAuthExchangeAction(input: {
Expand Down
Loading