Skip to content

Commit

Permalink
(DOCSP-32596): Set up CORS on the server (#103)
Browse files Browse the repository at this point in the history
* draft CORS setup

* add tests
  • Loading branch information
mongodben authored Aug 24, 2023
1 parent 5f0ea11 commit 76c9530
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 1 deletion.
2 changes: 2 additions & 0 deletions chat-server/environments/production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ env:
MONGODB_DATABASE_NAME: docs-chatbot-prod
VECTOR_SEARCH_INDEX_NAME: default
OPENAI_CHAT_COMPLETION_MODEL_VERSION: 2023-06-01-preview
ALLOWED_ORIGINS: https://mongodb.com,https://www.mongodb.com
NODE_ENV: production


envSecrets:
MONGODB_CONNECTION_URI: docs-chatbot-prod
OPENAI_ENDPOINT: docs-chatbot-prod
Expand Down
1 change: 1 addition & 0 deletions chat-server/environments/staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ env:
MONGODB_DATABASE_NAME: docs-chatbot-staging
VECTOR_SEARCH_INDEX_NAME: default
OPENAI_CHAT_COMPLETION_MODEL_VERSION: 2023-06-01-preview
ALLOWED_ORIGINS: https://knowledge.staging.corp.mongodb.com
NODE_ENV: staging

envSecrets:
Expand Down
2 changes: 2 additions & 0 deletions chat-server/src/AppConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
FindNearestNeighborsOptions,
} from "chat-core";
import { QueryPreprocessorFunc } from "./processors/QueryPreprocessorFunc";
import { CorsOptions } from "cors";

export type EmbedConfig = MakeOpenAiEmbedFuncArgs;

Expand Down Expand Up @@ -41,4 +42,5 @@ export interface AppConfig {
mongodb: MongoDbConfig;
embed: EmbedConfig;
maxRequestTimeoutMs?: number;
corsOptions?: CorsOptions;
}
30 changes: 30 additions & 0 deletions chat-server/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { makeDataStreamer } from "./services/dataStreamer";
import { makeOpenAiLlm } from "./services/llm";
import { config } from "./config";

const ipAddress = "127.0.0.1";

describe("App", () => {
// Create instances of services
const mongodb = new MongoDB(
Expand Down Expand Up @@ -46,6 +48,9 @@ describe("App", () => {
k: 3,
minScore: 0.9,
},
corsOptions: {
origin: ["http://localhost:3000", "http://example.com"],
},
});
});

Expand Down Expand Up @@ -96,4 +101,29 @@ describe("App", () => {
});
});
});
describe("CORS handling", () => {
const ipAddress = "";
test("should include the correct CORS headers", async () => {
const res = await request(app)
.post("/api/v1/conversations/")
.set("Origin", "http://example.com")
.set("X-FORWARDED-FOR", ipAddress);

expect(res.header["access-control-allow-origin"]).toBe(
"http://example.com"
);
expect(res.status).toBe(200);
});

test("should not allow unauthorized origin", async () => {
const res = await request(app)
.post("/api/v1/conversations")
.set("Origin", "http://unauthorized.com")
.set("X-FORWARDED-FOR", ipAddress)
.send();

expect(res.header["Access-Control-Allow-Origin"]).toBeUndefined();
expect(res.status).toBe(200);
});
});
});
4 changes: 3 additions & 1 deletion chat-server/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export const makeApp = async ({
findNearestNeighborsOptions,
searchBoosters,
userQueryPreprocessor,
corsOptions,
}: {
embed: EmbedFunc;
store: EmbeddedContentStore;
Expand All @@ -99,11 +100,12 @@ export const makeApp = async ({
findNearestNeighborsOptions?: Partial<FindNearestNeighborsOptions>;
searchBoosters?: SearchBooster[];
userQueryPreprocessor?: QueryPreprocessorFunc;
corsOptions?: cors.CorsOptions;
}): Promise<Express> => {
const app = express();
app.use(makeHandleTimeoutMiddleware(maxRequestTimeoutMs));
app.set("trust proxy", true);
app.use(cors()); // TODO: add specific options to only allow certain origins
app.use(cors(corsOptions));
app.use(express.json());
app.use(reqHandler);
const { NODE_ENV } = process.env;
Expand Down
5 changes: 5 additions & 0 deletions chat-server/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const {
OPENAI_CHAT_COMPLETION_DEPLOYMENT,
} = assertEnvVars(CORE_ENV_VARS);

const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [];

/**
Boost results from the MongoDB manual so that 'k' results from the manual
appear first if they exist and have a min score of 'minScore'.
Expand Down Expand Up @@ -133,4 +135,7 @@ export const config: AppConfig = {
vectorSearchIndexName: VECTOR_SEARCH_INDEX_NAME,
},
maxRequestTimeoutMs: 30000,
corsOptions: {
origin: allowedOrigins,
},
};
1 change: 1 addition & 0 deletions chat-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const startServer = async () => {
searchBoosters: config.conversations?.searchBoosters,
userQueryPreprocessor: config.conversations?.userQueryPreprocessor,
maxRequestTimeoutMs: config.maxRequestTimeoutMs,
corsOptions: config.corsOptions,
});

const server = app.listen(PORT, () => {
Expand Down

0 comments on commit 76c9530

Please sign in to comment.