Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/src/features/cloud/linkEnvironment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ describe("mobile cloud link environment client", () => {
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(connectRequestBody)).toMatchObject({
deviceId: "device-1",
clientKeyThumbprint: "client-proof-key-thumbprint",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
});
expect(createProofMock).toHaveBeenCalledWith({
method: "POST",
Expand Down
32 changes: 21 additions & 11 deletions apps/mobile/src/features/cloud/linkEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
scopes: [RelayEnvironmentConnectScope],
environmentId: input.environmentId,
deviceId,
client: authClientMetadata(),
})
.pipe(
Effect.mapError(
Expand All @@ -497,21 +498,30 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
message: "Relay returned credentials for a different environment.",
});
}
if (!("credential" in connect)) {
return yield* new CloudEnvironmentLinkError({
message:
connect.approvalStatus === "rejected"
? "This device was rejected by the environment. Approve it in the environment settings to connect."
: "Waiting for this device to be approved in the environment settings.",
});
}
const authorizedConnect = connect;
if (input.expectedEnvironment) {
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.expectedEnvironment,
connect,
connect: authorizedConnect,
});
}

const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
),
);
if (descriptor.environmentId !== connect.environmentId) {
if (descriptor.environmentId !== authorizedConnect.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Connected endpoint descriptor does not match the selected environment.",
});
Expand All @@ -520,29 +530,29 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
url: new URL("/oauth/token", authorizedConnect.endpoint.httpBaseUrl).toString(),
})
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
const bootstrap = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
credential: authorizedConnect.credential,
dpopProof: bootstrapDpop,
clientMetadata: authClientMetadata(),
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
),
);
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
const pairingUrl = new URL(authorizedConnect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", authorizedConnect.credential]]).toString();

return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
displayUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
wsBaseUrl: connect.endpoint.wsBaseUrl,
displayUrl: authorizedConnect.endpoint.httpBaseUrl,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
wsBaseUrl: authorizedConnect.endpoint.wsBaseUrl,
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
Expand Down
187 changes: 187 additions & 0 deletions apps/server/src/auth/ConnectClientStore.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
import { expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";

import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as ConnectClientStore from "./ConnectClientStore.ts";

const textEncoder = new TextEncoder();
const requestedAt = DateTime.makeUnsafe("2026-06-27T12:00:00.000Z");
const approvedAt = DateTime.makeUnsafe("2026-06-27T12:05:00.000Z");
const rejectedAt = DateTime.makeUnsafe("2026-06-27T12:06:00.000Z");

const approvedRecord: AuthConnectClients.AuthConnectClientRecord = {
clientProofKeyThumbprint: "client-thumbprint",
cloudUserId: "cloud-user",
deviceId: "device-1",
status: "approved",
client: {
label: "Client",
ipAddress: null,
userAgent: null,
deviceType: "desktop",
os: "macOS",
browser: null,
},
requestedAt,
updatedAt: approvedAt,
approvedAt,
rejectedAt: null,
revokedAt: null,
lastSeenAt: null,
};
const pendingRecord: AuthConnectClients.AuthConnectClientRecord = {
...approvedRecord,
status: "pending",
updatedAt: requestedAt,
approvedAt: null,
lastSeenAt: null,
};

const makeSecretStoreLayer = (mode: string) =>
Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
get: () => Effect.succeed(Option.some(textEncoder.encode(mode))),
set: () => Effect.void,
create: () => Effect.void,
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
remove: () => Effect.void,
}),
);

const secretStoreLayer = makeSecretStoreLayer("client-approval");

const makeStoreOnlyLayer = (mode: string) =>
Layer.effect(ConnectClientStore.ConnectClientStore, ConnectClientStore.make).pipe(
Layer.provide(makeSecretStoreLayer(mode)),
Layer.provide(
Layer.succeed(
AuthConnectClients.AuthConnectClientRepository,
AuthConnectClients.AuthConnectClientRepository.of({
upsertRequest: () => Effect.succeed(approvedRecord),
updateStatus: () => Effect.succeed(Option.none()),
revoke: () => Effect.succeed(false),
markSeen: () => Effect.succeed(Option.some(approvedRecord)),
listActive: () => Effect.succeed([]),
}),
),
),
);

