Skip to content
Closed
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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,8 @@ OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local

Google ID tokens are RS256-signed JWTs. The discovery document advertises RS256, and `/oauth2/v3/certs` returns the matching RSA public key used to verify issued tokens.

The token endpoint accepts the client's credentials in the request body (`client_secret_post`) or in an HTTP Basic `Authorization` header (`client_secret_basic`), the two methods Google's discovery document lists. With OAuth clients configured, a request whose body credentials do not match the header returns `400 invalid_request`.

Google authentication is permissive by default for local bearer-token workflows. Set `google.strict_scopes: true` in seed config to require emulator-issued, unexpired access tokens on Gmail, Calendar, Drive, and userinfo routes. Invalid credentials return `401 UNAUTHENTICATED`; missing method scopes return `403` with `insufficientPermissions`. Strict mode distinguishes read, write, send, settings, and metadata scopes, and userinfo includes only granted identity claims. Revoking an access or refresh token invalidates the linked access and refresh credentials. Discovery, signing keys, and the sign-in page remain public. This mode checks method scopes; resource-specific grants such as `drive.file` and Gmail add-on scopes are not modeled.

- `GET /o/oauth2/v2/auth` - authorization endpoint
Expand Down
2 changes: 2 additions & 0 deletions apps/web/content/docs/google.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local

Google ID tokens are RS256-signed JWTs. The discovery document advertises RS256, and the JWKS endpoint returns the matching RSA public key used to verify issued tokens.

The token endpoint accepts the client's credentials in the request body (`client_secret_post`) or in an HTTP Basic `Authorization` header (`client_secret_basic`), the two methods Google's discovery document lists. With OAuth clients configured, a request whose body credentials do not match the header returns `400 invalid_request`.

Google authentication is permissive by default for local bearer-token workflows. Set `google.strict_scopes: true` in seed config to require emulator-issued, unexpired access tokens on Gmail, Calendar, Drive, and userinfo routes. Invalid credentials return `401 UNAUTHENTICATED`; missing method scopes return `403` with `insufficientPermissions`. Strict mode distinguishes read, write, send, settings, and metadata scopes, and userinfo includes only granted identity claims. Revoking an access or refresh token invalidates the linked access and refresh credentials. Discovery, signing keys, and the sign-in page remain public. This mode checks method scopes; resource-specific grants such as `drive.file` and Gmail add-on scopes are not modeled.

## Gmail
Expand Down
2 changes: 1 addition & 1 deletion packages/@emulators/google/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ npm install @emulators/google

## Auth

Standard OAuth 2.0 authorization code flow with RS256-signed OIDC ID tokens. Configure clients in the seed config. The discovery document advertises RS256 and `/oauth2/v3/certs` returns the RSA public key used to verify issued ID tokens.
Standard OAuth 2.0 authorization code flow with RS256-signed OIDC ID tokens. Configure clients in the seed config. The token endpoint accepts the client's credentials in the request body (`client_secret_post`) or in an HTTP Basic `Authorization` header (`client_secret_basic`), the two methods Google's discovery document lists. With OAuth clients configured, a request whose body credentials do not match the header returns `400 invalid_request`. The discovery document advertises RS256 and `/oauth2/v3/certs` returns the RSA public key used to verify issued ID tokens.

## Seed Configuration

Expand Down
131 changes: 131 additions & 0 deletions packages/@emulators/google/src/__tests__/token-client-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { describe, expect, it } from "vitest";
import { Hono, Store, WebhookDispatcher, authMiddleware, type AppEnv, type TokenMap } from "@emulators/core";
import { googlePlugin, seedFromConfig } from "../index.js";

const base = "http://localhost:4000";
const client = { client_id: "123-abc.apps.googleusercontent.com", client_secret: "GOCSPX-a+b/c=d" };
const redirectUri = "http://127.0.0.1:8080/";
const email = "admin@example.com";

