Harden device login flow against transient relay failures
- Retry device authorization issuance on unique-code collisions - Validate relay device/login payload sizes up front - Keep polling and cleanup resilient to transient transport failures
This commit is contained in:
1 parent
ebaeee9339
commit
87c028fd05
4 files changed
+106
-53
No files matched your search
@@ -39,6 +39,7 @@ import { cloudCliOAuthConfig, relayUrlConfig, type CloudCliOAuthConfig } from ".
|
||||
const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";
|
||||
const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);
|
||||
const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));
|
||||
const CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES = 5;
|
||||
|
||||
const PersistedToken = Schema.Struct({
|
||||
accessToken: Schema.String,
|
||||
@@ -312,23 +313,45 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
let pollInterval = Duration.seconds(authorization.interval);
|
||||
// Approval can take minutes; a flaky network or a relay blip mid-wait
|
||||
// must not abort the whole login, so only repeated transport failures do.
|
||||
let consecutiveTransportFailures = 0;
|
||||
const failTransportOrContinue = (cause: unknown) => {
|
||||
consecutiveTransportFailures += 1;
|
||||
return consecutiveTransportFailures >= CLOUD_CLI_DEVICE_POLL_MAX_TRANSPORT_FAILURES
|
||||
? Effect.fail(new CloudCliAuthorizationError({ cause }))
|
||||
: Effect.succeed(Option.none<HttpClientResponse.HttpClientResponse>());
|
||||
};
|
||||
const poll = Effect.gen(function* () {
|
||||
while (true) {
|
||||
yield* Effect.sleep(pollInterval);
|
||||
const response = yield* rawHttpClient.execute(
|
||||
HttpClientRequest.post(`${relayUrl}/v1/device/token`).pipe(
|
||||
HttpClientRequest.bodyUrlParams({
|
||||
grant_type: RelayDeviceAuthorizationGrantType,
|
||||
device_code: authorization.device_code,
|
||||
client_id: metadata.clientId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (response.status === 200) {
|
||||
return yield* HttpClientResponse.schemaBodyJson(RelayDeviceTokenResponse)(response);
|
||||
const response = yield* rawHttpClient
|
||||
.execute(
|
||||
HttpClientRequest.post(`${relayUrl}/v1/device/token`).pipe(
|
||||
HttpClientRequest.bodyUrlParams({
|
||||
grant_type: RelayDeviceAuthorizationGrantType,
|
||||
device_code: authorization.device_code,
|
||||
client_id: metadata.clientId,
|
||||
}),
|
||||
),
|
||||
)
|
||||
.pipe(Effect.map(Option.some), Effect.catch(failTransportOrContinue));
|
||||
if (Option.isNone(response)) {
|
||||
continue;
|
||||
}
|
||||
if (response.value.status === 200) {
|
||||
return yield* HttpClientResponse.schemaBodyJson(RelayDeviceTokenResponse)(response.value);
|
||||
}
|
||||
if (response.value.status !== 400) {
|
||||
// Gateway errors and other unexpected statuses are transient.
|
||||
yield* failTransportOrContinue(
|
||||
`Relay device token poll returned status ${response.value.status}.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
consecutiveTransportFailures = 0;
|
||||
const body = yield* HttpClientResponse.schemaBodyJson(DeviceTokenPollErrorBody)(
|
||||
response,
|
||||
response.value,
|
||||
).pipe(Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })));
|
||||
switch (body.code) {
|
||||
case "authorization_pending":
|
||||
|
||||
+35
-23
@@ -711,31 +711,43 @@ export const deviceApi = HttpApiBuilder.group(
|
||||
yield* Effect.annotateCurrentSpan({
|
||||
"relay.oauth.client_id": args.payload.client_id,
|
||||
});
|
||||
const randomBytes = yield* crypto
|
||||
.randomBytes(32 + RELAY_DEVICE_USER_CODE_LENGTH)
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
|
||||
const deviceCode = Encoding.encodeBase64Url(randomBytes.slice(0, 32));
|
||||
const deviceCodeHash = yield* hashDeviceCode(crypto, deviceCode);
|
||||
const userCode = deviceUserCodeFromBytes(randomBytes.slice(32));
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.addDuration(now, RELAY_DEVICE_AUTHORIZATION_TTL);
|
||||
yield* deviceAuthorizations.create({
|
||||
deviceCodeHash,
|
||||
userCode,
|
||||
clientId: args.payload.client_id,
|
||||
scope: args.payload.scope,
|
||||
codeChallenge: args.payload.code_challenge,
|
||||
deviceName: args.payload.device_name ?? null,
|
||||
devicePlatform: args.payload.device_platform ?? null,
|
||||
clientVersion: args.payload.client_version ?? null,
|
||||
requestIp: request.headers["cf-connecting-ip"] ?? null,
|
||||
requestLocation: request.headers["cf-ipcountry"] ?? null,
|
||||
pollIntervalSeconds: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
|
||||
expiresAt,
|
||||
// A fresh code pair is generated per attempt so a user-code
|
||||
// collision on the unique index retries instead of failing the
|
||||
// login request.
|
||||
const issueAuthorization = Effect.gen(function* () {
|
||||
const randomBytes = yield* crypto
|
||||
.randomBytes(32 + RELAY_DEVICE_USER_CODE_LENGTH)
|
||||
.pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));
|
||||
const deviceCode = Encoding.encodeBase64Url(randomBytes.slice(0, 32));
|
||||
const deviceCodeHash = yield* hashDeviceCode(crypto, deviceCode);
|
||||
const userCode = deviceUserCodeFromBytes(randomBytes.slice(32));
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.addDuration(now, RELAY_DEVICE_AUTHORIZATION_TTL);
|
||||
yield* deviceAuthorizations.create({
|
||||
deviceCodeHash,
|
||||
userCode,
|
||||
clientId: args.payload.client_id,
|
||||
scope: args.payload.scope,
|
||||
codeChallenge: args.payload.code_challenge,
|
||||
deviceName: args.payload.device_name ?? null,
|
||||
devicePlatform: args.payload.device_platform ?? null,
|
||||
clientVersion: args.payload.client_version ?? null,
|
||||
requestIp: request.headers["cf-connecting-ip"] ?? null,
|
||||
requestLocation: request.headers["cf-ipcountry"] ?? null,
|
||||
pollIntervalSeconds: RELAY_DEVICE_POLL_INTERVAL_SECONDS,
|
||||
expiresAt,
|
||||
});
|
||||
return { deviceCode, userCode };
|
||||
});
|
||||
const formattedUserCode = formatDeviceUserCode(userCode);
|
||||
const issued = yield* issueAuthorization.pipe(
|
||||
Effect.retry({
|
||||
times: 2,
|
||||
while: (error) => error._tag === "DeviceAuthorizationPersistenceError",
|
||||
}),
|
||||
);
|
||||
const formattedUserCode = formatDeviceUserCode(issued.userCode);
|
||||
return {
|
||||
device_code: deviceCode,
|
||||
device_code: issued.deviceCode,
|
||||
user_code: formattedUserCode,
|
||||
verification_uri: `${appBaseUrl}/oauth/device`,
|
||||
verification_uri_complete: `${appBaseUrl}/oauth/device?user_code=${formattedUserCode}`,
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Drizzle from "alchemy/Drizzle";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Etag from "effect/unstable/http/Etag";
|
||||
@@ -250,18 +251,29 @@ export default class Api extends Cloudflare.Worker<Api>()(
|
||||
),
|
||||
);
|
||||
|
||||
// Each prune runs to completion even when the other fails; a failure in
|
||||
// one must not leave the other's expired rows behind for a whole cycle.
|
||||
yield* Cloudflare.cron("*/5 * * * *").subscribe(() =>
|
||||
DpopProofs.DpopProofReplay.pipe(
|
||||
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
|
||||
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
|
||||
Effect.andThen(
|
||||
Effect.gen(function* () {
|
||||
const dpopPruneExit = yield* Effect.exit(
|
||||
DpopProofs.DpopProofReplay.pipe(
|
||||
Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),
|
||||
Effect.withSpan("relay.cron.prune_expired_dpop_proofs"),
|
||||
),
|
||||
);
|
||||
const devicePruneExit = yield* Effect.exit(
|
||||
DeviceAuthorizations.DeviceAuthorizations.pipe(
|
||||
Effect.flatMap((deviceAuthorizations) => deviceAuthorizations.pruneExpired),
|
||||
Effect.withSpan("relay.cron.prune_expired_device_authorizations"),
|
||||
),
|
||||
),
|
||||
Effect.provide(runtimeLayer),
|
||||
),
|
||||
);
|
||||
if (Exit.isFailure(dpopPruneExit)) {
|
||||
return yield* Effect.failCause(dpopPruneExit.cause);
|
||||
}
|
||||
if (Exit.isFailure(devicePruneExit)) {
|
||||
return yield* Effect.failCause(devicePruneExit.cause);
|
||||
}
|
||||
}).pipe(Effect.provide(runtimeLayer)),
|
||||
);
|
||||
|
||||
const fetch = Layer.merge(
|
||||
|
||||
@@ -693,29 +693,35 @@ export type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.T
|
||||
export const RelayDeviceAuthorizationGrantType =
|
||||
"urn:ietf:params:oauth:grant-type:device_code" as const;
|
||||
|
||||
// Bounds mirror the relay_device_authorizations column widths so overlong
|
||||
// input fails request validation instead of surfacing as a persistence error.
|
||||
const RelayDeviceClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(191));
|
||||
const RelayDeviceScope = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
|
||||
const RelayDeviceCodeChallenge = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
|
||||
|
||||
export const RelayDeviceAuthorizationRequest = Schema.Struct({
|
||||
client_id: TrimmedNonEmptyString.annotate({
|
||||
client_id: RelayDeviceClientId.annotate({
|
||||
description: "Clerk OAuth client id of the CLI requesting device authorization.",
|
||||
}),
|
||||
scope: TrimmedNonEmptyString.annotate({
|
||||
scope: RelayDeviceScope.annotate({
|
||||
description: "Space-separated OAuth scopes requested from Clerk.",
|
||||
}),
|
||||
code_challenge: TrimmedNonEmptyString.annotate({
|
||||
code_challenge: RelayDeviceCodeChallenge.annotate({
|
||||
description: "PKCE code challenge generated by the device.",
|
||||
}),
|
||||
code_challenge_method: Schema.Literal("S256"),
|
||||
device_name: Schema.optional(
|
||||
TrimmedNonEmptyString.annotate({
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(191)).annotate({
|
||||
description: "Human-readable device name shown on the approval page.",
|
||||
}),
|
||||
),
|
||||
device_platform: Schema.optional(
|
||||
TrimmedNonEmptyString.annotate({
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(128)).annotate({
|
||||
description: "Platform descriptor shown on the approval page.",
|
||||
}),
|
||||
),
|
||||
client_version: Schema.optional(
|
||||
TrimmedNonEmptyString.annotate({
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
|
||||
description: "CLI version shown on the approval page.",
|
||||
}),
|
||||
),
|
||||
@@ -736,8 +742,8 @@ export type RelayDeviceAuthorizationResponse = typeof RelayDeviceAuthorizationRe
|
||||
|
||||
export const RelayDeviceTokenRequest = Schema.Struct({
|
||||
grant_type: Schema.Literal(RelayDeviceAuthorizationGrantType),
|
||||
device_code: TrimmedNonEmptyString,
|
||||
client_id: TrimmedNonEmptyString,
|
||||
device_code: TrimmedNonEmptyString.check(Schema.isMaxLength(128)),
|
||||
client_id: RelayDeviceClientId,
|
||||
})
|
||||
.annotate({ description: "Polls a pending device authorization for its granted code." })
|
||||
.pipe(HttpApiSchema.asFormUrlEncoded());
|
||||
@@ -772,7 +778,7 @@ export const RelayDeviceAuthorizationDetails = Schema.Struct({
|
||||
export type RelayDeviceAuthorizationDetails = typeof RelayDeviceAuthorizationDetails.Type;
|
||||
|
||||
export const RelayDeviceAuthorizationParams = Schema.Struct({
|
||||
userCode: TrimmedNonEmptyString,
|
||||
userCode: TrimmedNonEmptyString.check(Schema.isMaxLength(32)),
|
||||
});
|
||||
export type RelayDeviceAuthorizationParams = typeof RelayDeviceAuthorizationParams.Type;
|
||||
|
||||
@@ -785,10 +791,10 @@ export const RelayDeviceApprovalResponse = Schema.Struct({
|
||||
export type RelayDeviceApprovalResponse = typeof RelayDeviceApprovalResponse.Type;
|
||||
|
||||
export const RelayDeviceCompletionRequest = Schema.Struct({
|
||||
state: TrimmedNonEmptyString.annotate({
|
||||
state: TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
|
||||
description: "Opaque state returned by the approval step and echoed by Clerk.",
|
||||
}),
|
||||
code: TrimmedNonEmptyString.annotate({
|
||||
code: TrimmedNonEmptyString.check(Schema.isMaxLength(512)).annotate({
|
||||
description: "Authorization code issued by Clerk for the approved device.",
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user