Skip to content

feat: log the OAuth2 provider state and registered apps at startup - #29267

Merged
BobbyHo merged 24 commits into
mainfrom
plat-492-4-startup-lines
Sep 15, 2026
Merged

BobbyHo merged 24 commits into
mainfrom
plat-492-4-startup-lines

Conversation

@BobbyHo

@BobbyHo BobbyHo commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

Fourth of five for PLAT-492. Every coder server start logs whether the OAuth2 provider is enabled, naming CODER_OAUTH2_PROVIDER_ENABLE. If the provider is off but applications are still registered, one warning gives the count and the flag to set.

PR What it does
#29248 Adds the flag, a public build info field, and the test default.
#29251 Gates the OAuth2 routes and dashboard navigation on the flag.
#29257 Removes the oauth2 experiment.
this Logs the provider state and any registered apps at startup.
#29268 Docs.

Implementation Details
  • coderd.LogOAuth2ProviderState logs oauth2 provider enabled or oauth2 provider disabled at info with a flag field.
  • When disabled, it lists apps with the existing GetOAuth2ProviderApps under a system context and warns with the count. A query error is logged at warn and startup continues.
  • cli/server.go calls it once after the database connects, before coderd.New.
  • TestServer/SpammyLogs allows two more rows. The new line wraps to two rows at 80 columns.
Tests
  • TestLogOAuth2ProviderState runs a dbmock table: enabled, disabled with zero apps, disabled with two apps, and a query error. Each case asserts exactly one info line and the expected warnings.
  • The enabled case sets no mock expectation, so any query while the provider is on fails the test.

Manual Tests

