Skip to content

Commit 5969dc3

Browse files
authored
test(oauth): check OAuth scopes against a live server (#1188)
Released servers ignore requested scopes, so unit tests can't show that the extension requests enough. This adds a suite that runs the extension's OAuth login and token refresh against a server that enforces scopes, then calls every Coder API method the extension uses with the refreshed token. - `pnpm test` scans src/ with the TypeScript checker and fails when an API method the extension calls has no probe and no listed reason. - `pnpm test:scopes` checks that login and refresh grant exactly the requested scopes, runs each API probe, and sends the requests that `coder ssh`, `coder start` and the one-build update make. - PRs run against v2.38.0, the first release that enforces requested scopes. A nightly run against `coder-preview:latest` reports failures in an issue. Part of VSC-24.
1 parent 733bf61 commit 5969dc3

19 files changed

Lines changed: 1089 additions & 4 deletions
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
name: OAuth Scopes
2+
3+
# Nightly runs use the latest preview to catch server changes before they ship.
4+
on:
5+
pull_request:
6+
paths:
7+
- src/**
8+
- test/mocks/**
9+
- test/scopes/**
10+
- package.json
11+
- pnpm-lock.yaml
12+
- vitest.config.mts
13+
- .github/workflows/oauth-scopes.yaml
14+
schedule:
15+
# GitHub delays or drops fewer scheduled runs off the hour.
16+
- cron: "17 6 * * *"
17+
workflow_dispatch:
18+
19+
permissions:
20+
contents: read
21+
22+
cache-mode: read
23+
24+
# Cancel superseded PR runs; scheduled runs each get their own group.
25+
concurrency:
26+
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
27+
cancel-in-progress: true
28+
29+
jobs:
30+
live-server:
31+
name: Live Server Test (${{ github.event_name == 'schedule' && 'coder-preview' || 'pinned release' }})
32+
runs-on: ubuntu-24.04
33+
timeout-minutes: 15
34+
permissions:
35+
contents: read
36+
issues: write
37+
steps:
38+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
39+
with:
40+
persist-credentials: false
41+
- name: Setup pnpm, Node.js, and dependencies
42+
uses: ./.github/actions/pnpm-setup
43+
- run: docker compose -f test/scopes/compose.yaml up -d --wait
44+
env:
45+
CODER_IMAGE: ${{ github.event_name == 'schedule' && 'ghcr.io/coder/coder-preview:latest' || '' }}
46+
- run: pnpm test:scopes
47+
env:
48+
CODER_SCOPES_TEST_URL: http://localhost:7080
49+
# A failed scheduled run notifies only one person, so track it in an issue.
50+
- name: Report nightly failure
51+
if: failure() && github.event_name == 'schedule'
52+
env:
53+
GH_TOKEN: ${{ github.token }}
54+
GH_REPO: ${{ github.repository }}
55+
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
56+
run: |
57+
title="Nightly OAuth scope test failed"
58+
issue=$(gh issue list --state open --search "\"$title\" in:title" --json number --jq '.[0].number')
59+
if [ -n "$issue" ]; then
60+
gh issue comment "$issue" --body "Failed again: $RUN_URL"
61+
else
62+
gh issue create --title "$title" --body "The scope test failed against \`coder-preview:latest\`: $RUN_URL"
63+
fi

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ Before changing anything under `packages/` or `test/webview/`, read
4242
- Unit tests: `pnpm test`, or `pnpm test:extension` / `pnpm test:webview`
4343
with an optional file path
4444
- Integration tests: `pnpm test:integration`
45+
- OAuth scope tests: `CODER_SCOPES_TEST_URL=<url> pnpm test:scopes`, against a
46+
live server ([docs/TESTING.md](docs/TESTING.md#oauth-scope-tests))
4547
- Storybook: `pnpm storybook`; theme snapshots: `pnpm sync:vscode-themes`
4648

4749
Integration tests and the theme sync launch VS Code; on headless machines

‎CONTRIBUTING.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ guides cover the rest; they serve humans and coding agents alike, and
88
naming, and test placement.
99
- [Architecture](docs/ARCHITECTURE.md): how opening a workspace works, SSH
1010
config management, Windows permissions and connection logging.
11-
- [Testing](docs/TESTING.md): unit, webview and integration tests, and
12-
testing the open flow by hand.
11+
- [Testing](docs/TESTING.md): unit, webview, integration and OAuth scope
12+
tests, and testing the open flow by hand.
1313
- [Tooling](docs/TOOLING.md): linting, formatting, TypeScript, Node.js and
1414
dependency upgrades.
1515
- [Webviews](packages/AGENTS.md): React, `@repo/ui`, Storybook and the

‎docs/TESTING.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ test/
5050
├── unit/ # Extension unit tests (mirrors src/)
5151
├── webview/ # Webview unit tests (mirrors packages/<pkg>/src/, jsdom)
5252
├── integration/ # Integration tests (real VS Code, Mocha)
53+
├── scopes/ # OAuth scopes against a live server
5354
├── utils/ # Test utilities that are also tested
5455
└── mocks/ # Shared test mocks
5556
```
@@ -75,6 +76,29 @@ command with `xvfb-run -a`.
7576
run in that copy with its own user data directory, so an open VS Code
7677
doesn't interfere.
7778

79+
## OAuth scope tests
80+
81+
`test/scopes/` signs in and refreshes the token through the extension's OAuth
82+
flow against a live server, then probes each server call the extension makes.
83+
When `pnpm test` reports an unprobed method, add a probe to
84+
`test/scopes/probes.ts` and run the suite.
85+
86+
The suite has its own Vitest config and `pnpm test` never runs it. It needs
87+
Docker and a fresh deployment, since it creates users and workspaces.
88+
`pnpm test:scopes` takes the deployment's URL from `CODER_SCOPES_TEST_URL`:
89+
90+
```bash
91+
# Recreates the deployment, so every run starts fresh
92+
docker compose -f test/scopes/compose.yaml up -d --wait --force-recreate --renew-anon-volumes
93+
CODER_SCOPES_TEST_URL=http://localhost:7080 pnpm test:scopes
94+
docker compose -f test/scopes/compose.yaml down -v
95+
```
96+
97+
Pull requests run against the Coder release pinned in `compose.yaml`, which
98+
must enforce requested scopes, as 2.38 does and 2.37 doesn't. The
99+
nightly run uses `coder-preview:latest` and reports failures in a "Nightly
100+
OAuth scope test failed" issue. Set `CODER_IMAGE` to test another image.
101+
78102
## Testing the open flow by hand
79103

80104
There are a few ways you can test the "Open in VS Code" flow:

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"test": "cross-env CI=true ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs",
4848
"test:extension": "cross-env ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs --project extension",
4949
"test:integration": "pnpm build:test && node scripts/esbuild.mjs && vscode-test --config test/integration/.vscode-test.mjs",
50+
"test:scopes": "cross-env CI=true ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs --config test/scopes/vitest.config.mts",
5051
"test:webview": "cross-env ELECTRON_RUN_AS_NODE=1 electron node_modules/vitest/vitest.mjs --project webview",
5152
"typecheck": "concurrently -g -n extension,tests,packages,storybook \"tsc --noEmit\" \"tsc --noEmit -p test\" \"pnpm typecheck:packages\" \"tsc --noEmit -p .storybook\"",
5253
"typecheck:packages": "pnpm -r --filter \"./packages/*\" --parallel typecheck",

‎pnpm-workspace.yaml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ catalog:
2121
react-dom: ^19.3.1
2222
storybook: ^10.6.6
2323
storybook-addon-pseudo-states: ^10.6.6
24-
# typescript stays on the 6.0 API for typescript-eslint; TypeScript 7 runs `tsc`.
24+
# typescript stays on the 6.0 API for typescript-eslint and the compiler API in
25+
# test/unit/oauthScopeProbes.test.ts; TypeScript 7 runs `tsc`.
2526
# https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/
2627
typescript: npm:@typescript/typescript6@^6.0.2
2728
vite: ^8.3.6

‎src/websocket/oneWayWebSocket.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ export class OneWayWebSocket<
192192
}
193193
}
194194

195-
function rawDataToString(data: RawData): string {
195+
export function rawDataToString(data: RawData): string {
196196
if (Buffer.isBuffer(data)) {
197197
return data.toString("utf8");
198198
} else if (data instanceof ArrayBuffer) {

‎test/scopes/compose.yaml‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# A throwaway deployment for `pnpm test:scopes`.
2+
services:
3+
postgres:
4+
image: postgres:17
5+
environment:
6+
POSTGRES_USER: coder
7+
POSTGRES_PASSWORD: coder
8+
POSTGRES_DB: coder
9+
healthcheck:
10+
test: pg_isready -U coder
11+
interval: 2s
12+
retries: 30
13+
14+
coder:
15+
image: ${CODER_IMAGE:-ghcr.io/coder/coder:v2.38.0@sha256:38a4cfc548b096484d6d1743e5f1a5af18301ed9a7ffde5150663822f9887026}
16+
ports: ["127.0.0.1:7080:7080"]
17+
environment:
18+
CODER_PG_CONNECTION_URL: postgres://coder:coder@postgres:5432/coder?sslmode=disable
19+
CODER_HTTP_ADDRESS: 0.0.0.0:7080
20+
CODER_ACCESS_URL: http://localhost:7080
21+
CODER_OAUTH2_PROVIDER_ENABLE: "true"
22+
depends_on:
23+
postgres:
24+
condition: service_healthy
25+
healthcheck:
26+
test: curl -fs http://localhost:7080/healthz
27+
interval: 2s
28+
retries: 60

‎test/scopes/oauthScopes.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { beforeAll, describe, expect, it } from "vitest";
2+
3+
import { LocalProxySettings } from "@/settings/proxy";
4+
5+
import { MockConfigurationProvider } from "../mocks/testHelpers";
6+
7+
import { apiProbes, cliProbes } from "./probes";
8+
import { setUpDeployment, type Deployment } from "./support/deployment";
9+
10+
describe("OAuth scopes", () => {
11+
let deployment: Deployment;
12+
13+
// The extension creates these on activation, which the suite doesn't run.
14+
beforeAll(() => {
15+
new MockConfigurationProvider();
16+
const proxySettings = LocalProxySettings.initialize();
17+
return () => proxySettings.dispose();
18+
});
19+
20+
beforeAll(async () => {
21+
const url = process.env.CODER_SCOPES_TEST_URL;
22+
if (!url) {
23+
throw new Error(
24+
"Set CODER_SCOPES_TEST_URL to a fresh deployment; see docs/TESTING.md#oauth-scope-tests",
25+
);
26+
}
27+
deployment = await setUpDeployment(url);
28+
});
29+
30+
it.each(["login", "refresh"] as const)(
31+
"grants exactly the requested scopes at %s",
32+
(grant) => {
33+
const sorted = (scopes: string) => scopes.split(" ").sort();
34+
expect(sorted(deployment.grantedScopes[grant])).toEqual(
35+
sorted(deployment.requestedScopes),
36+
);
37+
},
38+
);
39+
40+
describe("API probes", () => {
41+
it.each(Object.entries(apiProbes))("%s", async (_name, probe) => {
42+
await probe(deployment);
43+
});
44+
});
45+
46+
describe("CLI probes", () => {
47+
it.each(Object.entries(cliProbes))("%s", async (_name, probe) => {
48+
await probe(deployment);
49+
});
50+
});
51+
});

‎test/scopes/probes.ts‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { opens, receives } from "./support/streams";
2+
import {
3+
ssh,
4+
startOutdatedWithCli,
5+
updateInOneBuild,
6+
} from "./support/workspaceActions";
7+
import { currentAgentId } from "./support/workspaces";
8+
9+
import type { CoderApi } from "@/api/coderApi";
10+
11+
import type { Probe } from "./support/deployment";
12+
13+
type ApiMethod = keyof CoderApi;
14+
15+
/**
16+
* One probe per Coder API method the extension calls, which
17+
* `oauthScopeProbes.test.ts` checks. Mutating probes leave `own` running with
18+
* no build in progress, so probes can run in any order.
19+
*/
20+
export const apiProbes = {
21+
getBuildInfo: ({ scoped }) => scoped.getBuildInfo(),
22+
getAuthenticatedUser: ({ scoped }) => scoped.getAuthenticatedUser(),
23+
getAppearance: ({ scoped }) => scoped.getAppearance(),
24+
getDeploymentSSHConfig: ({ scoped }) => scoped.getDeploymentSSHConfig(),
25+
getWorkspaces: async ({ scoped }) =>
26+
assertNonEmpty((await scoped.getWorkspaces({ q: "owner:me" })).workspaces),
27+
"getWorkspaces (shared)": async ({ scoped, own }) =>
28+
assertNonEmpty(
29+
(await scoped.getWorkspaces({ q: `shared_with_user:${own.owner_id}` }))
30+
.workspaces,
31+
),
32+
getWorkspace: ({ scoped, own }) => scoped.getWorkspace(own.id),
33+
getWorkspaceByOwnerAndName: ({ scoped, own }) =>
34+
scoped.getWorkspaceByOwnerAndName(own.owner_name, own.name),
35+
"getWorkspaceByOwnerAndName (shared)": ({ scoped, shared }) =>
36+
scoped.getWorkspaceByOwnerAndName(shared.owner_name, shared.name),
37+
getWorkspaceBuildByNumber: ({ scoped, own }) =>
38+
scoped.getWorkspaceBuildByNumber(own.owner_name, own.name, 1),
39+
getWorkspaceBuildParameters: async ({ scoped, own }) =>
40+
assertNonEmpty(
41+
await scoped.getWorkspaceBuildParameters(own.latest_build.id),
42+
),
43+
// No `assertNonEmpty`: the test agent never connects, so it has no logs.
44+
getWorkspaceAgentLogs: async ({ scoped, admin, own }) =>
45+
scoped.getWorkspaceAgentLogs(await currentAgentId(admin, own)),
46+
getTemplate: ({ scoped, own }) => scoped.getTemplate(own.template_id),
47+
getTemplateVersion: ({ scoped, own }) =>
48+
scoped.getTemplateVersion(own.template_active_version_id),
49+
getTemplateVersionResources: async ({ scoped, own }) =>
50+
assertNonEmpty(
51+
await scoped.getTemplateVersionResources(own.template_active_version_id),
52+
),
53+
getTemplateVersionRichParameters: async ({ scoped, own }) =>
54+
assertNonEmpty(
55+
await scoped.getTemplateVersionRichParameters(
56+
own.template_active_version_id,
57+
),
58+
),
59+
getTemplateVersionPresets: async ({ scoped, own }) =>
60+
assertNonEmpty(
61+
await scoped.getTemplateVersionPresets(own.template_active_version_id),
62+
),
63+
watchWorkspace: receives((api, { own }) => api.watchWorkspace(own)),
64+
watchAgentMetadata: receives(async (api, { admin, own }) =>
65+
api.watchAgentMetadata(await currentAgentId(admin, own)),
66+
),
67+
watchBuildLogsByBuildId: opens((api, { own }) =>
68+
api.watchBuildLogsByBuildId(own.latest_build.id, []),
69+
),
70+
watchWorkspaceAgentLogs: opens(async (api, { admin, own }) =>
71+
api.watchWorkspaceAgentLogs(await currentAgentId(admin, own), []),
72+
),
73+
watchInboxNotifications: opens((api) => api.watchInboxNotifications([], [])),
74+
"postWorkspaceBuild (update)": updateInOneBuild,
75+
} satisfies Partial<Record<ApiMethod | `${ApiMethod} (${string})`, Probe>>;
76+
77+
/**
78+
* CLI requests the source scan can't find. Unprobed: `ping` and `speedtest`
79+
* dial like `ssh`; `netcheck` calls `/workspaceagents/connection`, which has
80+
* no RBAC check; `support bundle` only reads what other probes cover.
81+
*/
82+
export const cliProbes: Record<string, Probe> = {
83+
"coder ssh": (d) => ssh(d, d.own),
84+
"coder ssh (shared)": (d) => ssh(d, d.shared),
85+
"coder start": startOutdatedWithCli,
86+
};
87+
88+
const TASKS_API =
89+
"Tasks API, only used on servers before 2.35, which ignore OAuth scopes";
90+
91+
/** Coder API methods the extension calls that need no probe, with the reason. */
92+
export const unprobedMethods: Partial<Record<ApiMethod, string>> = {
93+
startWorkspace: TASKS_API,
94+
stopWorkspace: TASKS_API,
95+
createTask: TASKS_API,
96+
deleteTask: TASKS_API,
97+
getTask: TASKS_API,
98+
getTaskLogs: TASKS_API,
99+
getTasks: TASKS_API,
100+
getTemplates: TASKS_API,
101+
pauseTask: TASKS_API,
102+
resumeTask: TASKS_API,
103+
sendTaskInput: TASKS_API,
104+
};
105+
106+
function assertNonEmpty(items: readonly unknown[] | null): void {
107+
if (!items?.length) {
108+
throw new Error(
109+
"Expected at least one item; the server omits rows the token cannot read, so an empty list usually means a missing scope",
110+
);
111+
}
112+
}

0 commit comments

Comments
 (0)