Skip to content

Commit 4fea821

Browse files
committed
fix: properly distinguish auth and internal userId
1 parent 12470bc commit 4fea821

File tree

5 files changed

+38
-17
lines changed

5 files changed

+38
-17
lines changed

packages/agent-api/src/auth.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { HttpRequest } from '@azure/functions';
22
import { DefaultAzureCredential, getBearerTokenProvider } from '@azure/identity';
3+
import { UserDbService } from './user-db-service';
34

45
const azureOpenAiScope = 'https://cognitiveservices.azure.com/.default';
56

@@ -17,18 +18,31 @@ export function getAzureOpenAiTokenProvider() {
1718
return getBearerTokenProvider(getCredentials(), azureOpenAiScope);
1819
}
1920

20-
export function getUserId(request: HttpRequest, body?: any): string | undefined {
21+
export function getAuthenticationUserId(request: HttpRequest, body?: any): string | undefined {
2122
let userId: string | undefined;
2223

23-
// Get the user ID from Azure easy auth if it's available
24+
// Get the user ID from Azure easy auth
2425
try {
2526
const token = Buffer.from(request.headers.get('x-ms-client-principal') ?? '', 'base64').toString('ascii');
2627
const infos = token && JSON.parse(token);
2728
userId = infos?.userId;
2829
} catch {}
2930

30-
// Get the user ID from the request as a fallback
31-
userId ??= body?.context?.userId ?? request.query.get('userId') ?? undefined;
32-
3331
return userId;
3432
}
33+
34+
export async function getInternalUserId(request: HttpRequest, body?: any): Promise<string | undefined> {
35+
// Get the user ID from Azure easy auth if it's available,
36+
let authUserId = getAuthenticationUserId(request, body);
37+
if (authUserId) {
38+
// Exchange the auth user ID to the internal user ID
39+
const db = await UserDbService.getInstance();
40+
let user = await db.getUserById(authUserId);
41+
if (user) {
42+
return user.id;
43+
}
44+
}
45+
46+
// Get the user ID from the request as a fallback
47+
return body?.context?.userId ?? request.query.get('userId') ?? undefined;
48+
}

packages/agent-api/src/functions/chats-delete.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import process from 'node:process';
22
import { HttpRequest, HttpResponseInit, InvocationContext, app } from '@azure/functions';
33
import { AzureCosmsosDBNoSQLChatMessageHistory } from '@langchain/azure-cosmosdb';
4-
import { getCredentials, getUserId } from '../auth.js';
4+
import { getCredentials, getInternalUserId } from '../auth.js';
55

66
async function deleteChats(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
77
const azureCosmosDbEndpoint = process.env.AZURE_COSMOSDB_NOSQL_ENDPOINT;
88
const { sessionId } = request.params;
9-
const userId = getUserId(request);
9+
const userId = await getInternalUserId(request);
1010

1111
if (!userId) {
1212
return {

packages/agent-api/src/functions/chats-get.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import process from 'node:process';
22
import { HttpRequest, HttpResponseInit, InvocationContext, app } from '@azure/functions';
33
import { AzureCosmsosDBNoSQLChatMessageHistory } from '@langchain/azure-cosmosdb';
4-
import { getCredentials, getUserId } from '../auth.js';
4+
import { getCredentials, getInternalUserId } from '../auth.js';
55

66
async function getChats(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
77
const azureCosmosDbEndpoint = process.env.AZURE_COSMOSDB_NOSQL_ENDPOINT;
88
const { sessionId } = request.params;
9-
const userId = getUserId(request);
9+
const userId = await getInternalUserId(request);
1010

1111
if (!userId) {
1212
return {

packages/agent-api/src/functions/chats-post.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { createToolCallingAgent } from 'langchain/agents';
1111
import { AgentExecutor } from 'langchain/agents';
1212
import { loadMcpTools } from '@langchain/mcp-adapters';
1313
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
14-
import { getAzureOpenAiTokenProvider, getCredentials, getUserId } from '../auth.js';
14+
import { getAzureOpenAiTokenProvider, getCredentials, getInternalUserId } from '../auth.js';
1515
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
1616
import { ChainValues } from '@langchain/core/utils/types.js';
1717

@@ -50,16 +50,23 @@ export async function postChats(request: HttpRequest, context: InvocationContext
5050
const requestBody = (await request.json()) as AIChatCompletionRequest;
5151
const { messages, context: chatContext } = requestBody;
5252

53-
// Wrong userID!!! need to exchange the one from the token to the me-get
54-
const userId = getUserId(request, requestBody);
53+
const userId = await getInternalUserId(request, requestBody);
54+
if (!userId) {
55+
return {
56+
status: 400,
57+
jsonBody: {
58+
error: 'Invalid or missing userId in the request',
59+
},
60+
}
61+
}
5562

5663
if (!messages || messages.length === 0 || !messages.at(-1)?.content) {
5764
return {
5865
status: 400,
5966
jsonBody: {
6067
error: 'Invalid or missing messages in the request body',
6168
},
62-
}
69+
};
6370
}
6471

6572
let model: BaseChatModel;

packages/agent-api/src/functions/me-get.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
import { createHash } from 'node:crypto';
22
import { app, type HttpRequest, type InvocationContext } from '@azure/functions';
33
import { UserDbService } from '../user-db-service.js';
4-
import { getUserId } from '../auth.js';
4+
import { getAuthenticationUserId } from '../auth.js';
55

66
app.http('me-get', {
77
methods: ['GET'],
88
authLevel: 'anonymous',
99
route: 'me',
1010
async handler(request: HttpRequest, context: InvocationContext) {
1111
try {
12-
const rawUserId = getUserId(request);
13-
if (!rawUserId) {
12+
const authenticationUserId = getAuthenticationUserId(request);
13+
if (!authenticationUserId) {
1414
return {
1515
status: 401,
1616
jsonBody: { error: 'Unauthorized' },
1717
};
1818
}
1919

20-
const id = createHash('sha256').update(rawUserId).digest('hex').substring(0, 32);
20+
const id = createHash('sha256').update(authenticationUserId).digest('hex').substring(0, 32);
2121
context.log(`User ID ${id}`);
2222

2323
const db = await UserDbService.getInstance();

0 commit comments

Comments
 (0)