function fixture() {
const app = new Hono<AppEnv>();
const store = new Store();
const tokens: TokenMap = new Map();
app.use("*", authMiddleware(tokens));
googlePlugin.register(app, store, new WebhookDispatcher(), base, tokens);
googlePlugin.seed?.(store, base);
seedFromConfig(store, base, {
strict_scopes: true,
users: [{ email, name: "Ada Admin" }],
oauth_clients: [{ ...client, redirect_uris: [redirectUri] }],
});

const form = (path: string, body: Record<string, string>, headers: Record<string, string> = {}) =>
app.request(`${base}${path}`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded", ...headers },
body: new URLSearchParams(body).toString(),
});

async function code(): Promise<string> {
const authorize = await form("/o/oauth2/v2/auth/callback", {
email,
redirect_uri: redirectUri,
scope: "openid email",
client_id: client.client_id,
});
return new URL(authorize.headers.get("Location")!).searchParams.get("code")!;
}

return { form, code };
}

// RFC 6749, section 2.3.1: each credential is form-urlencoded, then joined with a colon and base64-encoded.
const basic = (id: string, secret: string) =>
`Basic ${Buffer.from(`${encodeURIComponent(id)}:${encodeURIComponent(secret)}`).toString("base64")}`;

describe("Google token endpoint client authentication", () => {
it("accepts client credentials in an HTTP Basic Authorization header", async () => {
const { form, code } = fixture();
const exchange = await form(
"/oauth2/token",
{ grant_type: "authorization_code", code: await code(), redirect_uri: redirectUri },
{ Authorization: basic(client.client_id, client.client_secret) },
);
expect(exchange.status).toBe(200);
const tokens = (await exchange.json()) as { refresh_token: string };

const refreshed = await form(
"/oauth2/token",
{ grant_type: "refresh_token", refresh_token: tokens.refresh_token },
{ Authorization: basic(client.client_id, client.client_secret) },
);
expect(refreshed.status).toBe(200);
});

it("refuses a wrong secret or an unknown client in the header", async () => {
const { form, code } = fixture();
for (const header of [basic(client.client_id, "GOCSPX-wrong"), basic("unknown", client.client_secret)]) {
const exchange = await form(
"/oauth2/token",
{ grant_type: "authorization_code", code: await code(), redirect_uri: redirectUri },
{ Authorization: header },
);
expect(exchange.status).toBe(401);
// Google's token endpoint sends no WWW-Authenticate challenge here, despite RFC 6749 section 5.2.
expect(exchange.headers.get("WWW-Authenticate")).toBeNull();
expect(await exchange.json()).toMatchObject({ error: "invalid_client" });
}
});

it("refuses body credentials that do not match the header", async () => {
const { form, code } = fixture();
const mismatches: Record<string, string>[] = [
{ client_id: client.client_id, client_secret: "GOCSPX-other" },
{ client_secret: "GOCSPX-other" },
{ client_secret: client.client_secret },
{ client_id: "123-other.apps.googleusercontent.com" },
];
for (const extra of mismatches) {
const exchange = await form(
"/oauth2/token",
{ grant_type: "authorization_code", code: await code(), redirect_uri: redirectUri, ...extra },
{ Authorization: basic(client.client_id, client.client_secret) },
);
expect(exchange.status).toBe(400);
expect(exchange.headers.get("WWW-Authenticate")).toBeNull();
expect(await exchange.json()).toEqual({
error: "invalid_request",
error_description: "Credentials in post body and basic Authorization header do not match",
});
}
});

it("accepts body credentials that match the header, and ignores an empty body secret", async () => {
const { form, code } = fixture();
const matches: Record<string, string>[] = [
{ client_id: client.client_id, client_secret: client.client_secret },
{ client_id: client.client_id },
{ client_secret: "" },
];
for (const extra of matches) {
const exchange = await form(
"/oauth2/token",
{ grant_type: "authorization_code", code: await code(), redirect_uri: redirectUri, ...extra },
{ Authorization: basic(client.client_id, client.client_secret) },
);
expect(exchange.status).toBe(200);
}
});

it("keeps client credentials in the body", async () => {
const { form, code } = fixture();
const exchange = await form("/oauth2/token", {
...client,
grant_type: "authorization_code",
code: await code(),
redirect_uri: redirectUri,
});
expect(exchange.status).toBe(200);
});
});
44 changes: 42 additions & 2 deletions packages/@emulators/google/src/routes/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,50 @@ export function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): vo
const redirect_uri = typeof body.redirect_uri === "string" ? body.redirect_uri : "";
const grant_type = typeof body.grant_type === "string" ? body.grant_type : "";
const code_verifier = typeof body.code_verifier === "string" ? body.code_verifier : undefined;
const bodyClientId = typeof body.client_id === "string" ? body.client_id : "";
const bodyClientSecret = typeof body.client_secret === "string" ? body.client_secret : "";
let bodyClientId = typeof body.client_id === "string" ? body.client_id : "";
let bodyClientSecret = typeof body.client_secret === "string" ? body.client_secret : "";

