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
3 changes: 2 additions & 1 deletion .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ on:
- cron: "0 8 * * 3"
workflow_dispatch:

permissions: read-all
permissions:
contents: read

jobs:
analyze:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish-mcp-registry.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:

- name: Install mcp-publisher
run: |
curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher
curl --proto '=https' --tlsv1.2 -fsSL "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher

- name: Authenticate to MCP Registry
run: ./mcp-publisher login github-oidc
Expand Down
8 changes: 6 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,16 @@ concurrency:

jobs:
publish:
# On workflow_run, only publish if CI passed. Tag pushes and manual
# On workflow_run, only publish if CI passed on a push to main of this repo (never a fork PR whose head branch
# happens to be named main: workflow_run runs with secrets). Tag pushes and manual
# dispatch always run. The version-diff step is the real guard against
# double-publishing: if nothing changed it exits cleanly. Tags no longer trigger a publish; Release creates them.
if: |
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success')
(github.event_name == 'workflow_run' &&
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_repository.full_name == github.repository)
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
Expand Down
10 changes: 6 additions & 4 deletions .github/workflows/release-python.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ on:
workflow_dispatch:

permissions:
contents: write
contents: read

env:
PYTHON_VERSION: "3.11"
Expand All @@ -29,8 +29,8 @@ jobs:
- name: Install dependencies
working-directory: ./sdks/python
run: |
pip install hatch
pip install -e ".[dev]"
pip install --only-binary :all: hatch
pip install --only-binary :all: -e ".[dev]"

- name: Run tests
working-directory: ./sdks/python
Expand All @@ -51,7 +51,7 @@ jobs:
- name: Build and publish
working-directory: ./sdks/python
run: |
pip install hatch
pip install --only-binary :all: hatch
hatch build
hatch publish
env:
Expand All @@ -70,6 +70,8 @@ jobs:
runs-on: ubuntu-latest
needs: [publish]
if: needs.publish.result == 'success'
permissions:
contents: write # create the GitHub release
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7

Expand Down
5 changes: 3 additions & 2 deletions .github/workflows/scorecard.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ on:
- cron: "0 9 * * 2"
workflow_dispatch:

permissions: read-all
permissions:
contents: read

jobs:
analysis:
Expand All @@ -21,7 +22,7 @@ jobs:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: ossf/scorecard-action@v2.4.3
- uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
with:
results_file: results.sarif
results_format: sarif
Expand Down
8 changes: 7 additions & 1 deletion packages/cli/src/agent/inspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,13 @@ export function readEnvVarNames(cwd: string): string[] {
if (m?.[1] && /THEAUTH|AUTH|MCP|DATABASE|SESSION|APP_URL/.test(m[1])) names.add(m[1]);
}
}
return [...names].sort();
return [...names].sort(compareCodeUnits);
}

/** UTF-16 code unit order, the same order a bare `sort()` gives, kept explicit. */
function compareCodeUnits(a: string, b: string): number {
if (a < b) return -1;
return a > b ? 1 : 0;
}

