Skip to content

Commit d6b10aa

Browse files
committed
fix(knowledge): classify saved AWS credential failures and labels consistently
- Share the AWS failure message and transient check with the AWS tools, so STS throttling or an IdP outage during setup is no longer a 400. - Refuse another service's credential on S3 creation, as access updates do. - Return an empty access token for a saved AWS credential, not its id. - Record saved-credential connectors as authMode savedCredential in audit. - Narrow savedCredential.provider to aws, the only provider that resolves. - Derive create's key-vs-credential choice from connectorUsesCredential and rename the run-token refresh.
1 parent 61a6a6c commit d6b10aa

10 files changed

Lines changed: 182 additions & 52 deletions

File tree

‎apps/sim/connectors/auth.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ export function getConnectorCredentialService(auth: ConnectorAuthConfig): OAuthS
3636
*
3737
* An OAuth connector uses its credential unless it also takes a token and the row stores
3838
* only that. A key connector uses a credential only when it declares a `savedCredential`
39-
* alternative and the row names one, so a row that stores a key keeps using it.
39+
* alternative and the row names one; creation and access updates never bind a credential to
40+
* a row that stores a key, so such a row keeps using its key.
4041
*/
4142
export function connectorUsesCredential(
4243
auth: ConnectorAuthConfig,
@@ -46,6 +47,15 @@ export function connectorUsesCredential(
4647
return !(auth.apiKey && !connector.credentialId && connector.encryptedApiKey)
4748
}
4849

50+
/** How a connector row authenticates, as recorded in audit metadata. */
51+
export function connectorAuthModeLabel(
52+
authMode: ConnectorAuthConfig['mode'],
53+
usesCredential: boolean
54+
): 'apiKey' | 'oauth' | 'savedCredential' {
55+
if (!usesCredential) return 'apiKey'
56+
return authMode === 'apiKey' ? 'savedCredential' : 'oauth'
57+
}
58+
4959
/**
5060
* Whether a workspace-mode connector row still carries something to authenticate with. A
5161
* connector whose credential was removed keeps its documents but has no token source, so a

‎apps/sim/connectors/types.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,10 @@ export type ConnectorAuthConfig =
6666
* connector row with a stored key keeps using it, and one that names a
6767
* credential resolves it for the knowledge base's own scope. Fields
6868
* marked {@link ConnectorConfigField.apiKeyOnly} describe the key and
69-
* do not apply to a credential.
69+
* do not apply to a credential. Only AWS resolves to signing keys today;
70+
* another provider needs its own resolution in the connector access token.
7071
*/
71-
savedCredential?: { provider: OAuthService; label: string }
72+
savedCredential?: { provider: 'aws'; label: string }
7273
}
7374

7475
/** A group in an external directory, named as the connector's ACLs name it. */

‎apps/sim/lib/internal/aws/credentials.ts‎

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import { AsyncLocalStorage } from 'node:async_hooks'
2-
import { getErrorMessage } from '@sim/utils/errors'
32
import { isRecordLike } from '@sim/utils/object'
4-
import { isRetryableNetworkError } from '@/lib/core/errors/retryable-infrastructure'
53
import { awsRequestHandler } from '@/lib/core/network/proxy-agent.server'
64
import {
75
type AwsSessionCredentials,
86
buildAwsRoleSessionName,
97
getAwsCredentialConfig,
108
resolveAwsSessionCredentials,
119
} from '@/lib/credentials/aws-service-account.server'
10+
import { awsCredentialFailureMessage, isTransientAwsFailure } from '@/lib/internal/aws/failure'
1211
import type {
1312
InternalToolOperationCall,
1413
InternalToolOperationHandler,
@@ -112,27 +111,6 @@ export async function resolveAuthorizedAwsCredential(
112111
})
113112
}
114113

