fix(cloud): validate relay URL origins
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
26f36ca992
commit
7b3bc331cc
11 files changed
+144
-26
No files matched your search
@@ -31,4 +31,17 @@ describe("resolveCloudPublicConfig", () => {
|
||||
relayUrl: "https://relay.example.test",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an insecure relay URL", () => {
|
||||
expect(
|
||||
resolveCloudPublicConfig({
|
||||
clerk: { publishableKey: "pk_test_example", jwtTemplate: "t3-relay" },
|
||||
relay: { url: "http://relay.example.test" },
|
||||
}),
|
||||
).toEqual({
|
||||
clerkPublishableKey: "pk_test_example",
|
||||
clerkJwtTemplate: "t3-relay",
|
||||
relayUrl: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import Constants from "expo-constants";
|
||||
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
|
||||
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
|
||||
|
||||
@@ -22,7 +23,7 @@ export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig
|
||||
return {
|
||||
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
|
||||
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
|
||||
relayUrl: trimNonEmpty(relay?.url)?.replace(/\/+$/u, "") ?? null,
|
||||
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
|
||||
} satisfies CloudPublicConfig;
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
signRelayJwt,
|
||||
verifyRelayJwt,
|
||||
} from "@t3tools/shared/relayJwt";
|
||||
import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -155,20 +156,6 @@ function validateCloudMintPublicKey(
|
||||
);
|
||||
}
|
||||
|
||||
function isSecureRelayUrl(value: string): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (
|
||||
url.protocol === "https:" &&
|
||||
url.username.length === 0 &&
|
||||
url.password.length === 0 &&
|
||||
url.hash.length === 0
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function validateRelayConfigPayload(
|
||||
payload: RelayEnvironmentConfigRequest,
|
||||
): Effect.Effect<void, EnvironmentHttpBadRequestError> {
|
||||
|
||||
@@ -2127,6 +2127,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
relayIssuer: "http://relay.example.test",
|
||||
environmentCredential: "t3env_test_credential",
|
||||
});
|
||||
const nonOriginRelayUrl = yield* postRelayConfig({
|
||||
relayUrl: "https://relay.example.test/path",
|
||||
cloudUserId: "user_123",
|
||||
environmentCredential: "t3env_test_credential",
|
||||
});
|
||||
const emptyCredential = yield* postRelayConfig({
|
||||
relayUrl: "https://relay.example.test",
|
||||
cloudUserId: "user_123",
|
||||
@@ -2138,6 +2143,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>(
|
||||
insecureRelayIssuer,
|
||||
);
|
||||
const nonOriginRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>(
|
||||
nonOriginRelayUrl,
|
||||
);
|
||||
const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>(
|
||||
emptyCredential,
|
||||
);
|
||||
@@ -2149,6 +2157,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
insecureRelayIssuerBody.message,
|
||||
"Relay issuer must be a secure absolute HTTPS URL.",
|
||||
);
|
||||
assert.equal(nonOriginRelayUrl.status, 400);
|
||||
assert.equal(nonOriginRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL.");
|
||||
assert.equal(emptyCredential.status, 400);
|
||||
assert.equal(emptyCredentialBody.message, "Relay environment credential is required.");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
|
||||
@@ -22,4 +22,12 @@ describe("hasCloudPublicConfig", () => {
|
||||
vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");
|
||||
expect(hasCloudPublicConfig()).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an insecure relay URL", () => {
|
||||
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example");
|
||||
vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");
|
||||
vi.stubEnv("VITE_T3CODE_RELAY_URL", "http://relay.example.test");
|
||||
|
||||
expect(hasCloudPublicConfig()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
|
||||
export interface CloudPublicConfig {
|
||||
readonly clerkPublishableKey: string | null;
|
||||
@@ -16,11 +17,9 @@ export function resolveCloudPublicConfig(): CloudPublicConfig {
|
||||
import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined,
|
||||
),
|
||||
clerkJwtTemplate: trimNonEmpty(import.meta.env.VITE_CLERK_JWT_TEMPLATE as string | undefined),
|
||||
relayUrl:
|
||||
trimNonEmpty(import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined)?.replace(
|
||||
/\/+$/u,
|
||||
"",
|
||||
) ?? null,
|
||||
relayUrl: normalizeSecureRelayUrl(
|
||||
(import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined) ?? "",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,10 @@ import {
|
||||
} from "./managedRelay.ts";
|
||||
import { remoteHttpClientLayer } from "./remote.ts";
|
||||
|
||||
function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) {
|
||||
function managedRelayTestLayer(
|
||||
fetchFn: typeof globalThis.fetch,
|
||||
relayUrl = "https://relay.example.test",
|
||||
) {
|
||||
const httpClientLayer = remoteHttpClientLayer(fetchFn);
|
||||
const signerLayer = Layer.succeed(
|
||||
ManagedRelayDpopSigner,
|
||||
@@ -26,12 +29,33 @@ function managedRelayTestLayer(fetchFn: typeof globalThis.fetch) {
|
||||
}),
|
||||
);
|
||||
return managedRelayClientLayer({
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayUrl,
|
||||
clientId: "t3-mobile",
|
||||
}).pipe(Layer.provide(signerLayer), Layer.provide(httpClientLayer));
|
||||
}
|
||||
|
||||
describe("ManagedRelayClient", () => {
|
||||
it.effect("rejects unsafe relay URLs before sending credentials", () => {
|
||||
let requestCount = 0;
|
||||
const fetchFn = (() => {
|
||||
requestCount += 1;
|
||||
return Promise.resolve(Response.json({}));
|
||||
}) satisfies typeof globalThis.fetch;
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const relayClient = yield* ManagedRelayClient;
|
||||
const error = yield* relayClient
|
||||
.listEnvironments({ clerkToken: "clerk-token" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "ManagedRelayClientError",
|
||||
message: "Relay URL must be a secure absolute HTTPS origin.",
|
||||
});
|
||||
expect(requestCount).toBe(0);
|
||||
}).pipe(Effect.provide(managedRelayTestLayer(fetchFn, "http://relay.example.test")));
|
||||
});
|
||||
|
||||
it.effect("reuses usable DPoP tokens and refreshes cleared or expiring cache entries", () => {
|
||||
let tokenExchangeCount = 0;
|
||||
const fetchFn = ((input) => {
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
RelayUnregisterDeviceEndpoint,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";
|
||||
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
@@ -183,14 +184,37 @@ function dpopHeaders(authorization: ManagedRelayAuthorization) {
|
||||
};
|
||||
}
|
||||
|
||||
function disabledManagedRelayClient(relayUrl: string): ManagedRelayClientShape {
|
||||
const unavailable = () =>
|
||||
Effect.fail(relayClientError("Relay URL must be a secure absolute HTTPS origin."));
|
||||
return ManagedRelayClient.of({
|
||||
relayUrl,
|
||||
listEnvironments: unavailable,
|
||||
listDevices: unavailable,
|
||||
createEnvironmentLinkChallenge: unavailable,
|
||||
linkEnvironment: unavailable,
|
||||
unlinkEnvironment: unavailable,
|
||||
getEnvironmentStatus: unavailable,
|
||||
connectEnvironment: unavailable,
|
||||
registerDevice: unavailable,
|
||||
unregisterDevice: unavailable,
|
||||
registerLiveActivity: unavailable,
|
||||
resetTokenCache: Effect.void,
|
||||
});
|
||||
}
|
||||
|
||||
export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions) {
|
||||
return Layer.effect(
|
||||
ManagedRelayClient,
|
||||
Effect.gen(function* () {
|
||||
const relayUrl = normalizeSecureRelayUrl(options.relayUrl);
|
||||
if (relayUrl === null) {
|
||||
return disabledManagedRelayClient(options.relayUrl);
|
||||
}
|
||||
const signer = yield* ManagedRelayDpopSigner;
|
||||
const client = yield* HttpApiClient.make(RelayApi, { baseUrl: options.relayUrl });
|
||||
const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl });
|
||||
const cachedTokens = yield* SynchronizedRef.make<ReadonlyArray<CachedRelayAccessToken>>([]);
|
||||
const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: options.relayUrl });
|
||||
const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl });
|
||||
|
||||
type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;
|
||||
const dpopProofTargets = {
|
||||
@@ -257,7 +281,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
|
||||
subject_token: input.clerkToken,
|
||||
subject_token_type: RelayJwtSubjectTokenType,
|
||||
requested_token_type: RelayAccessTokenType,
|
||||
resource: options.relayUrl,
|
||||
resource: relayUrl,
|
||||
scope: encodeOAuthScope(input.scopes),
|
||||
client_id: options.clientId,
|
||||
},
|
||||
@@ -325,7 +349,7 @@ export function managedRelayClientLayer(options: ManagedRelayClientLayerOptions)
|
||||
});
|
||||
|
||||
return ManagedRelayClient.of({
|
||||
relayUrl: options.relayUrl,
|
||||
relayUrl,
|
||||
listEnvironments: (input) =>
|
||||
client.client.listEnvironments({ headers: bearerHeaders(input.clerkToken) }).pipe(
|
||||
Effect.map((response) => response.environments),
|
||||
|
||||
@@ -103,6 +103,10 @@
|
||||
"types": "./src/relayAuth.ts",
|
||||
"import": "./src/relayAuth.ts"
|
||||
},
|
||||
"./relayUrl": {
|
||||
"types": "./src/relayUrl.ts",
|
||||
"import": "./src/relayUrl.ts"
|
||||
},
|
||||
"./relayJwt": {
|
||||
"types": "./src/relayJwt.ts",
|
||||
"import": "./src/relayJwt.ts"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isSecureRelayUrl, normalizeSecureRelayUrl } from "./relayUrl.ts";
|
||||
|
||||
describe("normalizeSecureRelayUrl", () => {
|
||||
it("normalizes secure relay origins", () => {
|
||||
expect(normalizeSecureRelayUrl(" https://relay.example.test/// ")).toBe(
|
||||
"https://relay.example.test",
|
||||
);
|
||||
expect(normalizeSecureRelayUrl("https://relay.example.test:8443/")).toBe(
|
||||
"https://relay.example.test:8443",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"http://relay.example.test",
|
||||
"https://user:[email protected]",
|
||||
"https://relay.example.test/path",
|
||||
"https://relay.example.test?query=value",
|
||||
"https://relay.example.test#fragment",
|
||||
"not a url",
|
||||
])("rejects unsafe relay URL %s", (value) => {
|
||||
expect(normalizeSecureRelayUrl(value)).toBeNull();
|
||||
expect(isSecureRelayUrl(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
export function normalizeSecureRelayUrl(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value.trim());
|
||||
if (
|
||||
url.protocol !== "https:" ||
|
||||
url.username.length > 0 ||
|
||||
url.password.length > 0 ||
|
||||
url.search.length > 0 ||
|
||||
url.hash.length > 0 ||
|
||||
!/^\/+$/u.test(url.pathname)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isSecureRelayUrl(value: string): boolean {
|
||||
return normalizeSecureRelayUrl(value) !== null;
|
||||
}
|
||||
Reference in new issue
Block a user