const makeStoreLayer = (
overrides: Partial<AuthConnectClients.AuthConnectClientRepository["Service"]>,
) =>
Layer.effect(ConnectClientStore.ConnectClientStore, ConnectClientStore.make).pipe(
Layer.provide(secretStoreLayer),
Layer.provide(
Layer.succeed(
AuthConnectClients.AuthConnectClientRepository,
AuthConnectClients.AuthConnectClientRepository.of({
upsertRequest: () => Effect.succeed(approvedRecord),
updateStatus: () => Effect.succeed(Option.none()),
revoke: () => Effect.succeed(false),
markSeen: () => Effect.succeed(Option.some(approvedRecord)),
listActive: () => Effect.succeed([]),
...overrides,
}),
),
),
);

it.effect("fails closed when persisted security mode is invalid", () =>
Effect.gen(function* () {
const store = yield* ConnectClientStore.ConnectClientStore;
const error = yield* Effect.flip(store.getSecurityMode());

expect(error._tag).toBe("ConnectSecurityModeLoadError");
expect(error.invalidValue).toBe("invalid-mode");
}).pipe(Effect.provide(makeStoreOnlyLayer("invalid-mode"))),
);

it.effect("returns rejected when an approved client is rejected before last-seen update", () =>
Effect.gen(function* () {
const store = yield* ConnectClientStore.ConnectClientStore;
const authorization = yield* store.requestClient({
cloudUserId: "cloud-user",
clientProofKeyThumbprint: "client-thumbprint",
});

expect(authorization.mode).toBe("client-approval");
expect(authorization.status).toBe("rejected");
}).pipe(
Effect.provide(
makeStoreLayer({
markSeen: () =>
Effect.succeed(
Option.some({
...approvedRecord,
status: "rejected",
updatedAt: rejectedAt,
rejectedAt,
}),
),
}),
),
),
);

it.effect(
"re-registers a pending client when an approved client is revoked before last-seen update",
() => {
const upsertInputs: Array<AuthConnectClients.UpsertAuthConnectClientRequestInput> = [];

return Effect.gen(function* () {
const store = yield* ConnectClientStore.ConnectClientStore;
const changesFiber = yield* store.streamChanges.pipe(
Stream.take(2),
Stream.runCollect,
Effect.forkScoped,
);
yield* Effect.yieldNow;
const authorization = yield* store.requestClient({
cloudUserId: "cloud-user",
clientProofKeyThumbprint: "client-thumbprint",
});
const changes = Array.from(yield* Fiber.join(changesFiber));

expect(authorization.mode).toBe("client-approval");
expect(authorization.status).toBe("pending");
expect(upsertInputs).toHaveLength(2);
if (authorization.mode === "client-approval") {
expect(authorization.client.status).toBe("pending");
expect(authorization.client.approvedAt).toBeNull();
expect(authorization.client.lastSeenAt).toBeNull();
}
expect(changes.map((change) => change.type)).toEqual([
"connectClientUpserted",
"connectClientUpserted",
]);
expect(changes[1]?.type === "connectClientUpserted" ? changes[1].client.status : null).toBe(
"pending",
);
}).pipe(
Effect.provide(
makeStoreLayer({
upsertRequest: (input) =>
Effect.sync(() => {
upsertInputs.push(input);
return upsertInputs.length === 1
? approvedRecord
: {
...pendingRecord,
requestedAt: input.requestedAt,
updatedAt: input.requestedAt,
};
}),
markSeen: () => Effect.succeed(Option.none()),
}),
),
);
},
);
Loading
Loading