115-
const THROTTLING_ERROR_NAMES = new Set(['Throttling', 'ThrottlingException'])
116-
117-
/**
118-
* Whether resolving a credential failed because AWS was briefly unavailable rather
119-
* than because it denied the credential: an error STS models as retryable
120-
* (IDPCommunicationError, when STS could not reach Sim's OIDC issuer), throttling,
121-
* an STS 5xx, or a network failure. The SDK has already retried these.
122-
*/
123-
function isTransientAwsFailure(error: unknown): boolean {
124-
if (!isRecordLike(error)) return false
125-
const status = isRecordLike(error.$metadata) ? error.$metadata.httpStatusCode : undefined
126-
return (
127-
error.$retryable !== undefined ||
128-
THROTTLING_ERROR_NAMES.has(String(error.name)) ||
129-
status === 429 ||
130-
(typeof status === 'number' && status >= 500) ||
131-
error.name === 'TimeoutError' ||
132-
isRetryableNetworkError(error)
133-
)
134-
}
135-
136114
/** Wraps a family's operation handler so it also accepts a saved AWS credential. */
137115
export function withAwsCredential<Result>(
138116
handler: InternalToolOperationHandler<Result>
@@ -152,7 +130,7 @@ export function withAwsCredential<Result>(
152130
} catch (error) {
153131
request.signal?.throwIfAborted()
154132
return Response.json(
155-
{ error: `Could not use the AWS credential: ${getErrorMessage(error, 'Unknown error')}` },
133+
{ error: awsCredentialFailureMessage(error) },
156134
{ status: isTransientAwsFailure(error) ? 503 : 403 }
157135
)
158136
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { getErrorMessage } from '@sim/utils/errors'
2+
import { isRecordLike } from '@sim/utils/object'
3+
import { isRetryableNetworkError } from '@/lib/core/errors/retryable-infrastructure'
4+
5+
const THROTTLING_ERROR_NAMES = new Set(['Throttling', 'ThrottlingException'])
6+
7+
/**
8+
* Whether resolving a saved AWS credential failed because AWS was briefly unavailable rather
9+
* than because it denied the credential: an error STS models as retryable
10+
* (IDPCommunicationError, when STS could not reach Sim's OIDC issuer), throttling, an STS 5xx,
11+
* or a network failure. The SDK has already retried these.
12+
*/
13+
export function isTransientAwsFailure(error: unknown): boolean {
14+
if (!isRecordLike(error)) return false
15+
const status = isRecordLike(error.$metadata) ? error.$metadata.httpStatusCode : undefined
16+
return (
17+
error.$retryable !== undefined ||
18+
THROTTLING_ERROR_NAMES.has(String(error.name)) ||
19+
status === 429 ||
20+
(typeof status === 'number' && status >= 500) ||
21+
error.name === 'TimeoutError' ||
22+
isRetryableNetworkError(error)
23+
)
24+
}
25+
26+
/** The caller-facing reason a saved AWS credential could not be used: the AWS message, never a key. */
27+
export function awsCredentialFailureMessage(error: unknown): string {
28+
return `Could not use the AWS credential: ${getErrorMessage(error, 'Unknown error')}`
29+
}

‎apps/sim/lib/knowledge/application/connectors.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import {
88
credentialsAccessMockFns,
99
} from '@sim/testing/mocks/credentials-access.mock'
1010
import { environmentUtilsMockFns } from '@sim/testing/mocks/environment-utils.mock'
11+
import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/feature-flags.mock'
12+
import {
13+
internalAwsCredentialsMock,
14+
internalAwsCredentialsMockFns,
15+
} from '@sim/testing/mocks/internal-aws-credentials.mock'
1116
import {
1217
knowledgeAccessScopeMock,
1318
knowledgeAccessScopeMockFns,
@@ -71,6 +76,8 @@ vi.mock('@/lib/credentials/application/organization-credentials', () => ({
7176
}))
7277

7378
vi.mock('@/lib/oauth/credential-service', () => authOAuthUtilsMock)
79+
vi.mock('@/lib/internal/aws/credentials', () => internalAwsCredentialsMock)
80+
vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
7481
vi.mock('@/lib/api-key/crypto', () => ({ decryptApiKey: hoisted.decryptApiKey }))
7582

7683
vi.mock('@/lib/permission-groups/resolve.server', () => permissionGroupsResolveMock)
@@ -130,6 +137,7 @@ import { confluenceConnectorMeta } from '@/connectors/confluence/meta'
130137
import { gmailConnectorMeta } from '@/connectors/gmail/meta'
131138
import { googleCalendarConnectorMeta } from '@/connectors/google-calendar/meta'
132139
import { googleDriveConnectorMeta } from '@/connectors/google-drive/meta'
140+
import { s3ConnectorMeta } from '@/connectors/s3/meta'
133141

134142
const mocks = {
135143
...hoisted,
@@ -341,6 +349,43 @@ describe('knowledge connector application use cases', () => {
341349
expect(auditMockFns.mockRecordAudit).not.toHaveBeenCalled()
342350
})
343351

352+
it('refuses another service’s credential for an S3 connector before resolving it', async () => {
353+
featureFlagsMockFns.mockIsFeatureEnabled.mockResolvedValueOnce(true)
354+
mocks.getCredentialActorContext.mockResolvedValueOnce({
355+
credential: {
356+
id: 'credential-1',
357+
workspaceId: 'workspace-b',
358+
providerId: 'google-service-account',
359+
},
360+
member: { role: 'admin' },
361+
hasWorkspaceAccess: true,
362+
canWriteWorkspace: true,
363+
isAdmin: true,
364+
})
365+
mocks.createConnector.mockImplementationOnce(
366+
async (input: { resolveAccessToken: (credentialId: string) => Promise<unknown> }) => {
367+
await input.resolveAccessToken('credential-1')
368+
throw new Error('An ineligible credential reached connector persistence')
369+
}
370+
)
371+
await expect(
372+
createKnowledgeConnector.execute({
373+
principal: patPrincipal,
374+
input: {
375+
knowledgeBaseId: 'knowledge-b',
376+
connectorType: 's3',
377+
credentialId: 'credential-1',
378+
sourceConfig: { region: 'us-east-1', bucket: 'docs' },
379+
syncIntervalMinutes: 1440,
380+
},
381+
})
382+
).rejects.toMatchObject({
383+
code: 'validation',
384+
message: expect.stringContaining('belongs to another service'),
385+
})
386+
expect(internalAwsCredentialsMockFns.mockResolveAuthorizedAwsCredential).not.toHaveBeenCalled()
387+
})
388+
344389
it('rejects a personal Confluence OAuth credential before central token use', async () => {
345390
await expect(
346391
resolveConnectorCredentialAccessToken({
@@ -1022,6 +1067,29 @@ describe('organization connector credential authorization', () => {
10221067
}
10231068
)
10241069

1070+
it.each([
1071+
['refused by AWS', { name: 'AccessDenied' }, 400],
1072+
['throttled by AWS', { name: 'ThrottlingException', $metadata: { httpStatusCode: 400 } }, 500],
1073+
])(
1074+
'projects a saved AWS credential %s with the matching setup status',
1075+
async (_case, failure, status) => {
1076+
mocks.authorizeOrganizationCredentialUse.mockResolvedValueOnce({
1077+
credential: { ...credential, providerId: 'aws' },
1078+
userId: principal.userId,
1079+
})
1080+
internalAwsCredentialsMockFns.mockResolveAuthorizedAwsCredential.mockRejectedValueOnce(
1081+
Object.assign(new Error('AWS said no'), failure)
1082+
)
1083+
const error = await resolveConnectorCredentialAccessToken({
1084+
...input,
1085+
auth: s3ConnectorMeta.auth,
1086+
accessMode: 'workspace',
1087+
sourceConfig: { region: 'us-east-1', bucket: 'docs' },
1088+
}).catch((error: unknown) => error)
1089+
expect(internalOrchestrationErrorPolicy.project(error)?.status ?? 500).toBe(status)
1090+
}
1091+
)
1092+
10251093
it('does not mint a token after the credential creator leaves the organization', async () => {
10261094
mocks.resolveTokenIdentity.mockResolvedValueOnce(null)
10271095
await expect(resolveConnectorCredentialAccessToken(input)).resolves.toBeNull()

‎apps/sim/lib/knowledge/application/connectors.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,12 +115,17 @@ import type {
115115
KnowledgeOperationSource,
116116
KnowledgeOrchestrationResult,
117117
} from '@/lib/knowledge/orchestration/shared'
118-
import { credentialProviderMatchesService, type ServiceProviderIdentity } from '@/lib/oauth'
118+
import {
119+
credentialProviderMatchesService,
120+
getServiceConfigByServiceId,
121+
type ServiceProviderIdentity,
122+
} from '@/lib/oauth'
119123
import { ServiceAccountTokenError } from '@/lib/oauth/credential-service'
120124
import { CAPABILITY_RULES, refuseCapability } from '@/lib/permission-groups/capabilities'
121125
import { resolvePermissionGroupConfig } from '@/lib/permission-groups/config-scope.server'
122126
import { getUserPermissionConfigForOrganization } from '@/lib/permission-groups/resolve.server'
123127
import {
128+
connectorAuthModeLabel,
124129
connectorUsesCredential,
125130
getConnectorApiKeyConfig,
126131
isConnectorCredentialTypeAllowed,
@@ -335,7 +340,7 @@ export async function resolveConnectorCredentialAccessToken(input: {
335340

336341
/** Exposes actionable credential refusals without returning raw provider payloads. */
337342
function rethrowConnectorCredentialError(error: unknown): never {
338-
if (error instanceof ConnectorAwsCredentialError) {
343+
if (error instanceof ConnectorAwsCredentialError && !error.transient) {
339344
throw new OrchestrationError('validation', error.message)
340345
}
341346
if (error instanceof ServiceAccountTokenError && [400, 401, 403].includes(error.statusCode)) {
@@ -750,6 +755,11 @@ async function executeCreateKnowledgeConnector({
750755
throw new OrchestrationError('validation', 'Choose either an OAuth account or an API key')
751756
}
752757
await requireConnectorSavedCredentialSetup(connectorMeta.auth, input.credentialId)
758+
/** A key connector's saved credential must be of its declared service, as on an access update. */
759+
const savedCredentialService =
760+
connectorMeta.auth.mode === 'apiKey' && connectorMeta.auth.savedCredential
761+
? (getServiceConfigByServiceId(connectorMeta.auth.savedCredential.provider) ?? undefined)
762+
: undefined
753763
if (
754764
context.knowledgeBase.isSearchIndex &&
755765
(!connectorMeta.search || !input.accessMode || input.accessMode === 'workspace')
@@ -849,6 +859,7 @@ async function executeCreateKnowledgeConnector({
849859
...owner,
850860
actingUserId,
851861
requestId,
862+
...(savedCredentialService ? { service: savedCredentialService } : {}),
852863
auth: connectorMeta.auth,
853864
accessMode: input.accessMode ?? 'workspace',
854865
sourceConfig,
@@ -899,7 +910,10 @@ export const createKnowledgeConnector = defineAuthorizedKnowledgeUseCase({
899910
knowledgeBaseName: context.knowledgeBase.name,
900911
connectorType: result.connector.connectorType,
901912
syncIntervalMinutes: result.connector.syncIntervalMinutes,
902-
authMode: result.connector.credentialId ? 'oauth' : 'apiKey',
913+
authMode: connectorAuthModeLabel(
914+
getConnectorMeta(result.connector.connectorType)?.auth.mode ?? 'oauth',
915+
Boolean(result.connector.credentialId)
916+
),
903917
accessMode: result.connector.accessMode,
904918
},
905919
},

‎apps/sim/lib/knowledge/connectors/access-token.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ describe('saved AWS credential on a key connector', () => {
159159
internalAwsCredentialsMockFns.mockResolveAuthorizedAwsCredential.mockReset()
160160
})
161161

162-
it('resolves the credential only within the knowledge base scope and seeds its session', async () => {
162+
it('asks for the credential in the knowledge base scope and seeds its session, not a bearer token', async () => {
163163
internalAwsCredentialsMockFns.mockResolveAuthorizedAwsCredential.mockResolvedValueOnce(session)
164164
const organizationScope = { kind: 'organization', organizationId: 'org-1' } as const
165165

@@ -179,6 +179,7 @@ describe('saved AWS credential on a key connector', () => {
179179
expect(context).toMatchObject({ organizationId: 'org-1' })
180180
expect(context.workspaceId).toBeUndefined()
181181
expect(token.expiresAt).toEqual(session.expiration)
182+
expect(token.accessToken).toBe('')
182183
expect(readAwsSession(syncContextForToken(token))).toEqual({
183184
accessKeyId: session.accessKeyId,
184185
secretAccessKey: session.secretAccessKey,
@@ -217,7 +218,28 @@ describe('saved AWS credential on a key connector', () => {
217218
scope: WORKSPACE_SCOPE,
218219
sourceConfig: {},
219220
})
220-
).rejects.toBeInstanceOf(ConnectorAwsCredentialError)
221+
).rejects.toMatchObject({ name: 'ConnectorAwsCredentialError', transient: false })
222+
})
223+
224+
it('marks an AWS outage as transient rather than a refused credential', async () => {
225+
internalAwsCredentialsMockFns.mockResolveAuthorizedAwsCredential.mockRejectedValueOnce(
226+
Object.assign(new Error('Rate exceeded'), {
227+
name: 'ThrottlingException',
228+
$metadata: { httpStatusCode: 400 },
229+
})
230+
)
231+
232+
const failure = await resolveConnectorAccessToken({
233+
auth: s3ConnectorMeta.auth,
234+
connector: credentialConnector('aws-credential'),
235+
userId: 'user-1',
236+
requestId: 'sync-run',
237+
scope: WORKSPACE_SCOPE,
238+
sourceConfig: {},
239+
}).catch((error: unknown) => error)
240+
241+
expect(failure).toBeInstanceOf(ConnectorAwsCredentialError)
242+
expect(failure).toMatchObject({ transient: true })
221243
})
222244
})
223245

‎apps/sim/lib/knowledge/connectors/access-token.ts‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { getErrorMessage } from '@sim/utils/errors'
21
import { isValidEmailSyntax, normalizeEmail } from '@sim/utils/string'
32
import { decryptApiKey } from '@/lib/api-key/crypto'
43
import {
@@ -7,6 +6,7 @@ import {
76
resourceScopeFromOwner,
87
} from '@/lib/core/resource-scope'
98
import { resolveCredentialTokenIdentity } from '@/lib/credentials/access'
9+
import { awsCredentialFailureMessage, isTransientAwsFailure } from '@/lib/internal/aws/failure'
1010
import type { ConnectorAccessMode } from '@/lib/knowledge/connectors/access-modes'
1111
import {
1212
getServiceAccountToken,
@@ -48,8 +48,8 @@ export interface ConnectorAccessToken {
4848
getDelegatedAccessToken?: (subject: string, signal?: AbortSignal) => Promise<string>
4949
/**
5050
* AWS only — the keys a saved AWS credential resolved to for the knowledge
51-
* base's scope. A saved AWS credential has no bearer token; the connector
52-
* signs with these instead.
51+
* base's scope. A saved AWS credential has no bearer token, so `accessToken`
52+
* is empty and the connector signs with these instead.
5353
*/
5454
awsSession?: ConnectorAwsSession
5555
/** When the credential stops working, if it says; a holder may reuse it until shortly before. */
@@ -61,12 +61,16 @@ const AWS_CREDENTIAL_SERVICE = 'aws'
6161

6262
/**
6363
* A saved AWS credential that could not be used: unavailable in this scope,
64-
* or refused by AWS STS. The message is the AWS reason, never a secret.
64+
* refused by AWS STS, or not resolvable while AWS was briefly unavailable
65+
* (`transient`). The message is the AWS reason, never a secret.
6566
*/
6667
export class ConnectorAwsCredentialError extends Error {
67-
constructor(message: string, options?: { cause?: unknown }) {
68-
super(message, options)
68+
readonly transient: boolean
69+
70+
constructor(message: string, options: { cause: unknown; transient: boolean }) {
71+
super(message, { cause: options.cause })
6972
this.name = 'ConnectorAwsCredentialError'
73+
this.transient = options.transient
7074
}
7175
}
7276

@@ -91,13 +95,13 @@ async function resolveConnectorAwsToken(
9195
)
9296
} catch (error) {
9397
signal?.throwIfAborted()
94-
throw new ConnectorAwsCredentialError(
95-
`Could not use the AWS credential: ${getErrorMessage(error, 'Unknown error')}`,
96-
{ cause: error }
97-
)
98+
throw new ConnectorAwsCredentialError(awsCredentialFailureMessage(error), {
99+
cause: error,
100+
transient: isTransientAwsFailure(error),
101+
})
98102
}
99103
return {
100-
accessToken: credentialId,
104+
accessToken: '',
101105
awsSession: {
102106
accessKeyId: session.accessKeyId,
103107
secretAccessKey: session.secretAccessKey,

0 commit comments

Comments
 (0)