// client_secret_basic, which Google's discovery document lists beside client_secret_post: the client's
// credentials in an HTTP Basic Authorization header, each form-urlencoded (RFC 6749, section 2.3.1).
let basic: { id: string; secret: string } | undefined;
const authHeader = c.req.header("Authorization") ?? "";
if (authHeader.startsWith("Basic ")) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With OAuth clients configured, valid Authorization: basic … or Authorization: BASIC … credentials are ignored, causing header-only token requests to fail with 401 invalid_client.

Fix on Vercel

const decoded = Buffer.from(authHeader.slice(6), "base64").toString();
const sep = decoded.indexOf(":");
if (sep !== -1) {
const formDecode = (value: string) => {
try {
return decodeURIComponent(value.replace(/\+/g, " "));
} catch {
return value;
}
};
basic = { id: formDecode(decoded.slice(0, sep)), secret: formDecode(decoded.slice(sep + 1)) };
}
}

const clientsConfigured = gs.oauthClients.all().length > 0;
// Google refuses body credentials that do not match the header, and accepts an identical duplicate: a body
// client_secret needs the same client_id and secret, a body client_id alone the same client_id.
if (
clientsConfigured &&
basic &&
((bodyClientSecret && !constantTimeSecretEqual(bodyClientSecret, basic.secret)) ||
((bodyClientId || bodyClientSecret) && bodyClientId !== basic.id))
) {
return c.json(
{
error: "invalid_request",
error_description: "Credentials in post body and basic Authorization header do not match",
},
400,
);
}
if (basic) {
bodyClientId ||= basic.id;
bodyClientSecret ||= basic.secret;
}

if (clientsConfigured) {
const client = gs.oauthClients.findOneBy("client_id", bodyClientId);
if (!client) {
Expand Down
1 change: 1 addition & 0 deletions packages/emulate/src/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ Google Calendar discovery:
GET /discovery/v1/apis/calendar/v3/rest returns the public discovery document for the emulated Calendar v3 surface.

Google OIDC:
The token endpoint accepts client credentials in the body or an HTTP Basic header (client_secret_basic); with OAuth clients configured, body credentials that do not match the header return 400 invalid_request.
Discovery advertises RS256 ID tokens, and GET /oauth2/v3/certs returns the RSA public key used to verify them.
Set google.strict_scopes: true in seed config to validate issued access tokens, expiry, revocation, and method scopes.
Strict mode returns Google-style 401/403 errors and limits userinfo claims; bearer-token defaults remain permissive.
Expand Down
2 changes: 2 additions & 0 deletions skills/google/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ Also accepts `application/json` body. Returns:
}
```

The token endpoint accepts the client's credentials in the request body (`client_secret_post`) or in an HTTP Basic `Authorization` header (`client_secret_basic`), the two methods Google's discovery document lists. With OAuth clients configured, a request whose body credentials do not match the header returns `400 invalid_request`.

### Refresh Token

```bash
Expand Down