Skip to content
Merged
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
6 changes: 3 additions & 3 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1121,8 +1121,8 @@ export const make = Effect.gen(function* () {
Effect.withSpan("EnvironmentAuth.listSessions"),
);

const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
sessions.revoke(sessionId).pipe(
const revokeSession = (sessionId: AuthSessionId, callerSessionId?: AuthSessionId) =>
sessions.revoke(sessionId, callerSessionId).pipe(
Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeSession"),
);
Expand Down Expand Up @@ -1191,7 +1191,7 @@ export const make = Effect.gen(function* () {
if (currentSessionId === targetSessionId) {
return yield* new ServerAuthForbiddenOperationError({});
}
return yield* revokeSession(targetSessionId);
return yield* revokeSession(targetSessionId, currentSessionId);
});

const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ export class SessionStore extends Context.Service<
) => Effect.Effect<void, SessionCredentialVerificationError>;
readonly revoke: (
sessionId: AuthSessionId,
callerSessionId?: AuthSessionId,
) => Effect.Effect<boolean, SessionCredentialInternalError>;
readonly revokeAllExcept: (
sessionId: AuthSessionId,
Expand Down
149 changes: 138 additions & 11 deletions apps/server/src/kin/auth/ProofKeySessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
"other-devices",
"other-devices-live",
"other-key",
"other-key-expired",
"expired-revocation",
"expired-revocation-live-sibling",
"individual",
"individual-connected-expired",
"individual-connected-expired-original",
"individual-connected-expired-alone",
"same-key-caller",
"same-key-caller-connected-expired",
"same-key-caller-expired",
"other-key-caller",
"insert-race",
] as const)("%s", (action) =>
Effect.gen(function* () {
Expand All @@ -203,9 +212,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
);
const first = yield* exchange();
const original = yield* sessions.verify(first.access_token);
if (action === "other-key") {
const other = yield* sessions.issue({ proofKeyThumbprint: "other" });
yield* auth.revokeOtherClientSessions(original.sessionId);
if (action === "other-key" || action === "other-key-expired") {
const other = yield* sessions.issue({
proofKeyThumbprint: "other",
ttl: Duration.hours(1),
});
let caller = original;
if (action === "other-key-expired") {
yield* TestClock.adjust(Duration.minutes(61));
caller = yield* sessions.verify((yield* exchange()).access_token);
}
yield* auth.revokeOtherClientSessions(caller.sessionId);
const link = yield* auth.createPairingLink({ proofKeyThumbprint: "other" });
expect(
(yield* auth
Expand All @@ -216,6 +233,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
).toBe("ServerAuthInvalidCredentialError");
expect(Exit.isFailure(yield* sessions.verify(other.token).pipe(Effect.exit))).toBe(true);
yield* exchange();
expect((yield* sessions.verify((yield* exchange()).access_token)).proofKeyThumbprint).toBe(
"device",
);
} else if (action === "other-devices" || action === "other-devices-live") {
if (action === "other-devices") yield* TestClock.adjust(Duration.minutes(61));
const current = yield* sessions.verify((yield* exchange()).access_token);
Expand All @@ -227,12 +247,84 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
yield* TestClock.adjust(Duration.minutes(61));
yield* sessions.revoke(original.sessionId);
yield* exchange();
} else if (
action === "expired-revocation-live-sibling" ||
action === "individual-connected-expired-original" ||
action === "individual-connected-expired-alone"
) {
if (action !== "expired-revocation-live-sibling")
yield* sessions.markConnected(original.sessionId);
yield* TestClock.adjust(Duration.minutes(61));
if (action !== "individual-connected-expired-alone") yield* exchange();
yield* sessions.revoke(original.sessionId);
const link = yield* auth.createPairingLink({
subject: "cloud-connect",
proofKeyThumbprint: "device",
});
expect(
(yield* auth
.exchangeBootstrapCredentialForAccessToken(link.credential, undefined, metadata, {
proofKeyThumbprint: "device",
})
.pipe(Effect.flip))._tag,
).toBe("ServerAuthInvalidCredentialError");
} else if (action.startsWith("same-key-caller") || action === "other-key-caller") {
if (action === "same-key-caller-connected-expired")
yield* sessions.markConnected(original.sessionId);
if (action.endsWith("expired")) yield* TestClock.adjust(Duration.minutes(61));
const callerToken =
action === "other-key-caller"
? (yield* sessions.issue({ proofKeyThumbprint: "desktop" })).token
: (yield* exchange()).access_token;
const caller = yield* sessions.verify(callerToken);
expect(yield* auth.revokeClientSession(caller.sessionId, original.sessionId)).toBe(true);
const sql = yield* SqlClient.SqlClient;
expect(
yield* sql`SELECT revoked_at FROM auth_sessions WHERE session_id = ${original.sessionId}`,
).toEqual([{ revoked_at: expect.any(String) }]);
const link = yield* auth.createPairingLink({
subject: "cloud-connect",
proofKeyThumbprint: "device",
});
const mint = yield* auth
.exchangeBootstrapCredentialForAccessToken(link.credential, undefined, metadata, {
proofKeyThumbprint: "device",
})
.pipe(Effect.exit);
expect(Exit.isSuccess(mint)).toBe(action !== "other-key-caller");
if (action !== "other-key-caller")
expect((yield* sessions.verify(callerToken)).sessionId).toBe(caller.sessionId);
} else if (action === "individual") {
const sibling = yield* exchange();
yield* sessions.revoke(original.sessionId);
expect(Exit.isFailure(yield* sessions.verify(sibling.access_token).pipe(Effect.exit))).toBe(
true,
);
} else if (action === "individual-connected-expired") {
yield* sessions.markConnected(original.sessionId);
yield* TestClock.adjust(Duration.minutes(61));
const renewed = yield* sessions.verify((yield* exchange()).access_token);
const changes = yield* Queue.unbounded<SessionStore.SessionCredentialChange>();
yield* sessions.streamChanges.pipe(
Stream.runForEach((change) => Queue.offer(changes, change)),
Effect.forkScoped({ startImmediately: true }),
);
yield* sessions.revoke(renewed.sessionId);
const sql = yield* SqlClient.SqlClient;
expect(
yield* sql`SELECT revoked_at FROM auth_sessions WHERE session_id = ${original.sessionId}`,
).toEqual([{ revoked_at: expect.any(String) }]);
expect([yield* Queue.take(changes), yield* Queue.take(changes)]).toEqual(
expect.arrayContaining([
{ type: "clientRemoved", sessionId: original.sessionId },
{ type: "clientRemoved", sessionId: renewed.sessionId },
]),
);
expect(
(yield* sessions.listActive()).some(
(session) => session.sessionId === original.sessionId,
),
).toBe(false);
} else {
yield* (yield* SessionHooks).checkExchange("device", { method: "one-time-token" });
yield* sessions.revoke(original.sessionId);
Expand All @@ -259,7 +351,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
}).pipe(Effect.scoped, Effect.provide(layer)),
);

it.effect.each(["wrong-link", "spent"] as const)("repair guard: %s", (guard) =>
it.effect.each([
"wrong-link",
"spent",
"bulk-after-repair",
"issued-before-revoke",
"issued-before-revoke-at-expiry",
"issued-before-bulk",
] as const)("repair guard: %s", (guard) =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const sql = yield* SqlClient.SqlClient;
Expand All @@ -275,14 +374,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
),
),
);
const first = yield* sessions.issue({ proofKeyThumbprint: "device" });
yield* sessions.revoke(first.sessionId);
yield* hooks.recordRepair("device", "A");
const bulkFromDesktop = sessions
.issue({ proofKeyThumbprint: "desktop" })
.pipe(Effect.flatMap((desktop) => sessions.revokeAllExcept(desktop.sessionId)));
const first = yield* sessions.issue({ proofKeyThumbprint: "device", ttl: Duration.hours(1) });
const issuedBefore = guard.startsWith("issued-before");
if (issuedBefore) yield* hooks.recordRepair("device", "A");
if (guard === "issued-before-revoke-at-expiry") yield* TestClock.adjust(Duration.hours(1));
if (guard === "issued-before-bulk") yield* bulkFromDesktop;
else yield* sessions.revoke(first.sessionId);
if (!issuedBefore) yield* hooks.recordRepair("device", "A");
const grant = { method: "one-time-token", proofKeyThumbprint: "device", pairingLinkId: "A" };
if (guard === "spent") {
expect(yield* hooks.checkExchange("device", grant)).toBe(true);
const next = yield* sessions.issue({ proofKeyThumbprint: "device" });
yield* sessions.revoke(next.sessionId);
} else if (guard === "bulk-after-repair") {
expect(yield* hooks.checkExchange("device", grant)).toBe(true);
yield* bulkFromDesktop;
}
expect(
yield* hooks.checkExchange("device", {
Expand Down Expand Up @@ -390,9 +499,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
}).pipe(Effect.provide(layer)),
);

it.effect(
"blocks fresh cloud mints after revoke until an owner uses a bound repair pairing",
() =>
it.effect.each(["individual", "bulk-expired"] as const)(
"blocks fresh cloud mints after %s revoke until an owner uses a bound repair pairing",
(revocation) =>
Effect.gen(function* () {
const auth = yield* EnvironmentAuth.EnvironmentAuth;
const sessions = yield* SessionStore.SessionStore;
Expand All @@ -411,7 +520,25 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Kin proof key se
});
const first = yield* exchange((yield* mint()).credential);
const issued = yield* sessions.verify(first.access_token);
yield* sessions.revoke(issued.sessionId);
if (revocation === "individual") yield* sessions.revoke(issued.sessionId);
else {
yield* TestClock.adjust(Duration.minutes(61));
const desktop = yield* exchange(
(yield* mint("cloud-connect", "desktop")).credential,
"desktop",
);
const caller = yield* exchange(
(yield* mint("cloud-connect", "desktop")).credential,
"desktop",
);
yield* auth.revokeOtherClientSessions(
(yield* sessions.verify(caller.access_token)).sessionId,
);
expect(
Exit.isFailure(yield* sessions.verify(desktop.access_token).pipe(Effect.exit)),
).toBe(true);
yield* exchange((yield* mint("cloud-connect", "desktop")).credential, "desktop");
}
const denied = yield* exchange((yield* mint()).credential).pipe(Effect.exit);
expect(Exit.isFailure(denied)).toBe(true);
const unboundRepair = yield* auth.createPairingLink({ subject: "one-time-token" });
Expand Down
48 changes: 38 additions & 10 deletions apps/server/src/kin/auth/ProofKeySessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,23 @@ import * as KinEnabled from "../KinEnabled.ts";
import * as KinPersistence from "../persistence/KinPersistence.ts";
import { SessionHooks } from "./sessionHooks.ts";

// `individually_revoked`: 0 none; 1 blocks only if `revoked_at <= expires_at`; 2 blocks unconditionally
// (bulk sign-out, or a revoke that killed an active session).
const GUARDED_BLOCK = 1;
const UNCONDITIONAL_BLOCK = 2;

const enabled = Layer.effect(
SessionHooks,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const blocked = Effect.fn("ProofKeySessions.blocked")(
function* (thumbprint: string) {
// Readers of `individually_revoked` test `!= 0` and apply the expiry guard only to 1.
const rows =
yield* sql`SELECT 1 FROM kin_auth_session_keys m JOIN auth_sessions s ON s.session_id = m.session_id
WHERE m.proof_key_thumbprint = ${thumbprint} AND m.individually_revoked = 1 AND m.repaired_at IS NULL
AND s.revoked_at IS NOT NULL AND s.revoked_at <= s.expires_at LIMIT 1`;
WHERE m.proof_key_thumbprint = ${thumbprint} AND m.repaired_at IS NULL AND s.revoked_at IS NOT NULL
AND m.individually_revoked != 0
AND (m.individually_revoked != ${GUARDED_BLOCK} OR s.revoked_at <= s.expires_at) LIMIT 1`;
return rows.length > 0;
},
Effect.mapError(toPersistenceSqlError("ProofKeySessions.blocked")),
Expand Down Expand Up @@ -91,7 +98,7 @@ const enabled = Layer.effect(
AND consumed_at IS NULL RETURNING pairing_link_id`;
if (repairs.length > 0)
yield* sql`UPDATE kin_auth_session_keys SET repaired_at = ${now.epochMilliseconds}
WHERE proof_key_thumbprint = ${thumbprint} AND individually_revoked = 1
WHERE proof_key_thumbprint = ${thumbprint} AND individually_revoked != 0
AND session_id IN (SELECT session_id FROM auth_sessions WHERE revoked_at IS NOT NULL)`;
}
return !(yield* blocked(thumbprint));
Expand All @@ -110,25 +117,46 @@ const enabled = Layer.effect(
next.delete(sessionId);
return next;
}).pipe(Effect.andThen(notifications.emitRemoved(sessionId)));
const revoke = (sessionId: AuthSessionId, bulk: boolean) =>
const revoke = (sessionId: AuthSessionId, bulk: boolean, callerSessionId?: AuthSessionId) =>
sql
.withTransaction(
Effect.gen(function* () {
const now = yield* DateTime.now;
// Upstream keeps an expired session active while it stays connected.
const connected = sql.in([
...(yield* Ref.get(notifications.connectedSessionsRef)).keys(),
]);
const active = sql`SELECT session_id FROM auth_sessions WHERE expires_at >= ${DateTime.formatIso(now)} OR session_id IN ${connected}`;
const keyOf = (id: AuthSessionId | null) =>
sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${id}`;
const caller = bulk ? sessionId : (callerSessionId ?? null);
// A caller never signs itself out or blocks the key it is signed in with.
const notCallerKey = sql`proof_key_thumbprint IS NOT (${keyOf(caller)})`;
const selected = bulk
? sql<{
session_id: AuthSessionId;
}>`SELECT session_id FROM auth_sessions WHERE session_id != ${sessionId} AND revoked_at IS NULL`
: sql<{
session_id: AuthSessionId;
}>`SELECT s.session_id FROM auth_sessions s LEFT JOIN kin_auth_session_keys m ON m.session_id = s.session_id
WHERE s.revoked_at IS NULL AND (s.session_id = ${sessionId} OR (s.expires_at > ${DateTime.formatIso(now)} AND m.proof_key_thumbprint = (SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId})))`;
WHERE s.revoked_at IS NULL AND s.session_id IS NOT ${caller} AND (s.session_id = ${sessionId}
OR (m.proof_key_thumbprint = (${keyOf(sessionId)}) AND s.session_id IN (${active})))`;
const blockedKeys = bulk
? sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys
WHERE session_id != ${sessionId} AND ${notCallerKey}`
: sql`SELECT proof_key_thumbprint FROM kin_auth_session_keys
WHERE session_id IN (${selected}) AND individually_revoked = ${UNCONDITIONAL_BLOCK} AND ${notCallerKey}`;
if (bulk) {
yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = 1 WHERE session_id IN (SELECT session_id FROM auth_sessions WHERE session_id != ${sessionId} AND revoked_at IS NULL AND expires_at > ${DateTime.formatIso(now)})
AND proof_key_thumbprint != COALESCE((SELECT proof_key_thumbprint FROM kin_auth_session_keys WHERE session_id = ${sessionId}), '')`;
yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = ${UNCONDITIONAL_BLOCK}, repaired_at = NULL
WHERE proof_key_thumbprint IN (${blockedKeys})`;
} else {
yield* sql`UPDATE kin_auth_session_keys SET individually_revoked = 1 WHERE session_id = ${sessionId} AND EXISTS (SELECT 1 FROM auth_sessions WHERE session_id = ${sessionId} AND revoked_at IS NULL)`;
yield* sql`UPDATE kin_auth_session_keys SET individually_revoked =
CASE WHEN session_id IN (${active}) THEN ${UNCONDITIONAL_BLOCK} ELSE ${GUARDED_BLOCK} END
WHERE session_id IN (${selected}) AND ${notCallerKey}`;
}
// A repair link issued before this block must not lift it.
yield* sql`UPDATE kin_auth_key_repairs SET consumed_at = ${now.epochMilliseconds}
WHERE consumed_at IS NULL AND thumbprint IN (${blockedKeys})`;
return yield* sql<{
session_id: AuthSessionId;
}>`UPDATE auth_sessions SET revoked_at = ${DateTime.formatIso(now)} WHERE session_id IN (${selected}) AND revoked_at IS NULL RETURNING session_id`;
Expand Down Expand Up @@ -179,8 +207,8 @@ const enabled = Layer.effect(
),
);
}),
revoke: Effect.fn("ProofKeySessions.revoke")((sessionId) =>
revoke(sessionId, false).pipe(
revoke: Effect.fn("ProofKeySessions.revoke")((sessionId, callerSessionId) =>
revoke(sessionId, false, callerSessionId).pipe(
Effect.map((ids) => ids.some((row) => row.session_id === sessionId)),
Effect.mapError(
(cause) =>
Expand Down
Loading