Run 2026-09-14 in a Coder workspace against embedded Postgres. Two checkouts share one .coderv2: ~/coder-before at the merge base (v2.37.0-devel+c26a6b86a9, before the stack) and ~/coder at the stack head (v2.37.0-devel+d3df4aa16a, #29248 through this PR). Each scenario restarts scripts/develop.sh under tmux with a different environment, so the same database, session and registered apps carry across every upgrade and flag change. Requests run on the workspace against localhost:3000. Token values are shown as prefix and length only.

Scenario summary, all 36
# Scenario Result
1 Pre-upgrade server with CODER_EXPERIMENTS=oauth2 reports ["oauth2"] Pass
2 Pre-upgrade log has the HERE BE DRAGONS line for oauth2 and no line naming CODER_OAUTH2_PROVIDER_ENABLE Pass
3 Pre-upgrade build info has no oauth2_provider field Pass
4 Pre-upgrade gated routes all serve (no 404) Pass
5 Pre-upgrade binary rejects --oauth2-provider-enable as an unknown flag Pass
6 Two apps registered, one secret issued Pass
7 Authorization code grant issues an access and refresh token pair Pass
8 The access token authenticates Pass
9 Database before the upgrade: 2 apps, 1 token row, 1 oauth2 api key, 0 settings audit rows Pass
10 Upgrade in place, environment unchanged: same database, same session token Pass
11 Startup log: ignoring unknown experiment, oauth2 provider disabled, and the warning naming 2 registered apps Pass
12 No HERE BE DRAGONS line for oauth2 on the new binary Pass
13 Experiments endpoint passes oauth2 through like any unknown value Pass
14 Build info reports oauth2_provider: false Pass
15 Every gated route answers 404 with the flag unset, including MCP HTTP Pass
16 The 404 body is the generic route-not-found body, identical to an unknown path Pass
17 The pre-upgrade access token still authenticates Pass
18 The pre-upgrade refresh token cannot be redeemed; its row is untouched Pass
19 Settings stay reachable and writable; DCR can be switched on but /oauth2/register stays 404 Pass
20 The settings PUT is audited; nothing else since the upgrade is Pass
21 Database rows and schema version unchanged by the upgrade Pass
22 Dashboard hides both "OAuth2 Applications" nav items; the direct URL renders the 404 error state Pass
23 Restart with the flag and the experiment: oauth2 provider enabled, no apps warning Pass
24 Restart with the flag only: no warning of any kind, one enabled line Pass
25 Build info reports oauth2_provider: true; experiments [] Pass
26 Every gated route is back Pass
27 The pre-upgrade refresh token redeems without user interaction; the old access token is revoked Pass
28 Pre-upgrade apps are listed and a fresh code grant works with the pre-upgrade secret Pass
29 Dashboard shows both nav items; the apps page lists both fixtures Pass
30 Flag on, MCP experiment off: 403 naming mcp-server-http Pass
31 Flag off, MCP experiment on: 404 (the OAuth2 gate runs first) Pass
32 CODER_EXPERIMENTS=OAuth2 is lower-cased in the warning Pass
33 CODER_EXPERIMENTS=* never mentions oauth2; routes 404 Pass
34 --oauth2-provider-enable on the command line enables the provider; --help shows the option Pass
35 oauth2.provider.enable: true in YAML enables the provider Pass
36 CODER_OAUTH2_PROVIDER_ENABLE=true on the old binary is ignored Pass

Three expectations in the runbook were wrong and are corrected in the notes below: the unknown-experiment and dragons lines print four times per start, not three; the old binary's MCP route answers 415 rather than 403 because the dev bypass skips the experiment gate; and a second code grant for the same user and app replaces the previous token pair instead of adding one.

Environment and shell helpers

start_server runs develop.sh in a detached tmux session with the given environment and tees the log to a per-start file. stop_server ends the session and also stops the embedded Postgres, which otherwise outlives develop.sh and blocks the next start on postmaster.pid.

# $1=checkout dir, $2=log name, rest=env assignments; extra server args after --
start_server() {
  local dir=$1 name=$2; shift 2
  local envs=() extra=()
  while [ $# -gt 0 ]; do
    if [ "$1" = -- ]; then shift; extra=(-- "$@"); break; fi
    envs+=("$1"); shift
  done
  ssh "$WS" "cd $dir || exit 1; tmux kill-session -t coderd 2>/dev/null; \
    tmux new-session -d -s coderd \"env ${envs[*]} ./scripts/develop.sh ${extra[*]} 2>&1 | tee ~/coderd-$name.log\""
}
stop_server() {
  ssh "$WS" 'tmux kill-session -t coderd 2>/dev/null; sleep 2; \
    if [ -f ~/coder/.coderv2/postgres/data/postmaster.pid ]; then \
      ~/coder/.coderv2/postgres/bin/bin/pg_ctl -D ~/coder/.coderv2/postgres/data stop -m fast; fi'
}
# The api child logs in colour and the codes sit between a field name and its value, so strip them first.
logs()     { ssh "$WS" "sed -E 's/\x1b\[[0-9;]*m//g' ~/coderd-$1.log | grep -E '$2' | tail -n ${3:-20}"; }
logcount() { ssh "$WS" "sed -E 's/\x1b\[[0-9;]*m//g' ~/coderd-$1.log | grep -cE '$2'"; }

Request helpers, run on the workspace:

BASE_URL=http://localhost:3000
AUTH_HEADER="Coder-Session-Token: $(cat ~/coder/.coderv2/session)"
urlenc() { jq -rn --arg v "$1" '$v|@uri'; }
# status METHOD PATH [curl args] -> "METHOD PATH -> code body"
status() {
  local code; code=$(curl -s -o /tmp/plat492/status.body -w '%{http_code}' -X "$1" "$BASE_URL$2" -H "$AUTH_HEADER" ${3:-})
  printf '%-4s %-45s -> %s %s\n' "$1" "$2" "$code" "$(head -c 120 /tmp/plat492/status.body | tr -d '\n')"
}
# The route table CODER_OAUTH2_PROVIDER_ENABLE controls.
gated() {
  status GET  /.well-known/oauth-authorization-server
  status GET  /.well-known/oauth-protected-resource
  status GET  /oauth2/authorize
  status POST /oauth2/tokens
  status POST /oauth2/revoke
  status POST /oauth2/register
  status GET  /api/v2/oauth2-provider/apps
  status POST /api/experimental/mcp/http
}
new_pkce() {
  VERIFIER=$(openssl rand 32 | base64 | tr -d '\n=' | tr '+/' '-_')
  CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d '=' | tr '+/' '-_')
  STATE=$(openssl rand -hex 16)
}
CB=http://localhost:9876/callback
# authorize CLIENT_ID -> sets CODE (header auth, POST)
authorize() {
  new_pkce
  local url="$BASE_URL/oauth2/authorize?client_id=$1&response_type=code&redirect_uri=$(urlenc "$CB")&state=$STATE&code_challenge=$CHALLENGE&code_challenge_method=S256"
  local loc; loc=$(curl -s -o /dev/null -X POST "$url" -H "$AUTH_HEADER" -w '%{redirect_url}')
  CODE=$(python3 -c 'import sys,urllib.parse as u;print(dict(u.parse_qsl(u.urlparse(sys.argv[1]).query)).get("code",""))' "$loc")
}
exchange_form() { printf 'grant_type=authorization_code&client_id=%s&client_secret=%s&code=%s&code_verifier=%s&redirect_uri=%s' "$1" "$2" "$CODE" "$VERIFIER" "$(urlenc "$CB")"; }
refresh_form()  { printf 'grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s' "$1" "$2" "$3"; }
# tok FORM: prints HTTP status and body, sets AT/RT on 200
tok() {
  local st; st=$(curl -s -o /tmp/plat492/tok.body -w '%{http_code}' -X POST "$BASE_URL/oauth2/tokens" -H 'Content-Type: application/x-www-form-urlencoded' -d "$1")
  echo "HTTP $st"; jq . /tmp/plat492/tok.body
  [ "$st" = 200 ] && { AT=$(jq -r .access_token /tmp/plat492/tok.body); RT=$(jq -r .refresh_token /tmp/plat492/tok.body); }
}
probe() { curl -s -o /dev/null -w "GET /api/v2/users/me with token -> %{http_code}\n" "$BASE_URL/api/v2/users/me" -H "Coder-Session-Token: $1"; }
pg() { PGPASSWORD=$(cat ~/coder/.coderv2/postgres/password) psql -h localhost -p $(cat ~/coder/.coderv2/postgres/port) -U coder -d coder -tA -c "$1"; }
# apps | refresh-token rows | oauth2 session keys
oauth2_rows() { pg "SELECT (SELECT count(*) FROM oauth2_provider_apps), (SELECT count(*) FROM oauth2_provider_app_tokens), (SELECT count(*) FROM api_keys WHERE login_type = 'oauth2_provider_app');"; }

Fixtures, registered through the API on the pre-upgrade binary:

plat492-live   65e258eb-7bd7-4508-9675-ac12c0bb4af1   one secret, used for every grant
plat492-idle   92d132a9-f802-4594-bc8a-2840a402a260   never used; makes the apps warning count 2
1. Baseline: the pre-upgrade binary with the experiment (scenarios 1 to 5)
start_server ~/coder-before before CODER_EXPERIMENTS=oauth2
curl -s "$BASE_URL/api/v2/experiments" -H "$AUTH_HEADER" | jq -c .
logs before 'HERE BE DRAGONS'; logcount before 'CODER_OAUTH2_PROVIDER_ENABLE'
curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{version, has_flag: has("oauth2_provider")}'
gated
./build/coder_linux_amd64 server --oauth2-provider-enable --help 2>&1 | head -1
ready: v2.37.0-devel+c26a6b86a9
["oauth2"]
[warn]  coderd: 🐉 HERE BE DRAGONS: opting into hidden experiment  experiment=oauth2   (x4)
CODER_OAUTH2_PROVIDER_ENABLE mentions: 0
{"version":"v2.37.0-devel+c26a6b86a9","has_flag":false}

GET  /.well-known/oauth-authorization-server       -> 200 {"issuer":"http://127.0.0.1:3000",...
GET  /.well-known/oauth-protected-resource         -> 200 {"resource":"http://127.0.0.1:3000",...
GET  /oauth2/authorize                             -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/tokens                                -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/revoke                                -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/register                              -> 403 {"error":"invalid_request","error_description":"Dynamic client registration is disabled on this deployment"}
GET  /api/v2/oauth2-provider/apps                  -> 200 []
POST /api/experimental/mcp/http                    -> 415 Content-Type must be 'application/json'

parsing flags ([server --oauth2-provider-enable --help]) for "coder server": unknown flag: --oauth2-provider-enable   (exit 1)

The dragons line prints four times, once per ReadExperiments call at startup. The MCP route answers 415, not the 403 first expected: RequireExperimentWithDevBypass returns early on a dev build, so the request reaches the MCP transport and its Content-Type check answers. This is the baseline section 4 is compared against. The unknown-flag error is why the release note recommends the environment variable for the zero-downtime path.

2. Fixtures: two apps and a live token pair (scenarios 6 to 9)
APP1=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" -H "$AUTH_HEADER" -H 'Content-Type: application/json' -d '{"name":"plat492-live","callback_url":"http://localhost:9876/callback"}')
APP2=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" -H "$AUTH_HEADER" -H 'Content-Type: application/json' -d '{"name":"plat492-idle","callback_url":"http://localhost:9876/callback"}')
APP1_SECRET=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$APP1_ID/secrets" -H "$AUTH_HEADER" | jq -r .client_secret_full)
authorize "$APP1_ID"; tok "$(exchange_form "$APP1_ID" "$APP1_SECRET")"; PRE_AT=$AT; PRE_RT=$RT
probe "$PRE_AT"
oauth2_rows; pg "SELECT count(*) FROM audit_logs WHERE resource_type = 'oauth2_provider_settings';"
{"id":"65e258eb-7bd7-4508-9675-ac12c0bb4af1","name":"plat492-live","callback_url":"http://localhost:9876/callback"}
{"id":"92d132a9-f802-4594-bc8a-2840a402a260","name":"plat492-idle","callback_url":"http://localhost:9876/callback"}
secret_len=57
HTTP 200
{"token_type":"Bearer","expires_in":86399,"scope":"coder:all","at_len":33,"rt_len":57,"at_prefix":"Dt9MX9RLgg","rt_prefix":"coder_hVn6"}
GET /api/v2/users/me with token -> 200
2|1|1
0
token row 93a979ab-908f-48ff-9a2b-ebd04c66cd52 expires 2026-10-14; key Dt9MX9RLgg expires 2026-09-15
site_configs oauth2_dcr_enabled: (no row)

2|1|1 and 0 are the invariant the upgrade must not move. The row ids are kept so section 4 can show the same rows survive, not just the same counts.

3. Upgrade in place, environment unchanged (scenarios 10 to 14)

CODER_EXPERIMENTS=oauth2 is still set; the flag is not. This is the moment the startup lines in this PR are for.

stop_server; start_server ~/coder after-noflag CODER_EXPERIMENTS=oauth2
logs after-noflag 'CODER_OAUTH2_PROVIDER_ENABLE|oauth2 provider|experiment=oauth2'
logcount after-noflag 'HERE BE DRAGONS'
curl -s "$BASE_URL/api/v2/experiments" -H "$AUTH_HEADER" | jq -c .
curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{version, oauth2_provider}'
ready: v2.37.0-devel+d3df4aa16a
[warn]  coderd: ignoring unknown experiment  experiment=oauth2                       (x4)
[info]  oauth2 provider disabled  flag=CODER_OAUTH2_PROVIDER_ENABLE                  (x1)
[warn]  The OAuth2 provider is disabled but 2 OAuth2 application(s) are registered. Existing applications, secrets and user authorizations are preserved but cannot be used until the provider is enabled. Set CODER_OAUTH2_PROVIDER_ENABLE=true to enable it.   (x1)
HERE BE DRAGONS: 0
["oauth2"]
{"version":"v2.37.0-devel+d3df4aa16a","oauth2_provider":false}

The same session token authenticates across the restart. The state line and the apps warning print once each; the count in the warning is the two fixtures. ReadExperiments warns about the unknown value but still appends it, so the endpoint keeps echoing oauth2; nothing reads it, as section 4 shows.

4. Flag unset: what an upgraded deployment sees (scenarios 15 to 22)
gated
curl -s -o 404.body -w 'HTTP %{http_code}\n' -X POST "$BASE_URL/oauth2/tokens" -H 'Content-Type: application/x-www-form-urlencoded' -d "$(refresh_form "$APP1_ID" "$APP1_SECRET" "$PRE_RT")"
jq -c '{has_error: has("error"), message}' 404.body; diff <(curl -s "$BASE_URL/api/v2/does-not-exist") 404.body && echo "bodies identical"
probe "$PRE_AT"
oauth2_rows
status GET /api/v2/oauth2-provider/settings
curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" -H 'Content-Type: application/json' -d '{"dynamic_client_registration_enabled":true}' -w '\nHTTP %{http_code}\n'
status POST /oauth2/register '-H Content-Type:application/json -d {"client_name":"x","redirect_uris":["http://localhost:9876/callback"]}'
pg "SELECT time, action, resource_type FROM audit_logs WHERE time > '2026-09-14 16:59:00+00' ORDER BY time;"
pg "SELECT version FROM schema_migrations;"
GET  /.well-known/oauth-authorization-server       -> 404 {"message":"Route not found."}
GET  /.well-known/oauth-protected-resource         -> 404 {"message":"Route not found."}
GET  /oauth2/authorize                             -> 404 {"message":"Route not found."}
POST /oauth2/tokens                                -> 404 {"message":"Route not found."}
POST /oauth2/revoke                                -> 404 {"message":"Route not found."}
POST /oauth2/register                              -> 404 {"message":"Route not found."}
GET  /api/v2/oauth2-provider/apps                  -> 404 {"message":"Route not found."}
POST /api/experimental/mcp/http                    -> 404 {"message":"Route not found."}

refresh grant: HTTP 404  {"has_error":false,"message":"Route not found."}  bodies identical
GET /api/v2/users/me with token -> 200            (pre-upgrade access token)
2|1|1                                             (same token row 93a979ab..., same key Dt9MX9RLgg)

GET  /api/v2/oauth2-provider/settings              -> 200 {"dynamic_client_registration_enabled":false}
PUT  -> {"dynamic_client_registration_enabled":true}  HTTP 200
POST /oauth2/register                              -> 404 {"message":"Route not found."}
audit rows since the upgrade: 2026-09-14 17:29:56 | write | oauth2_provider_settings   (the PUT, and nothing else)
schema_migrations: 594

Every route that served in section 1 now 404s, including the apps list under a valid Owner session and the MCP route. The body is the generic RouteNotFound, not an RFC 6749 error, so a disabled provider looks like a deployment that never had one. The access token keeps working because the API key middleware does not consult the gate; the refresh token is refused before the handler runs, so its row is untouched. Settings are outside the gate, so DCR can be pre-configured while /oauth2/register stays 404. The only audit row since the upgrade is the PUT: the startup query in this PR runs under a system context and audits nothing. Schema version and every row id are what they were before the upgrade.

Dashboard, as the Owner: no "OAuth2 Applications" item in the Deployment sidebar (/deployment/overview) or the Account sidebar (/settings/account). Typing /deployment/oauth2-provider/apps directly renders the page with a "Route not found." error box above an empty table.

5. The admin sets the flag (scenarios 23 to 29)
stop_server; start_server ~/coder after-flag-exp CODER_EXPERIMENTS=oauth2 CODER_OAUTH2_PROVIDER_ENABLE=true
logs after-flag-exp 'oauth2 provider|OAuth2 application|experiment=oauth2'
stop_server; start_server ~/coder after-flag CODER_OAUTH2_PROVIDER_ENABLE=true
logs after-flag '\[warn\]'; logs after-flag 'oauth2 provider'
curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{oauth2_provider}'; curl -s "$BASE_URL/api/v2/experiments" -H "$AUTH_HEADER" | jq -c .
gated
tok "$(refresh_form "$APP1_ID" "$APP1_SECRET" "$PRE_RT")"; probe "$AT"; probe "$PRE_AT"; oauth2_rows
authorize "$APP1_ID"; tok "$(exchange_form "$APP1_ID" "$APP1_SECRET")"; oauth2_rows
flag + experiment:
[warn]  coderd: ignoring unknown experiment  experiment=oauth2      (x4)
[info]  oauth2 provider enabled  flag=CODER_OAUTH2_PROVIDER_ENABLE  (x1)
apps warning: 0

flag only:
[warn] lines at startup: none
[info]  oauth2 provider enabled  flag=CODER_OAUTH2_PROVIDER_ENABLE  (x1)
{"oauth2_provider":true}
[]

GET  /.well-known/oauth-authorization-server       -> 200 {"issuer":"http://127.0.0.1:3000",...
GET  /.well-known/oauth-protected-resource         -> 200 {"resource":"http://127.0.0.1:3000",...
GET  /oauth2/authorize                             -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/tokens                                -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/revoke                                -> 400 {"error":"invalid_request","error_description":"Missing client_id parameter"}
POST /oauth2/register                              -> 400 {"message":"Request body must be valid JSON.","detail":"EOF"}
GET  /api/v2/oauth2-provider/apps                  -> 200 [{"id":"92d132a9-...","name":"plat492-idle",...},{"id":"65e258eb-...","name":"plat492-live",...}]
POST /api/experimental/mcp/http                    -> 403 {"message":"MCP HTTP Server Functionality functionality requires enabling the 'mcp-server-http' experiment."}

refresh of the pre-upgrade token:
HTTP 200  {"token_type":"Bearer","expires_in":86399,"scope":"coder:all","at_prefix":"MPZcTIn7Xl","rt_prefix":"coder_FURW"}
GET /api/v2/users/me with token -> 200            (new access token)
GET /api/v2/users/me with token -> 401            (pre-upgrade access token, key deleted by the rotation)
2|1|1                                             (new token row e855f071..., new key MPZcTIn7Xl)

fresh code grant with the pre-upgrade secret:
HTTP 200  {"token_type":"Bearer","expires_in":86399,"scope":"coder:all","at_prefix":"xW1dNExH7G","rt_prefix":"coder_L8Yu"}
2|1|1

With the flag on, the apps warning is gone because the check returns before the query. With the experiment removed as well, the api child logs no warning of any kind. Every route from section 1 is back; register is 400 rather than 403 because DCR was switched on in section 4, and MCP is 403 naming mcp-server-http because the new binary has no dev bypass. The refresh token that section 4 could not redeem redeems here unchanged, which is the observable form of "preserved". The counts stay 2|1|1 after the second grant because the code grant deletes the previous key with the same token name for that user and app before inserting (coderd/oauth2provider/tokens.go, "Delete the previous key, if any"), so there is one live pair per user per app.

Dashboard, as the Owner: "OAuth2 Applications" is present in both sidebars, and /deployment/oauth2-provider/apps lists plat492-idle and plat492-live.

6. Edge cases and the other flag forms (scenarios 30 to 36)
# flag on, no experiments (state after section 5)
status POST /api/experimental/mcp/http
stop_server; start_server ~/coder mcp-noflag CODER_EXPERIMENTS=mcp-server-http
status POST /api/experimental/mcp/http; curl -s "$BASE_URL/api/v2/experiments" -H "$AUTH_HEADER" | jq -c .
stop_server; start_server ~/coder mixedcase CODER_EXPERIMENTS=OAuth2
logcount mixedcase 'ignoring unknown experiment.*experiment=oauth2'; logcount mixedcase 'experiment=OAuth2'
stop_server; start_server ~/coder wildcard 'CODER_EXPERIMENTS=*'
logcount wildcard 'experiment=oauth2'; logcount wildcard 'HERE BE DRAGONS'; gated | grep -c 404
stop_server; start_server ~/coder cliflag -- --oauth2-provider-enable
logs cliflag 'oauth2 provider enabled' 1; curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{oauth2_provider}'
./build/coder_linux_amd64 server --help 2>&1 | grep -A 5 "OAUTH2 / PROVIDER OPTIONS"
printf 'oauth2:\n  provider:\n    enable: true\n' > ~/plat492.yaml
stop_server; start_server ~/coder yaml -- --config ~/plat492.yaml
logs yaml 'oauth2 provider enabled' 1; curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{oauth2_provider}'
stop_server; start_server ~/coder-before before-with-envvar CODER_EXPERIMENTS=oauth2 CODER_OAUTH2_PROVIDER_ENABLE=true
logcount before-with-envvar 'CODER_OAUTH2_PROVIDER_ENABLE'; curl -s "$BASE_URL/api/v2/buildinfo" | jq -c '{version, has_flag: has("oauth2_provider")}'; gated | grep -c 404
flag on, MCP experiment off:
POST /api/experimental/mcp/http                    -> 403 {"message":"MCP HTTP Server Functionality functionality requires enabling the 'mcp-server-http' experiment."}

flag off, MCP experiment on:
POST /api/experimental/mcp/http                    -> 404 {"message":"Route not found."}
["mcp-server-http"]

CODER_EXPERIMENTS=OAuth2:
lower-cased experiment=oauth2: 4    as typed experiment=OAuth2: 0

CODER_EXPERIMENTS=*:
experiment=oauth2: 0    HERE BE DRAGONS: 0    gated 404s: 8    experiments: []

--oauth2-provider-enable on the command line (no CODER_* in the environment):
[info]  oauth2 provider enabled  flag=CODER_OAUTH2_PROVIDER_ENABLE
{"oauth2_provider":true}
OAUTH2 / PROVIDER OPTIONS:
      --oauth2-provider-enable bool, $CODER_OAUTH2_PROVIDER_ENABLE (default: false)
          Enable the OAuth 2.1 authorization server, which lets external
          applications (such as MCP clients) obtain tokens for Coder on behalf
          of users. Disabled by default. When disabled, the OAuth2 endpoints and
          discovery documents return 404.

--config with oauth2.provider.enable: true:
[info]  oauth2 provider enabled  flag=CODER_OAUTH2_PROVIDER_ENABLE
{"oauth2_provider":true}

CODER_OAUTH2_PROVIDER_ENABLE=true on the old binary:
ready: v2.37.0-devel+c26a6b86a9
CODER_OAUTH2_PROVIDER_ENABLE mentions: 0    state lines: 0    HERE BE DRAGONS for oauth2: 4
{"version":"v2.37.0-devel+c26a6b86a9","has_flag":false}
gated 404s: 0

The MCP experiment alone no longer suffices: RequireOAuth2Provider runs before RequireExperiment, so the 404 wins over the 403. Mixed case is lower-cased before the switch. * expands to ExperimentsSafe, which never contained oauth2. All three flag forms produce the same state line and build info value. The old binary ignores the new environment variable entirely, which is the zero-downtime path: set the variable, then upgrade.

Incidental, outside this stack: the MCP 403 message reads "Functionality functionality" because the experiment's display name already ends in that word and the middleware template appends it again.

BobbyHo and others added 11 commits September 11, 2026 13:31
Add an opt-in deployment flag for Coder's OAuth 2.1 authorization server.
The flag is off by default and nothing reads it yet; a follow-up moves the
OAuth2 routes and dashboard navigation off the oauth2 experiment and onto
this flag.

- Add oauth2.provider.enable (--oauth2-provider-enable,
  CODER_OAUTH2_PROVIDER_ENABLE) under a new Provider group beneath OAuth2,
  and reword the OAuth2 group so it covers more than GitHub login.
- Add oauth2_provider to the build info response so the dashboard can read
  the provider state without an admin-only config request.
- Turn the flag on by default in coderdtest so existing OAuth2 tests keep
  working once the routes are gated on it.
- Regenerate API docs, TypeScript types, the CLI reference, and golden files.

Part of PLAT-492.
Read the build info flag value through api.DeploymentValues like the
neighbouring fields, and distinguish OAuth2ProviderConfig from
OAuth2ProviderSettings in its doc comment.
Move every OAuth2 provider gate off the oauth2 experiment and onto the
deployment flag added in the previous commit. The flag is off by default,
so a deployment that relied on CODER_EXPERIMENTS=oauth2 must set it or its
OAuth2 clients receive 404 responses after upgrading.

- Add httpmw.RequireOAuth2Provider, which answers 404 while the provider is
  disabled. A disabled provider looks like a deployment that never had one.
  There is no bypass for development builds.
- Use it on both discovery documents, the /oauth2 tree, the admin apps API,
  and the MCP HTTP endpoint, which keeps its mcp-server-http experiment
  check. The AI Gateway's deprecated MCP injection reads the flag too.
- Keep /api/v2/oauth2-provider/settings reachable while disabled so an
  admin can configure dynamic client registration before enabling the
  provider.
- Gate both OAuth2 navigation items on the new build info field instead of
  the experiment, and drop the development-build escape hatch.

The oauth2 experiment is still parsed and reported; a follow-up makes it a
no-op with a specific warning.

Part of PLAT-492.
RequireOAuth2Provider takes a bool: the flag is read once at startup in
three places, so the closure promised a runtime toggle that would ship
half-working. The settings comment moves onto the route it describes,
and both enabled sidebar stories set the flag explicitly instead of
relying on the fixture default.
The MCP HTTP endpoint no longer has a development-build bypass for the
mcp-server-http experiment, so tests that reach it must opt in.
…ER_ENABLE

The oauth2 experiment no longer does anything. ReadExperiments drops it
from the result and logs one warning per process naming the flag, so an
admin whose OAuth2 clients start getting 404s after upgrading sees why.
The constant stays known for one release so the warning can be specific;
the next release removes it.
The deprecation warning promised removal in the next release, which no
ticket backed. Removal is now tracked in PLAT-635, so the message says a
future release and the code comment names the ticket.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Trim the doc comment on the message constant to its purpose so it
cannot drift from the literal. Assert the deprecation warning by count
instead of an exact warn slice, which coupled the test to the safety
classification of an unrelated experiment, and check explicitly that no
unknown-experiment warning leaks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Every coder server start logs one info line stating whether the OAuth2
provider is enabled, naming CODER_OAUTH2_PROVIDER_ENABLE. When the
provider is disabled and applications are still registered, one warning
gives the count and the flag to set. A failed query is logged and does
not abort startup.

The SpammyLogs test allows two more rows for the new line.
@linear-code

linear-code Bot commented Sep 12, 2026

Copy link
Copy Markdown

PLAT-492

@BobbyHo

BobbyHo commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@BobbyHo

BobbyHo commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@BobbyHo

BobbyHo commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

Experiments carry no compatibility guarantee and previously graduated
experiments were deleted outright, so the oauth2 experiment goes the same
way. The constant, its display name, the known-list entry and the
recognized no-op branch in ReadExperiments are gone, along with the
once-per-process deprecation warning and its tests.

A leftover CODER_EXPERIMENTS=oauth2 value is now handled like any other
unknown experiment: the server logs "ignoring unknown experiment" and
nothing gates on it. The startup provider-state lines and the release
note carry the migration message pointing at CODER_OAUTH2_PROVIDER_ENABLE.
@BobbyHo

BobbyHo commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review

coder-agents-review Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review in progress (16/16 reviewers complete) | View chat
Requested: 2026-09-14 16:27 UTC by @BobbyHo

deep-review v0.9.0 | Round 2 | bbaa055..3581cf8

Last posted: Round 2, 7 findings (1 P0, 1 P3, 4 Nit, 1 Note), COMMENT. Review

Finding inventory

Finding inventory - PR #29267

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P0 Author fixed (3581cf8); panel verified R2 coderd/oauth2_provider_state_internal_test.go:56 logRecorder undefined; coderd test package did not compile R1 Netero Yes
CRF-2 P3 Open coderd/oauth2_provider_state_internal_test.go:80 Test asserts only e.Message; flag field and query-error cause never verified R2 Bisky P3, Mafu-san P3, Chopper Nit Yes
CRF-3 Nit Open coderd/oauth2_provider_state.go:39 Disabled-with-apps warning interpolates count into text instead of a structured field R2 Kite, Chopper, Hisoka, Mafuuu Yes
CRF-4 Nit Open coderd/oauth2_provider_state.go:15 %d OAuth2 application(s) are registered reads wrong for exactly one app R2 Leorio, Ryosuke Yes
CRF-5 Nit Open coderd/oauth2_provider_state.go:13 Const doc comment restates the const name and message text R2 Gon (P2, downgraded) Yes
CRF-6 Nit Open coderd/oauth2_provider_state.go:23 flag variable holds a slog.Field, not a flag value; misleading name R2 Gon Yes
CRF-7 Note Open coderd/oauth2_provider_state.go:23 CODER_OAUTH2_PROVIDER_ENABLE literal duplicated, separate from canonical option def R2 Meruem Yes

Contested and acknowledged

None.

Round log

Round 1

Netero-only first pass. 1 P0. Reviewed against bbaa055..68a5306. P0 blocks panel per pre-panel Netero gate; posting first-pass review only. CI red (gen, lint, test-go-pg, test-go-pg-17, test-go-race-pg); the P0 is the root cause of the lint and test-go jobs.

Round 2 update

Churn guard: PROCEED. CRF-1 addressed in 3581cf8 (switched test to testutil.FakeSink); panel verified fixed at root cause, coverage 100% on LogOAuth2ProviderState. Panel of 14. New: 1 P3, 4 Nit, 1 Note posted. Gon P2 (const doc bloat) downgraded to Nit. Notes folded into body: Ryosuke (package home for the exported helper), Robin (a testutil level-filter predicate would retire the 4th hand-written copy). Reviewed against bbaa055..3581cf8. Event: COMMENT (no surviving P0-P2).

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

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.

First-pass review only. These are mechanical findings from Netero; the full review panel has not yet reviewed this PR and will do so after the first-pass finding is addressed.

The change itself is small and well-scoped: one startup log line recording whether the OAuth2 provider is enabled, a warning when it is disabled with apps still registered, and a table-driven test covering enabled, disabled-no-apps, disabled-with-apps, and query-error cases. The AsSystemRestricted startup read carries the right //nolint:gocritic justification, and the SpammyLogs threshold bump is explained by a comment.

One blocker: the new test references a logRecorder type that does not exist anywhere in the tree, so the coderd test package does not compile. This is the root cause of the failing lint and test-go CI jobs. gen also fails in CI; that may be independent and is worth checking separately.

Severity count: 1 P0.

As Netero put it: production code builds, so "the failure is isolated to this test file" but it takes the whole coderd test binary down with it.

🤖 This review was automatically generated with Coder Agents.

The test referenced a logRecorder type that was never defined, so the
coderd package failed to compile in test mode and every Go CI job broke.
Reuse the existing testutil.FakeSink instead of adding a new helper.
@BobbyHo

BobbyHo commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review

@coder-agents-review coder-agents-review Bot left a comment

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.

The panel reviewed this round; the P0 from round 1 is resolved. CRF-1 (undefined logRecorder) is verified fixed in 3581cf8: the test now uses the existing testutil.FakeSink, go test ./coderd/ -run TestLogOAuth2ProviderState passes, and LogOAuth2ProviderState reads 100% covered. The fix reuses infrastructure rather than adding a new helper, which is the right call.

The change is small, well-scoped, and honest. Pariston tried to build a case against it and could not: a default-off, startup-only flag that silently strands registered apps is correctly diagnosed, the log-line mechanism fits a boot-only value better than an audit row or settings page, and the PR description discloses those absences plainly. The AsSystemRestricted startup read is authorized correctly (ActionRead on ResourceOauth2App), carries an accurate //nolint:gocritic justification, and exposes only a count, not app contents.

Nothing here blocks. The remaining findings are one test-completeness gap and a cluster of convention nits, all in code the author should settle now since no follow-up round is assumed.

The strongest signal is a test that looks thorough but does not pin the feature's stated deliverable: the flag field. As Bisky put it, "Four rows, four genuinely different code paths... No costume jewelry", but the helper "throws away every field, so the flag field that is the whole point of the info line is never asserted." Chopper adds that the query-error branch would still pass if slog.Error(err) were dropped.

Two observations not worth an inline comment: the helper is exported from coderd for a single cli caller while its startup siblings are unexported cli helpers (Ryosuke: defensible, coderd.ReadExperiments is the counter-precedent), and the level-filter predicate in the test is now the fourth hand-written copy in the repo (Robin: a shared testutil AtLevel(level) predicate would retire all four next time someone touches that package).

Severity count: 1 P3, 4 Nit, 1 Note.

🤖 This review was automatically generated with Coder Agents.

Comment thread coderd/oauth2_provider_state.go Resolved
Comment thread coderd/oauth2_provider_state.go Resolved
Comment thread coderd/oauth2_provider_state.go Resolved
Comment thread coderd/oauth2_provider_state.go Resolved
Comment thread coderd/oauth2_provider_state.go Resolved
Move the registered application count from the warning text into a
structured field so the message is static, rename the flag field
variable, drop the redundant const comment, and assert the logged fields
in the test.
BobbyHo added a commit that referenced this pull request Sep 14, 2026
…ENABLE (#29257)

Third of five for PLAT-492. Removes the oauth2 experiment entirely; CODER_EXPERIMENTS=oauth2 is now treated as an unknown experiment and nothing depends on it.

Stacked on #29251. No migration.
Removes ExperimentOAuth2 and its generated/API references.
Removed outright per review, consistent with experiments having no compatibility guarantee.
Migration guidance is covered by the startup logging in #29267 and docs/release notes in #29268, both pointing to CODER_OAUTH2_PROVIDER_ENABLE.
Existing unknown-experiment handling and tests already cover leftover oauth2 values.
After this merges, main is safe to cut a release from.
Base automatically changed from plat-492-3-deprecate-experiment to main September 14, 2026 21:10
@BobbyHo
BobbyHo marked this pull request as ready for review September 14, 2026 21:10

@dylanhuff-at-coder dylanhuff-at-coder left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One non-blocking comment on the startup warning, otherwise lgtm

Comment thread coderd/oauth2_provider_state.go Resolved
…survive disable

Disabling the provider blocks new authorizations and token exchanges but
does not invalidate already-issued access tokens, which keep authenticating
API requests until they expire or are revoked. The prior wording implied
existing authorizations stopped working entirely.
@BobbyHo
BobbyHo merged commit 7bb049f into main Sep 15, 2026
27 of 28 checks passed
@BobbyHo
BobbyHo deleted the plat-492-4-startup-lines branch September 15, 2026 01:31
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants