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
2 changes: 1 addition & 1 deletion apps/mobile/modules/kin-approval-key/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ import { stableStringify } from "./src/relaySigning.ts";
const b = (o) => Buffer.from(stableStringify(o)).toString("base64url");
const now = Math.floor(Date.now() / 1000);
const header = { alg: "ES256", kid: "test", typ: "kin-grant+jws" };
const payload = { v: 1, orgId: "org", actionId: "act_test", revision: 0, nonce: "n", jti: crypto.randomUUID(),
const payload = { v: 1, orgId: "org", actionId: "act_test", revision: 0, nonce: "n".repeat(43), jti: crypto.randomUUID(),
kind: "merge_pull_request", targetDigest: "0".repeat(64), headSha: "a1b2c3d".padEnd(40, "0"), base: "main",
mergeMethod: "squash", target: { _tag: "pull_request", host: "github.com", repo: "GLDRoger/t3code", number: 212,
mergeMethod: "squash", deleteBranchAfter: false }, approver: { humanId: "h", kid: "test" }, decision: "approve",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ static final class NotAGrantException extends Exception {
/** Lead and chat ids: letters, digits and {@code . _ -}. */
private static final Pattern ID = Pattern.compile("[A-Za-z0-9._-]+");
private static final Pattern THUMBPRINT = Pattern.compile("[A-Za-z0-9_-]{43}");
// Spec section 5: a jti is 16+ random bytes, a nonce exactly 32, as unpadded base64url.
private static final Pattern JTI = Pattern.compile("[A-Za-z0-9_-]{22,}");
private static final Pattern NONCE = Pattern.compile("[A-Za-z0-9_-]{43}");

private static final Set<String> PAYLOAD_REQUIRED = setOf(
"v", "orgId", "actionId", "revision", "nonce", "jti", "kind", "targetDigest", "target",
Expand Down Expand Up @@ -81,7 +84,9 @@ private static String promptFor(Map<String, Object> p, String kid, long now) thr
exactKeys(p, PAYLOAD_REQUIRED, setOf("headSha", "base", "mergeMethod"), "payload");
if (integer(p, "v") != 1) throw new NotAGrantException("v is not 1");
if (!"approve".equals(p.get("decision"))) throw new NotAGrantException("decision is not approve");
for (String key : new String[] {"orgId", "actionId", "nonce", "jti"}) nonEmpty(p, key);
for (String key : new String[] {"orgId", "actionId"}) nonEmpty(p, key);
matches(p, "jti", JTI);
matches(p, "nonce", NONCE);
if (integer(p, "revision") < 0) throw new NotAGrantException("revision is negative");
matches(p, "targetDigest", HEX64);
Map<String, Object> approver = child(p, "approver");
Expand Down
248 changes: 145 additions & 103 deletions apps/mobile/modules/kin-approval-key/fixtures/grant-vectors.json

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion apps/mobile/modules/kin-approval-key/ios/KinGrant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ enum KinGrant {
try exactKeys(p, payloadRequired, payloadOptional, "payload")
guard try integer(p, "v") == 1 else { throw NotAGrant("v is not 1") }
guard try string(p, "decision") == "approve" else { throw NotAGrant("decision is not approve") }
for key: Bytes in ["orgId", "actionId", "nonce", "jti"] { try nonEmpty(p, key) }
for key: Bytes in ["orgId", "actionId"] { try nonEmpty(p, key) }
// Spec section 5: a jti is 16+ random bytes, a nonce exactly 32, as unpadded base64url.
try base64Url(p, "jti", length: 22...Int.max)
try base64Url(p, "nonce", length: 43...43)
guard try integer(p, "revision") >= 0 else { throw NotAGrant("revision is negative") }
_ = try hex(p, "targetDigest", length: 64)
let approver = try child(p, "approver")
Expand Down Expand Up @@ -204,6 +207,13 @@ enum KinGrant {
guard try !string(map, key).utf8.isEmpty else { throw NotAGrant("\(key) is empty") }
}

private static func base64Url(_ map: [Bytes: Value], _ key: Bytes, length: ClosedRange<Int>) throws {
let value = try string(map, key).utf8
guard length.contains(value.count), value.allSatisfy(isBase64UrlByte) else {
throw NotAGrant("\(key) is malformed")
}
}

private static func hex(_ map: [Bytes: Value], _ key: Bytes, length: Int) throws -> String {
let value = try string(map, key).utf8
let lowerHex = value.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }
Expand Down
62 changes: 62 additions & 0 deletions apps/server/src/kin/approvals/GrantVerifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -893,6 +893,68 @@ describe("GrantVerifier", () => {
}).pipe(Effect.provide(h.layer));
});

it.effect("check 10's refusals carry the action's facts and spend the verified budget", () => {
const h = harness();
return Effect.gen(function* () {
const { grants, actions, ownerKey } = yield* enrol;
const loseAtCheck10 = Effect.fn(function* (number: number, moveHead = false) {
const action = yield* requestMerge(actions, number, h.github);
const compact = yield* signFor(grants, ownerPhone, action, signerOf(ownerKey));
// A concurrent refresh moves the row to a head the owner never signed.
const resolved =
action.resolved._tag === "none"
? action.resolved
: { ...action.resolved, headSha: sha("c") };
h.race.during = moveHead
? actions
.refresh({
orgId,
actionId: action.id,
revision: 0,
resolved,
targetDigest: kinTargetDigest(action.kind, action.target, resolved),
})
.pipe(Effect.orDie)
: actions
.transition({ orgId, actionId: action.id, revision: 0, to: "rejected" })
.pipe(Effect.orDie);
const exit = yield* Effect.exit(grants.submitGrant(ownerPhone, { compact }));
delete h.race.during;
assert.strictEqual(reasonOf(exit), "stale");
return action;
});
const rejections = () =>
h.audit.filter(
(entry) => entry.event === "grant_rejected" && entry.sessionId !== undefined,
);

const first = yield* loseAtCheck10(300, true);
assert.include(rejections()[0], {
actionId: first.id,
kind: "merge_pull_request",
headSha: sha("b"),
result: "stale",
});
// An approval hands its reserved slot back.
const approved = yield* requestMerge(actions, 303, h.github);
yield* grants.submitGrant(ownerPhone, {
compact: yield* signFor(grants, ownerPhone, approved, signerOf(ownerKey)),
});
// Check 6's refusals fill the rest of the same budget.
const gone = yield* requestMerge(actions, 301, h.github);
const late = yield* signFor(grants, ownerPhone, gone, signerOf(ownerKey));
yield* actions.transition({ orgId, actionId: gone.id, revision: 0, to: "rejected" });
for (let attempt = 0; attempt < 19; attempt++) {
yield* Effect.exit(grants.submitGrant(ownerPhone, { compact: late }));
}
assert.strictEqual(rejections().length, 20);
yield* loseAtCheck10(302);
assert.strictEqual(rejections().length, 20);
yield* TestClock.adjust("1 minute");
assert.strictEqual(rejections().at(-1)?.result, "1 more not recorded");
}).pipe(Effect.provide(h.layer));
});

it.effect(
"revoking a relay phone's renewed session rejects its key's grants, even mid-check",
() => {
Expand Down
81 changes: 54 additions & 27 deletions apps/server/src/kin/approvals/GrantVerifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
Expand All @@ -35,17 +36,17 @@ import { KinPendingActions, kinTargetDigest } from "./PendingActions.ts";
// the budget that records forgeries against a real key. Past the budget, rejections are counted.
const AUDITS_PER_WINDOW = 20;
const JUNK_WINDOW = Duration.minutes(1);
const auditBucket = (reason: KinApprovalError["reason"], signatureVerified: boolean) =>
type AuditBucket = "signed" | "junk" | "names_key";
const auditBucket = (
reason: KinApprovalError["reason"],
signatureVerified: boolean,
): AuditBucket =>
signatureVerified
? "signed"
: reason === "malformed" || reason === "unknown_key"
? "junk"
: "names_key";

// A jti is 16+ random bytes (spec section 5): 22 unpadded base64url characters. Kept out of the
// shared decoder so it stays byte-for-byte with the device's parser.
const MIN_JTI_CHARS = 22;

const isKinApprovalError = Schema.is(KinApprovalError);
const decodeUnsigned = Schema.decodeUnknownEffect(KinGrantUnsignedPayload);

Expand Down Expand Up @@ -206,7 +207,6 @@ const make = Effect.gen(function* () {
keyThumbprint: header.kid,
...(payload.headSha === undefined ? {} : { headSha: payload.headSha }),
};
if (payload.jti.length < MIN_JTI_CHARS) return yield* reject("malformed");

// 2. An active key in the grant's org, after session revocations.
const key = yield* keys.requireActive({ orgId: payload.orgId, thumbprint: header.kid });
Expand Down Expand Up @@ -273,26 +273,43 @@ const make = Effect.gen(function* () {
}
}

// 10. Grant row and CAS in one transaction, against the row's own org and nonce.
const result = yield* actions.approve({
orgId: action.orgId,
actionId: action.id,
revision: action.revision,
nonce: action.nonce,
jti: payload.jti,
approverHumanId: key.humanId,
keyThumbprint: key.thumbprint,
compact,
iat: payload.iat,
exp: payload.exp,
sessionId: caller.session.sessionId,
// 10. Grant row and CAS in one transaction, against the row's own org and nonce. A refusal
// here spends the verified-grant budget like any other; the slot is handed back on approval.
const window = yield* auditWindow(action.orgId, caller.session.sessionId, "signed");
const auditRefusal = window.used < AUDITS_PER_WINDOW;
if (auditRefusal) window.used += 1;
const release = Effect.sync(() => {
if (auditRefusal) window.used -= 1;
});
if (result._tag !== "approved") {
// `approve` already wrote this refusal's `grant_rejected` on the action's own chain.
seen.audited = true;
return yield* reject(result._tag);
}
return { action, grant: result.grant };
const result = yield* actions
.approve({
orgId: action.orgId,
actionId: action.id,
revision: action.revision,
nonce: action.nonce,
jti: payload.jti,
approverHumanId: key.humanId,
keyThumbprint: key.thumbprint,
compact,
iat: payload.iat,
exp: payload.exp,
sessionId: caller.session.sessionId,
auditRefusal,
...(payload.headSha === undefined ? {} : { headSha: payload.headSha }),
})
.pipe(
// Only a refusal keeps its slot; approval, failure and interruption hand it back.
Effect.onExit((exit) =>
Exit.isSuccess(exit) && exit.value._tag !== "approved" ? Effect.void : release,
),
);
if (result._tag === "approved") return { action, grant: result.grant };
// `approve` wrote this refusal's `grant_rejected` on the action's own chain, or counted it.
// Re-read the window: the one checked above may have closed while `approve` ran.
if (!auditRefusal)
(yield* auditWindow(action.orgId, caller.session.sessionId, "signed")).skipped += 1;
seen.audited = true;
return yield* reject(result._tag);
});

/** The window's skipped count is written when it ends, or when the server stops. */
Expand All @@ -317,6 +334,13 @@ const make = Effect.gen(function* () {
);
};

const auditWindow = (orgId: KinOrgId, sessionId: AuthSessionId, bucket: AuditBucket) =>
Effect.suspend(() => {
const slot = `${orgId} ${sessionId} ${bucket}`;
const window = junkWindows.get(slot);
return window === undefined ? openJunkWindow(slot, orgId, sessionId) : Effect.succeed(window);
});

const recordRejection = Effect.fn("GrantVerifier.recordRejection")(function* (
caller: KinKeyCaller,
seen: Seen,
Expand All @@ -342,8 +366,11 @@ const make = Effect.gen(function* () {
sessionId,
result: error.reason,
};
const slot = `${orgId} ${sessionId} ${auditBucket(error.reason, seen.orgId !== undefined)}`;
const window = junkWindows.get(slot) ?? (yield* openJunkWindow(slot, orgId, sessionId));
const window = yield* auditWindow(
orgId,
sessionId,
auditBucket(error.reason, seen.orgId !== undefined),
);
if (window.used >= AUDITS_PER_WINDOW) {
window.skipped += 1;
return;
Expand Down
17 changes: 13 additions & 4 deletions apps/server/src/kin/approvals/PendingActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,10 @@ export class KinPendingActions extends Context.Service<
readonly exp: number;
readonly sessionId?: AuthSessionId;
readonly deviceLabel?: string;
/** False when the caller's audit budget is spent: a refusal is then not written. */
readonly auditRefusal?: boolean;
/** The head the grant signed; a refusal records it, not the row's possibly newer head. */
readonly headSha?: string;
},
) => Effect.Effect<KinApproveResult, Errors>;
/** Whether the org already holds this `jti`, or this approver's grant for the action. */
Expand Down Expand Up @@ -435,6 +439,8 @@ const make = Effect.gen(function* () {
readonly exp: number;
readonly sessionId?: AuthSessionId;
readonly deviceLabel?: string;
readonly auditRefusal?: boolean;
readonly headSha?: string;
},
) {
const now = yield* Clock.currentTimeMillis;
Expand Down Expand Up @@ -504,17 +510,20 @@ const make = Effect.gen(function* () {
);
// A refused grant still leaves a trace (spec section 11), but only on the chain of the org
// that owns the action: an unknown org or action stays `stale` and writes nothing.
if (result._tag !== "approved") {
if (result._tag !== "approved" && input.auditRefusal !== false) {
yield* sql
.withTransaction(
Effect.gen(function* () {
const [owned] = yield* sql`SELECT 1 FROM kin_pending_actions
WHERE org_id = ${input.orgId} AND action_id = ${input.actionId}`;
const [owned] = yield* sql<FactsRow>`SELECT action_id, kind, resolved_json
FROM kin_pending_actions
WHERE org_id = ${input.orgId} AND action_id = ${input.actionId}`;
if (owned === undefined) return;
const { headSha: _rowHead, ...facts } = yield* auditFacts(owned);
yield* audit.append({
orgId: input.orgId,
event: "grant_rejected",
actionId: input.actionId,
...facts,
...(input.headSha === undefined ? {} : { headSha: input.headSha }),
...who,
result: result._tag,
});
Expand Down
2 changes: 1 addition & 1 deletion docs/kin/specs/approvals.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ export const KinGrantPayload = Schema.Struct({

`kin.approvals.submitGrant({compact})` checks, in this order, and stops at the first failure with a typed reason:

1. Decode header and payload; `alg`, `typ`, no `jwk`; each part's bytes equal `stableStringify(JSON.parse(bytes))`; `jti` is at least 16 bytes (22 base64url characters) → `malformed`.
1. Decode header and payload; `alg`, `typ`, no `jwk`; each part's bytes equal `stableStringify(JSON.parse(bytes))`; `jti` is at least 16 bytes (22 base64url characters) and `nonce` is 32 bytes (43 characters) → `malformed`. The device parsers refuse the same.
2. `kid` is an `active` and attested key in `payload.orgId`, and `payload.approver.kid` equals it → `unknown_key` / `revoked_key`. An unattested key never activates, so one found active means the database was edited; it fails `unknown_key`.
3. Signature verifies with `p256.verify(sig, sha256(signingInput), key, {prehash: false, format: "compact", lowS: true})` → `bad_signature`. Unlike `verifyDpopProof`, `lowS: true` is required: the device always sends low-S, and ECDSA's `(r, n − s)` twin of a signature would otherwise also verify. Never identify or deduplicate a grant by its compact string; `jti` is its identity, and `compact` is kept for audit only.
4. `approver.humanId` equals the key's `humanId`, and that person currently meets a `requiredApprovers` entry (phase 1: holds the owner role in the org) → `not_owner`.
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/src/kinGrant.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function grantFor(kid: string, overrides: Partial<KinGrantPayload> = {}) {
orgId: "org_01",
actionId: "act_01JD7Z00000000000000000000",
revision: 2,
nonce: "c2VydmVyLW5vbmNlLTMyLWJ5dGVzLWJhc2U2NHVybA",
nonce: "a2luLXNlcnZlci1ub25jZS1vZi0zMi1ieXRlcy1iNjQ",
jti: "ZGV2aWNlLWp0aS0xNi1ieXRlcw",
kind: "merge_pull_request",
targetDigest: "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
Expand Down
4 changes: 4 additions & 0 deletions packages/shared/src/kinGrant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import { stableStringify } from "./relaySigning.ts";

const MAX_COMPACT_LENGTH = 16_384;
const BASE64URL = /^[A-Za-z0-9_-]+$/;
// Spec section 5: a jti is 16+ random bytes, a nonce exactly 32. The device parsers check the same.
const JTI = /^[A-Za-z0-9_-]{22,}$/;
const NONCE = /^[A-Za-z0-9_-]{43}$/;
const strict = { onExcessProperty: "error" } as const;
const decodeHeader = Schema.decodeUnknownExit(KinGrantHeader, strict);
const decodePayload = Schema.decodeUnknownExit(KinGrantPayload, strict);
Expand Down Expand Up @@ -69,6 +72,7 @@ export function decodeKinGrant(compact: string): DecodedKinGrant | null {
const payload = decodePayload(canonicalJson(payloadPart));
const signature = strictBase64Url(signaturePart);
if (Exit.isFailure(header) || Exit.isFailure(payload) || signature?.length !== 64) return null;
if (!JTI.test(payload.value.jti) || !NONCE.test(payload.value.nonce)) return null;
const signingInput = `${headerPart}.${payloadPart}`;
// A schema that trims or otherwise transforms a value would make the decoded grant differ from
// the signed bytes; one signed string must have exactly one meaning.
Expand Down