|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +import express from "express"; |
| 5 | +import type { Express } from "express-serve-static-core"; |
| 6 | +import { DefaultAzureCredential, type TokenCredential } from "@azure/identity"; |
| 7 | +import { randomUUID } from "node:crypto"; |
| 8 | +import { createPrinter } from "./printer"; |
| 9 | + |
| 10 | +const printer = createPrinter("browser-relay"); |
| 11 | + |
| 12 | +export interface TestCredentialServerOptions { |
| 13 | + /** |
| 14 | + * Port to listen on. Defaults to 4895. |
| 15 | + */ |
| 16 | + port?: number; |
| 17 | + |
| 18 | + /** |
| 19 | + * Host to listen on. Defaults to `localhost`. Caution: do not expose this server to the network. |
| 20 | + */ |
| 21 | + listenHost?: string; |
| 22 | +} |
| 23 | + |
| 24 | +function isValidScopes(scopes: unknown): scopes is string | string[] { |
| 25 | + return ( |
| 26 | + typeof scopes === "string" || |
| 27 | + (Array.isArray(scopes) && scopes.every((s) => typeof s === "string")) |
| 28 | + ); |
| 29 | +} |
| 30 | + |
| 31 | +function buildServer(app: Express) { |
| 32 | + const credentials: Record<string, TokenCredential> = {}; |
| 33 | + |
| 34 | + app.use(express.json()); |
| 35 | + app.use((_req, res, next) => { |
| 36 | + res.set("Access-Control-Allow-Methods", "GET, PUT"); |
| 37 | + res.set("Access-Control-Allow-Origin", "*"); |
| 38 | + next(); |
| 39 | + }); |
| 40 | + |
| 41 | + app.get("/health", (_req, res) => { |
| 42 | + res.status(204).send(); |
| 43 | + }); |
| 44 | + |
| 45 | + // Endpoint for creating a new credential |
| 46 | + app.put("/credential", (req, res) => { |
| 47 | + const id = randomUUID(); |
| 48 | + try { |
| 49 | + const cred = new DefaultAzureCredential(req.body); |
| 50 | + credentials[id] = cred; |
| 51 | + res.status(201).send({ id }); |
| 52 | + } catch (error: unknown) { |
| 53 | + res.status(400).send({ error }); |
| 54 | + return; |
| 55 | + } |
| 56 | + }); |
| 57 | + |
| 58 | + // Endpoint for getting a token using a pre-created credential |
| 59 | + app.get("/credential/:id/token", async (req, res) => { |
| 60 | + const credential = credentials[req.params.id]; |
| 61 | + if (!credential) { |
| 62 | + res.status(404).send({ error: "Credential not found, create a credential first" }); |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + const scopes = req.query["scopes"]; |
| 67 | + |
| 68 | + if (!isValidScopes(scopes)) { |
| 69 | + res.status(400).send({ error: "Scopes must be provided" }); |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + const options = JSON.parse(req.query["options"]?.toString() ?? "{}"); |
| 74 | + |
| 75 | + try { |
| 76 | + const token = await credential.getToken(scopes, options); |
| 77 | + res.status(200).send(token); |
| 78 | + } catch (error: unknown) { |
| 79 | + res.status(400).send({ error }); |
| 80 | + } |
| 81 | + }); |
| 82 | +} |
| 83 | + |
| 84 | +async function isRelayAlive(options: TestCredentialServerOptions = {}): Promise<boolean> { |
| 85 | + try { |
| 86 | + const res = await fetch( |
| 87 | + `http://${options.listenHost ?? "localhost"}:${options.port ?? 4895}/health`, |
| 88 | + ); |
| 89 | + |
| 90 | + if (res.ok) { |
| 91 | + printer("Browser relay is already alive"); |
| 92 | + return true; |
| 93 | + } else { |
| 94 | + throw new Error(`Browser relay responded with an error: ${await res.text()}`); |
| 95 | + } |
| 96 | + } catch (e) { |
| 97 | + printer("Browser relay is not yet alive"); |
| 98 | + return false; |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +export async function shouldStartRelay( |
| 103 | + options: TestCredentialServerOptions = {}, |
| 104 | +): Promise<boolean> { |
| 105 | + const testMode = (process.env.TEST_MODE ?? "playback").toLowerCase(); |
| 106 | + if (testMode !== "record" && testMode !== "live") { |
| 107 | + printer("Not in record or live mode; not starting relay"); |
| 108 | + return false; |
| 109 | + } |
| 110 | + |
| 111 | + return !(await isRelayAlive(options)); |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Create and start the relay server used by test credential to provide credentials to the browser tests. |
| 116 | + * @param options Options for the relay server. |
| 117 | + * @returns A callback which, when called, will stop the server. |
| 118 | + */ |
| 119 | +export function startRelayServer(options: TestCredentialServerOptions = {}): () => void { |
| 120 | + const app = express(); |
| 121 | + buildServer(app); |
| 122 | + |
| 123 | + const { listenHost = "localhost", port = 4895 } = options; |
| 124 | + |
| 125 | + printer(`Starting browser relay on http://${listenHost}:${port}/`); |
| 126 | + const server = app.listen(port, listenHost); |
| 127 | + return () => server.close(); |
| 128 | +} |
0 commit comments