Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e371cc280b | ||
|
|
1690e15f58 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
computeDpopAccessTokenHash,
|
||||
@@ -202,4 +202,25 @@ describe("verifyDpopProof", () => {
|
||||
}),
|
||||
).toMatchObject({ ok: false, reason: "Invalid DPoP JWT header." });
|
||||
});
|
||||
|
||||
it("validates decoded JWT JSON with schemas", () => {
|
||||
const header = Buffer.from(
|
||||
JSON.stringify({
|
||||
typ: "dpop+jwt",
|
||||
alg: "ES256",
|
||||
jwk: publicJwk,
|
||||
}),
|
||||
).toString("base64url");
|
||||
const malformedJsonPayload = Buffer.from("{").toString("base64url");
|
||||
|
||||
assert.deepEqual(
|
||||
verifyDpopProof({
|
||||
proof: `${header}.${malformedJsonPayload}.signature`,
|
||||
method: "POST",
|
||||
url: "https://example.com/oauth/token",
|
||||
nowEpochSeconds: 101,
|
||||
}),
|
||||
{ ok: false, reason: "Invalid DPoP JWT payload." },
|
||||
);
|
||||
});
|
||||
});
|
||||
+48
-55
@@ -1,6 +1,7 @@
|
||||
import { p256 } from "@noble/curves/nist";
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -9,6 +10,7 @@ import { stableStringify } from "./relaySigning.ts";
|
||||
const DPOP_TYP = "dpop+jwt";
|
||||
const DPOP_ALG = "ES256";
|
||||
const DEFAULT_MAX_AGE_SECONDS = 300;
|
||||
const decodeJsonStringOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
export const DpopPublicJwk = Schema.Struct({
|
||||
kty: Schema.Literal("EC"),
|
||||
@@ -17,21 +19,24 @@ export const DpopPublicJwk = Schema.Struct({
|
||||
y: Schema.String.check(Schema.isNonEmpty()),
|
||||
});
|
||||
export type DpopPublicJwk = typeof DpopPublicJwk.Type;
|
||||
const isDpopPublicJwk = Schema.is(DpopPublicJwk);
|
||||
|
||||
interface DpopJwtHeader {
|
||||
readonly typ: string;
|
||||
readonly alg: string;
|
||||
readonly jwk: DpopPublicJwk;
|
||||
}
|
||||
const DpopJwtHeader = Schema.Struct({
|
||||
typ: Schema.Literal(DPOP_TYP),
|
||||
alg: Schema.Literal(DPOP_ALG),
|
||||
jwk: DpopPublicJwk,
|
||||
});
|
||||
type DpopJwtHeader = typeof DpopJwtHeader.Type;
|
||||
const decodeDpopJwtHeaderOption = Schema.decodeUnknownOption(DpopJwtHeader);
|
||||
|
||||
interface DpopJwtPayload {
|
||||
readonly htm: string;
|
||||
readonly htu: string;
|
||||
readonly jti: string;
|
||||
readonly iat: number;
|
||||
readonly ath?: string;
|
||||
}
|
||||
const DpopJwtPayload = Schema.Struct({
|
||||
htm: Schema.String.check(Schema.isNonEmpty()),
|
||||
htu: Schema.String.check(Schema.isNonEmpty()),
|
||||
jti: Schema.String.check(Schema.isNonEmpty()),
|
||||
iat: Schema.Int,
|
||||
ath: Schema.optional(Schema.String),
|
||||
});
|
||||
type DpopJwtPayload = typeof DpopJwtPayload.Type;
|
||||
const decodeDpopJwtPayloadOption = Schema.decodeUnknownOption(DpopJwtPayload);
|
||||
|
||||
export type DpopVerificationResult =
|
||||
| {
|
||||
@@ -49,40 +54,23 @@ function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function decodeBase64UrlJson(value: string): unknown {
|
||||
return JSON.parse(Result.getOrThrow(Encoding.decodeBase64UrlString(value))) as unknown;
|
||||
function decodeBase64UrlJson(value: string): Option.Option<unknown> {
|
||||
return Result.match(Encoding.decodeBase64UrlString(value), {
|
||||
onFailure: () => Option.none(),
|
||||
onSuccess: decodeJsonStringOption,
|
||||
});
|
||||
}
|
||||
|
||||
function isDpopJwtHeader(value: unknown): value is DpopJwtHeader {
|
||||
function hasPrivateJwkMaterial(value: unknown): boolean {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return false;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
record.typ === DPOP_TYP &&
|
||||
record.alg === DPOP_ALG &&
|
||||
typeof record.jwk === "object" &&
|
||||
record.jwk !== null &&
|
||||
!("d" in record.jwk) &&
|
||||
isDpopPublicJwk(record.jwk)
|
||||
);
|
||||
return typeof record.jwk === "object" && record.jwk !== null && "d" in record.jwk;
|
||||
}
|
||||
|
||||
function isDpopJwtPayload(value: unknown): value is DpopJwtPayload {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return false;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof record.htm === "string" &&
|
||||
record.htm.length > 0 &&
|
||||
typeof record.htu === "string" &&
|
||||
record.htu.length > 0 &&
|
||||
typeof record.jti === "string" &&
|
||||
record.jti.length > 0 &&
|
||||
typeof record.iat === "number" &&
|
||||
Number.isInteger(record.iat)
|
||||
);
|
||||
function decodeDpopJwtHeader(value: unknown): Option.Option<DpopJwtHeader> {
|
||||
return hasPrivateJwkMaterial(value) ? Option.none() : decodeDpopJwtHeaderOption(value);
|
||||
}
|
||||
|
||||
function dpopThumbprintInput(jwk: DpopPublicJwk): string {
|
||||
@@ -145,53 +133,58 @@ export function verifyDpopProof(input: {
|
||||
}
|
||||
|
||||
try {
|
||||
const header = decodeBase64UrlJson(parts[0]);
|
||||
const payload = decodeBase64UrlJson(parts[1]);
|
||||
if (!isDpopJwtHeader(header)) {
|
||||
const header = Option.flatMap(decodeBase64UrlJson(parts[0]), decodeDpopJwtHeader);
|
||||
const payload = Option.flatMap(decodeBase64UrlJson(parts[1]), decodeDpopJwtPayloadOption);
|
||||
if (Option.isNone(header)) {
|
||||
return { ok: false, reason: "Invalid DPoP JWT header." };
|
||||
}
|
||||
if (!isDpopJwtPayload(payload)) {
|
||||
if (Option.isNone(payload)) {
|
||||
return { ok: false, reason: "Invalid DPoP JWT payload." };
|
||||
}
|
||||
|
||||
const thumbprint = computeDpopJwkThumbprint(header.jwk);
|
||||
const thumbprint = computeDpopJwkThumbprint(header.value.jwk);
|
||||
if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {
|
||||
return { ok: false, reason: "DPoP key thumbprint mismatch." };
|
||||
}
|
||||
if (payload.htm.toUpperCase() !== input.method.toUpperCase()) {
|
||||
if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {
|
||||
return { ok: false, reason: "DPoP method mismatch." };
|
||||
}
|
||||
const normalizedHtu = normalizeDpopHtu(input.url);
|
||||
if (normalizedHtu === null || payload.htu !== normalizedHtu) {
|
||||
if (normalizedHtu === null || payload.value.htu !== normalizedHtu) {
|
||||
return { ok: false, reason: "DPoP URL mismatch." };
|
||||
}
|
||||
if (input.expectedAccessToken) {
|
||||
const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);
|
||||
if (payload.ath !== expectedAth) {
|
||||
if (payload.value.ath !== expectedAth) {
|
||||
return { ok: false, reason: "DPoP access token hash mismatch." };
|
||||
}
|
||||
}
|
||||
|
||||
const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;
|
||||
if (
|
||||
payload.iat > input.nowEpochSeconds + 5 ||
|
||||
input.nowEpochSeconds - payload.iat > maxAgeSeconds
|
||||
payload.value.iat > input.nowEpochSeconds + 5 ||
|
||||
input.nowEpochSeconds - payload.value.iat > maxAgeSeconds
|
||||
) {
|
||||
return { ok: false, reason: "DPoP proof is outside the allowed time window." };
|
||||
}
|
||||
|
||||
const signature = base64UrlToBytes(parts[2]);
|
||||
const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
|
||||
const verified = p256.verify(signature, signatureInputHash, publicKeyBytesFromJwk(header.jwk), {
|
||||
prehash: false,
|
||||
format: "compact",
|
||||
});
|
||||
const verified = p256.verify(
|
||||
signature,
|
||||
signatureInputHash,
|
||||
publicKeyBytesFromJwk(header.value.jwk),
|
||||
{
|
||||
prehash: false,
|
||||
format: "compact",
|
||||
},
|
||||
);
|
||||
return verified
|
||||
? {
|
||||
ok: true,
|
||||
thumbprint,
|
||||
jti: payload.jti,
|
||||
iat: payload.iat,
|
||||
jti: payload.value.jti,
|
||||
iat: payload.value.iat,
|
||||
}
|
||||
: { ok: false, reason: "Invalid DPoP signature." };
|
||||
} catch {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";
|
||||
@@ -192,6 +194,58 @@ describe("RelayClient", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("removes stale installation locks before installing", () => {
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-",
|
||||
});
|
||||
const manager = yield* makeCloudflaredRelayClient({
|
||||
baseDir,
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
});
|
||||
const managedDirectory = `${baseDir}/tools/cloudflared/${CLOUDFLARED_VERSION}/linux-x64`;
|
||||
const managedPath = `${managedDirectory}/cloudflared`;
|
||||
const lockPath = `${managedPath}.lock`;
|
||||
yield* fileSystem.makeDirectory(managedDirectory, { recursive: true });
|
||||
yield* fileSystem.writeFileString(lockPath, "stale");
|
||||
yield* fileSystem.utimes(
|
||||
lockPath,
|
||||
DateTime.toDate(DateTime.makeUnsafe("2026-06-15T15:50:00.000Z")),
|
||||
DateTime.toDate(DateTime.makeUnsafe("2026-06-15T15:50:00.000Z")),
|
||||
);
|
||||
yield* TestClock.setTime(
|
||||
DateTime.toEpochMillis(DateTime.makeUnsafe("2026-06-15T16:00:00.000Z")),
|
||||
);
|
||||
|
||||
const installed = yield* manager.install;
|
||||
|
||||
assert.deepEqual(installed, {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
assert.isFalse(yield* fileSystem.exists(lockPath));
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeHttpClientLayer(bytes),
|
||||
makeSpawnerLayer([]),
|
||||
hostRuntimeLayer(),
|
||||
TestClock.layer(),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("serializes concurrent installs within one runtime", () => {
|
||||
const commands: Array<string> = [];
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import type {
|
||||
RelayClientInstallProgressEvent,
|
||||
RelayClientInstallProgressStage,
|
||||
@@ -7,6 +6,8 @@ import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -14,6 +15,8 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -62,6 +65,12 @@ class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError"
|
||||
readonly exitCode: number;
|
||||
}> {}
|
||||
|
||||
class RelayClientInstallLockBusy extends Schema.TaggedErrorClass<RelayClientInstallLockBusy>()(
|
||||
"RelayClientInstallLockBusy",
|
||||
{},
|
||||
) {}
|
||||
const isRelayClientInstallLockBusy = Schema.is(RelayClientInstallLockBusy);
|
||||
|
||||
export interface CloudflaredReleaseAsset {
|
||||
readonly url: string;
|
||||
readonly sha256: string;
|
||||
@@ -98,9 +107,16 @@ const CLOUDFLARED_RELEASE_ASSETS: Readonly<
|
||||
},
|
||||
};
|
||||
|
||||
const INSTALL_LOCK_RETRY_COUNT = 100;
|
||||
const INSTALL_LOCK_RETRY_DELAY = "100 millis";
|
||||
const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
|
||||
const INSTALL_LOCK_RETRY_ATTEMPTS = 100;
|
||||
const INSTALL_LOCK_RETRY_DELAY = Duration.millis(100);
|
||||
const INSTALL_LOCK_STALE_DURATION = Duration.minutes(5);
|
||||
const INSTALL_LOCK_RETRY_POLICY = Schedule.both(
|
||||
Schedule.spaced(INSTALL_LOCK_RETRY_DELAY),
|
||||
Schedule.recurs(INSTALL_LOCK_RETRY_ATTEMPTS - 1),
|
||||
).pipe(
|
||||
Schedule.setInputType<RelayClientInstallLockBusy | PlatformError.PlatformError>(),
|
||||
Schedule.while(({ input }) => isRelayClientInstallLockBusy(input)),
|
||||
);
|
||||
|
||||
const trimmedString = (name: string) =>
|
||||
Config.string(name).pipe(
|
||||
@@ -325,31 +341,51 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
return bytes;
|
||||
});
|
||||
|
||||
const tryAcquireInstallLock = Effect.fn("cloudflared.tryAcquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
const writeLock = fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
const acquired = yield* writeLock;
|
||||
if (acquired) return true;
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (
|
||||
Option.isSome(mtime) &&
|
||||
Duration.isGreaterThan(
|
||||
DateTime.distance(DateTime.fromDateUnsafe(mtime.value), now),
|
||||
INSTALL_LOCK_STALE_DURATION,
|
||||
)
|
||||
) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
return yield* writeLock;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
return yield* tryAcquireInstallLock(lockPath).pipe(
|
||||
Effect.flatMap((acquired) =>
|
||||
acquired ? Effect.void : Effect.fail(new RelayClientInstallLockBusy({})),
|
||||
),
|
||||
Effect.retry(INSTALL_LOCK_RETRY_POLICY),
|
||||
Effect.catchTag("RelayClientInstallLockBusy", () =>
|
||||
Effect.fail(
|
||||
new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
}
|
||||
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
|
||||
}
|
||||
return yield* new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
});
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
|
||||
|
||||
Reference in new issue
Block a user