export function inspectProject(cwd: string): InspectReport {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/audit/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

import { and, desc, eq, isNotNull } from "drizzle-orm";
import { compareCodeUnits } from "../compare.js";
import { hmacSha256, sha256 } from "../crypto/web-crypto.js";
import type { Database } from "../db/database.js";
import { auditLogs } from "../db/schema.js";
Expand Down Expand Up @@ -54,7 +55,7 @@ export function canonicalJson(value: unknown): string {
if (typeof value === "object") {
const obj = value as Record<string, unknown>;
const parts: string[] = [];
for (const key of Object.keys(obj).sort()) {
for (const key of Object.keys(obj).sort(compareCodeUnits)) {
if (obj[key] === undefined) continue;
parts.push(`${JSON.stringify(key)}:${canonicalJson(obj[key])}`);
}
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/auth/federated-logout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@
key: VerifyKey,
options: JWTVerifyOptions,
): Promise<JWTVerifyResult> {
return typeof key === "function"
? jwtVerify(token, key, options)
: jwtVerify(token, key, options);
// jose types the static-key and key-resolver forms as separate overloads, so a
// static key is wrapped in a resolver to reach a single call. Verification is identical.
const getKey: JWTVerifyGetKey = typeof key === "function" ? key : async () => key;

Check warning on line 47 in packages/core/src/auth/federated-logout.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Async arrow function has no 'await' expression.

See more on https://sonarcloud.io/project/issues?id=glincker_theauth&issues=AaEm_F-lMufu6bsvWfr3&open=AaEm_F-lMufu6bsvWfr3&pullRequest=194
return jwtVerify(token, getKey, options);
}

// ---------------------------------------------------------------------------
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/auth/oauth-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,7 @@ export function createOAuthProxyModule(
});
} catch (err) {
if (err instanceof OAuthProxyError) {
const status = err.code === "redirect_uri_not_allowed" ? 400 : 400;
return jsonError(err.message, status);
return jsonError(err.message, 400);
}
return jsonError("Failed to start OAuth proxy flow", 500);
}
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/auth/password-reset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -534,8 +534,7 @@ export function createPasswordResetModule(
const result = await resetPassword(b.token, b.password);
if (!result.success) {
// Don't reveal specific error details to the client
const status = result.error.code === "INVALID_PASSWORD" ? 400 : 400;
return jsonResponse({ error: result.error.message }, status);
return jsonResponse({ error: result.error.message }, 400);
}

return new Response(null, { status: 204 });
Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/compare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Compare two strings by UTF-16 code unit order.
*
* This is exactly the order `Array.prototype.sort()` produces without a
* comparator, written out so the ordering is explicit. It is deliberately not
* `localeCompare`: the audit hash chain, SigV4 canonical headers and
* permission fingerprints all depend on a locale-independent, stable order.
*/
export function compareCodeUnits(a: string, b: string): number {
if (a < b) return -1;
return a > b ? 1 : 0;
}
3 changes: 2 additions & 1 deletion packages/core/src/email/ses.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { compareCodeUnits } from "../compare.js";
import { hmacSha256Raw, sha256, toHex } from "../crypto/web-crypto.js";
import type { EmailProvider, EmailSendOptions, EmailSendResult } from "./types.js";

Expand Down Expand Up @@ -69,7 +70,7 @@ export function ses(config: SesConfig): EmailProvider {
};
if (config.sessionToken) headers["x-amz-security-token"] = config.sessionToken;

const names = Object.keys(headers).sort();
const names = Object.keys(headers).sort(compareCodeUnits);
const canonicalHeaders = names.map((n) => `${n}:${headers[n]}\n`).join("");
const signedHeaders = names.join(";");
const canonicalRequest = [
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/policy/rbac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import { and, eq } from "drizzle-orm";
import { compareCodeUnits } from "../compare.js";
import type { Database } from "../db/database.js";
import { orgMembers, orgRoles } from "../db/schema.js";
import type { Permission } from "../types.js";
Expand Down Expand Up @@ -62,7 +63,7 @@ function toPermissions(rawStrings: string[]): Permission[] {
}
return Array.from(map.entries()).map(([resource, actionsSet]) => ({
resource,
actions: Array.from(actionsSet).sort(),
actions: Array.from(actionsSet).sort(compareCodeUnits),
}));
}

Expand All @@ -73,7 +74,7 @@ function deduplicate(permissions: Permission[]): Permission[] {
const seen = new Set<string>();
const result: Permission[] = [];
for (const perm of permissions) {
const key = `${perm.resource}|${[...perm.actions].sort().join(",")}`;
const key = `${perm.resource}|${[...perm.actions].sort(compareCodeUnits).join(",")}`;
if (!seen.has(key)) {
seen.add(key);
result.push(perm);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/simulator/simulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ export function createSimulator(config: { db: Database }) {
const override = input.overrides?.delegationChains;
let chains: ResolvedChain[];
if (override) {
chains = override.map(fromOverride);
chains = override.map((chain, index) => fromOverride(chain, index));
trace.push({
stage: "delegation",
outcome: "info",
Expand Down
67 changes: 67 additions & 0 deletions packages/core/tests/compare.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import { canonicalJson } from "../src/audit/chain.js";
import { compareCodeUnits } from "../src/compare.js";

// Mixed case, digits, punctuation, accents, CJK and an astral code point (a surrogate pair,
// whose UTF-16 order differs from code point order and from localeCompare).
const SAMPLE = [
"b",
"B",
"a",
"A",
"10",
"9",
"_x",
"-x",
"é",
"e",
"z",
"Z",
"日",
"\u{1F600}",
"~",
"",
];

describe("compareCodeUnits", () => {
it("orders exactly like a bare sort() (UTF-16 code unit order)", () => {
expect([...SAMPLE].sort(compareCodeUnits)).toEqual([...SAMPLE].sort());
});

it("is not locale order", () => {
expect(["b", "B", "a", "A"].sort(compareCodeUnits)).toEqual(["A", "B", "a", "b"]);
expect(["a", "B"].sort((x, y) => x.localeCompare(y))).not.toEqual(
["a", "B"].sort(compareCodeUnits),
);
});

it("returns 0 for equal strings", () => {
expect(compareCodeUnits("abc", "abc")).toBe(0);
});
});

describe("canonicalJson key ordering (hash chain input)", () => {
it("sorts keys in code unit order, independent of insertion order", () => {
const a = canonicalJson({ b: 1, B: 2, a: 3, A: 4, é: 5, "10": 6, "9": 7 });
const b = canonicalJson({ "9": 7, é: 5, A: 4, a: 3, B: 2, b: 1, "10": 6 });
expect(a).toBe('{"10":6,"9":7,"A":4,"B":2,"a":3,"b":1,"é":5}');
expect(b).toBe(a);
});

it("matches the pre-comparator output for nested objects and astral keys", () => {
const value = { z: { y: 1, Y: 2 }, "\u{1F600}": 1, "~": 2, a: [{ d: 1, c: 2 }] };
const legacy = (v: unknown): string => {
if (v === null || v === undefined) return "null";
if (Array.isArray(v)) return `[${v.map(legacy).join(",")}]`;
if (typeof v === "object") {
const o = v as Record<string, unknown>;
return `{${Object.keys(o)
.sort()
.map((k) => `${JSON.stringify(k)}:${legacy(o[k])}`)
.join(",")}}`;
}
return JSON.stringify(v);
};
expect(canonicalJson(value)).toBe(legacy(value));
});
});
56 changes: 56 additions & 0 deletions packages/core/tests/federated-logout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { SignJWT } from "jose";
import { describe, expect, it } from "vitest";
import {
BACKCHANNEL_LOGOUT_EVENT,
createBackChannelLogoutReceiver,
} from "../src/auth/federated-logout.js";

const secret = new TextEncoder().encode("0123456789abcdef0123456789abcdef");
const ISS = "https://idp.example.com";
const AUD = "client-1";

async function logoutToken(jti: string): Promise<string> {
return new SignJWT({ sub: "user-1", events: { [BACKCHANNEL_LOGOUT_EVENT]: {} } })
.setProtectedHeader({ alg: "HS256", typ: "logout+jwt" })
.setIssuer(ISS)
.setAudience(AUD)
.setIssuedAt()
.setJti(jti)
.sign(secret);
}

describe("back-channel logout token verification key forms", () => {
it("accepts a static key", async () => {
const receiver = createBackChannelLogoutReceiver({
issuer: ISS,
clientId: AUD,
verificationKey: secret,
algorithms: ["HS256"],
});
const result = await receiver.verifyLogoutToken(await logoutToken("static-1"));
expect(result.success).toBe(true);
if (result.success) expect(result.data.sub).toBe("user-1");
});

it("accepts a key resolver", async () => {
const receiver = createBackChannelLogoutReceiver({
issuer: ISS,
clientId: AUD,
verificationKey: async () => secret,
algorithms: ["HS256"],
});
const result = await receiver.verifyLogoutToken(await logoutToken("resolver-1"));
expect(result.success).toBe(true);
});

it("rejects a token signed with a different key", async () => {
const receiver = createBackChannelLogoutReceiver({
issuer: ISS,
clientId: AUD,
verificationKey: new TextEncoder().encode("fedcba9876543210fedcba9876543210"),
algorithms: ["HS256"],
});
const result = await receiver.verifyLogoutToken(await logoutToken("wrong-1"));
expect(result.success).toBe(false);
});
});
4 changes: 2 additions & 2 deletions packages/core/tests/rate-limit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,10 +308,10 @@ describe("rateLimit() plugin — window string parsing", () => {
vi.useRealTimers();
});

it("throws on invalid window string", () => {
it("throws on invalid window string", async () => {
// The error is thrown lazily when the first request hits the endpoint
const plugin = rateLimit({ default: { window: "invalid", max: 5 } });
expect(runHook(plugin, makeRequest("/auth/sign-in", "50.0.0.1"))).rejects.toThrow(
await expect(runHook(plugin, makeRequest("/auth/sign-in", "50.0.0.1"))).rejects.toThrow(
/Invalid rate limit window/,
);
});
Expand Down
Loading