|
| 1 | +# Enterprise OAuth PKCE Design |
| 2 | + |
| 3 | +Date: 2026-07-04 |
| 4 | +Status: Design approved in discussion; written spec pending user review |
| 5 | + |
| 6 | +## Summary |
| 7 | + |
| 8 | +Add OAuth Authorization Code flow with PKCE for Stack Overflow Internal Enterprise API v3 authentication. The flow follows the Stack Enterprise support article "Secure API Token Generation with OAuth and PKCE" and replaces manual Enterprise access-token entry for v3-only workflows. |
| 9 | + |
| 10 | +The first implementation targets Enterprise v3-only workflows, starting with Enterprise User Group Sync. Existing API key support remains for Enterprise workflows that still call Stack API v2.3. Stack Overflow Basic/Business workflows keep personal access token authentication because OAuth is not available for those tiers. |
| 11 | + |
| 12 | +## Goals |
| 13 | + |
| 14 | +- Provide a first-party OAuth PKCE connection flow for Enterprise API v3. |
| 15 | +- Use PKCE with S256, a random state value, and no client secret. |
| 16 | +- Store OAuth access tokens in browser session memory only, consistent with the current credential model. |
| 17 | +- Request minimum scopes by default. |
| 18 | +- Request `write_access` for User Group Sync. |
| 19 | +- Include `no_expiry` only when the user explicitly opts in. |
| 20 | +- Keep API key support for Enterprise v2.3 and mixed v2.3/v3 workflows. |
| 21 | +- Keep PAT support for Stack Overflow Basic/Business workflows. |
| 22 | +- Remove or hide direct manual Enterprise access-token entry from the normal credentials form. |
| 23 | + |
| 24 | +## Non-Goals |
| 25 | + |
| 26 | +- No OAuth support for Stack Overflow Basic/Business. |
| 27 | +- No refresh-token handling; the documented Enterprise response provides an access token and optional expiry. |
| 28 | +- No persisted credentials in local storage, indexed DB, cookies, or server-side storage. |
| 29 | +- No replacement for Enterprise API key authentication where v2.3 endpoints are still required. |
| 30 | +- No broad rewrite of report collection from v2.3 to v3. |
| 31 | +- No support for non-PKCE client-secret token exchange. |
| 32 | + |
| 33 | +## Source Documentation |
| 34 | + |
| 35 | +The design is based on Stack Overflow's Enterprise PKCE documentation: |
| 36 | + |
| 37 | +- https://support.stackenterprise.co/support/solutions/articles/22000294542-secure-api-token-generation-with-oauth-and-pkce |
| 38 | + |
| 39 | +Key requirements from that document: |
| 40 | + |
| 41 | +- Enterprise authorization starts at `https://[your_site].stackenterprise.co/oauth`. |
| 42 | +- PKCE uses a generated `code_verifier`, derived `code_challenge`, and `code_challenge_method=S256`. |
| 43 | +- PKCE token exchange does not require `client_secret`. |
| 44 | +- Token exchange uses `https://[your_site].stackenterprise.co/oauth/access_token/json`. |
| 45 | +- The access token response includes `access_token` and may include `expires`. |
| 46 | +- Tokens expire after 24 hours unless the request includes `no_expiry`. |
| 47 | +- `no_expiry` is discouraged unless the app actually requires it. |
| 48 | + |
| 49 | +## Recommended Approach |
| 50 | + |
| 51 | +Use a server-mediated PKCE callback. |
| 52 | + |
| 53 | +The browser collects Enterprise instance URL, OAuth client ID, scope choices, and the explicit `no_expiry` preference. The app starts OAuth by generating PKCE state and verifier data, then redirecting to the Enterprise authorization URL. After approval, Enterprise redirects back to the app. A Next.js callback route validates state, exchanges the authorization code with the Enterprise token endpoint, and gives the browser the resulting session credential. |
| 54 | + |
| 55 | +This approach fits the app's current same-origin Next API route pattern and avoids depending on Enterprise token endpoint CORS behavior in the browser. |
| 56 | + |
| 57 | +## User Flow |
| 58 | + |
| 59 | +1. User opens the Credentials panel. |
| 60 | +2. User selects `Enterprise` as the instance type. |
| 61 | +3. User enters the Enterprise instance URL. |
| 62 | +4. User enters the OAuth Client ID from their Enterprise API application. |
| 63 | +5. User chooses the workflow or scope level. |
| 64 | +6. User leaves `no_expiry` unchecked unless they explicitly need a non-expiring token. |
| 65 | +7. User clicks `Connect with Enterprise OAuth`. |
| 66 | +8. App redirects to `https://[site].stackenterprise.co/oauth` with: |
| 67 | + - `client_id` |
| 68 | + - `redirect_uri` |
| 69 | + - `scope` |
| 70 | + - `code_challenge` |
| 71 | + - `code_challenge_method=S256` |
| 72 | + - `state` |
| 73 | +9. Enterprise prompts login and authorization. |
| 74 | +10. Enterprise redirects back to the app callback route with `code` and `state`. |
| 75 | +11. The callback route validates state and exchanges the code at `https://[site].stackenterprise.co/oauth/access_token/json`. |
| 76 | +12. The app stores the returned token in session state as the Enterprise v3 credential. |
| 77 | +13. User returns to the v3-only workflow and can run it without pasting an access token. |
| 78 | + |
| 79 | +If authorization fails, is denied, or is cancelled, the app returns to Credentials with a clear status message and leaves existing credentials unchanged. |
| 80 | + |
| 81 | +## Credential Lanes |
| 82 | + |
| 83 | +The app will make the authentication lane explicit by instance type and workflow. |
| 84 | + |
| 85 | +### Stack Overflow Basic/Business |
| 86 | + |
| 87 | +Basic/Business workflows continue to use PAT authentication. The credentials form shows the PAT field for Basic/Business and does not offer Enterprise OAuth. |
| 88 | + |
| 89 | +Validation requires a PAT for live API calls against Basic/Business. |
| 90 | + |
| 91 | +### Stack Overflow Enterprise v3-only |
| 92 | + |
| 93 | +Enterprise v3-only workflows use OAuth PKCE. User Group Sync is the first target workflow. |
| 94 | + |
| 95 | +The credentials form shows: |
| 96 | + |
| 97 | +- Instance URL. |
| 98 | +- OAuth Client ID. |
| 99 | +- OAuth connect button. |
| 100 | +- Scope controls, including an explicit `no_expiry` opt-in. |
| 101 | + |
| 102 | +The form does not ask the user to paste an Enterprise access token directly. The access token is produced by OAuth PKCE and stored in memory. |
| 103 | + |
| 104 | +Validation requires a non-expired OAuth PKCE token. |
| 105 | + |
| 106 | +### Stack Overflow Enterprise v2.3 Or Mixed v2.3/v3 |
| 107 | + |
| 108 | +Enterprise workflows that still call v2.3 keep API key support. If a mixed workflow also needs v3, it should use OAuth PKCE for the v3 token and API key for v2.3. |
| 109 | + |
| 110 | +Validation requires: |
| 111 | + |
| 112 | +- API key when the workflow calls v2.3 Enterprise endpoints. |
| 113 | +- Non-expired OAuth PKCE token when the workflow calls v3 Enterprise endpoints. |
| 114 | + |
| 115 | +## Data Model |
| 116 | + |
| 117 | +Extend `SessionCredentials` without removing current manual credential fields needed by existing workflows. |
| 118 | + |
| 119 | +```ts |
| 120 | +interface SessionCredentials { |
| 121 | + instanceType: InstanceType; |
| 122 | + baseUrl: string; |
| 123 | + apiKey?: string; |
| 124 | + pat?: string; |
| 125 | + accessToken?: string; |
| 126 | + authSource?: "manual-pat" | "oauth-pkce"; |
| 127 | + oauthClientId?: string; |
| 128 | + oauthScopes?: string[]; |
| 129 | + accessTokenExpiresAt?: string; |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +`accessToken` remains in the model as the internal bearer token used by API v3 clients, but it is no longer a normal user-entered field for Enterprise. |
| 134 | + |
| 135 | +`accessTokenExpiresAt` is derived from the Enterprise token response's `expires` value when present. If the user opts into `no_expiry`, the response may omit `expires`; in that case the session credential has no expiration timestamp. |
| 136 | + |
| 137 | +## Scope Rules |
| 138 | + |
| 139 | +The app builds scopes from workflow requirements. |
| 140 | + |
| 141 | +- Read-only v3 workflows request the minimum read scope required by that workflow. |
| 142 | +- User Group Sync requests `write_access`. |
| 143 | +- `team_access` is reserved for future private-team-specific workflows. |
| 144 | +- `private_info` is not requested by default. |
| 145 | +- `read_inbox` is not requested by default. |
| 146 | +- `no_expiry` is included only when the user checks an explicit opt-in control. |
| 147 | + |
| 148 | +Multiple scopes are sent as comma-delimited values with no spaces, matching the Enterprise documentation. |
| 149 | + |
| 150 | +## New Architecture Units |
| 151 | + |
| 152 | +### `src/auth/oauthPkce.ts` |
| 153 | + |
| 154 | +Responsibilities: |
| 155 | + |
| 156 | +- Generate PKCE code verifier. |
| 157 | +- Derive S256 code challenge from verifier. |
| 158 | +- Generate random state values. |
| 159 | +- Build Enterprise authorization URLs. |
| 160 | +- Build Enterprise token endpoint URLs. |
| 161 | +- Normalize and validate OAuth scope arrays. |
| 162 | + |
| 163 | +### `src/server/oauthPkceApi.ts` |
| 164 | + |
| 165 | +Responsibilities: |
| 166 | + |
| 167 | +- Handle OAuth start requests in pure, testable functions. |
| 168 | +- Validate Enterprise instance URL and client ID. |
| 169 | +- Reject non-Enterprise OAuth targets. |
| 170 | +- Create pending OAuth transaction payloads. |
| 171 | +- Handle callback requests in pure, testable functions. |
| 172 | +- Validate callback state. |
| 173 | +- Exchange authorization code for JSON token response. |
| 174 | +- Redact sensitive OAuth material from errors. |
| 175 | + |
| 176 | +### `src/app/api/oauth/pkce/start/route.ts` |
| 177 | + |
| 178 | +Responsibilities: |
| 179 | + |
| 180 | +- Accept same-origin OAuth start requests from the browser. |
| 181 | +- Delegate to `src/server/oauthPkceApi.ts`. |
| 182 | +- Set a short-lived HTTP-only pending OAuth cookie. |
| 183 | +- Return the Enterprise authorization URL. |
| 184 | + |
| 185 | +### `src/app/api/oauth/pkce/callback/route.ts` |
| 186 | + |
| 187 | +Responsibilities: |
| 188 | + |
| 189 | +- Receive Enterprise redirect requests with `code`, `state`, or OAuth error query parameters. |
| 190 | +- Delegate to `src/server/oauthPkceApi.ts`. |
| 191 | +- Return a small callback page that forwards the outcome to the opener or redirects back to the app credentials panel. |
| 192 | + |
| 193 | +### `src/components/CredentialsPanel.tsx` |
| 194 | + |
| 195 | +Responsibilities: |
| 196 | + |
| 197 | +- Present PAT entry for Basic/Business. |
| 198 | +- Present Enterprise OAuth PKCE controls for Enterprise. |
| 199 | +- Keep API key entry available for Enterprise workflows that need v2.3. |
| 200 | +- Hide direct manual Enterprise access-token entry from the normal flow. |
| 201 | +- Show OAuth connection state, token expiry, and reconnect actions. |
| 202 | + |
| 203 | +### `src/credentials/credentialRules.ts` |
| 204 | + |
| 205 | +Responsibilities: |
| 206 | + |
| 207 | +- Validate Business/Basic PAT requirements. |
| 208 | +- Validate Enterprise v3 OAuth token requirements. |
| 209 | +- Validate Enterprise v2.3 API key requirements. |
| 210 | +- Reject expired OAuth credentials with an actionable reconnect message. |
| 211 | + |
| 212 | +## Pending OAuth State |
| 213 | + |
| 214 | +Pending OAuth data should be stored in a short-lived HTTP-only cookie created by the OAuth start route and cleared by the callback route. This keeps the verifier available to the server-mediated callback without adding persisted server storage. |
| 215 | + |
| 216 | +The pending cookie stores only OAuth transaction data, not long-lived credentials: |
| 217 | + |
| 218 | +- Enterprise base URL. |
| 219 | +- OAuth client ID. |
| 220 | +- Requested scopes. |
| 221 | +- Redirect URI. |
| 222 | +- State. |
| 223 | +- Code verifier. |
| 224 | +- Created-at timestamp or expiration timestamp. |
| 225 | + |
| 226 | +The cookie must preserve these properties: |
| 227 | + |
| 228 | +- State is random and non-guessable. |
| 229 | +- State is validated before token exchange. |
| 230 | +- Code verifier is never logged. |
| 231 | +- Code verifier is cleared after success or failure. |
| 232 | +- Pending OAuth transactions expire quickly, with a target max age of 10 minutes. |
| 233 | +- Cookie attributes are `HttpOnly`, `SameSite=Lax`, and `Secure` when served over HTTPS. |
| 234 | +- Pending OAuth transaction data is not reused after a callback succeeds or fails. |
| 235 | + |
| 236 | +## Error Handling |
| 237 | + |
| 238 | +- Invalid Enterprise URL: reject before OAuth start. |
| 239 | +- Non-Stack Enterprise host for OAuth: reject before redirect. |
| 240 | +- Missing client ID: block OAuth start with a clear message. |
| 241 | +- Missing or mismatched state: reject callback and do not save credentials. |
| 242 | +- Missing pending code verifier: reject callback and do not save credentials. |
| 243 | +- OAuth denial or cancellation: return to Credentials with a clear failure status. |
| 244 | +- Token exchange failure: surface a safe error message with `code`, `code_verifier`, and tokens redacted. |
| 245 | +- Missing `access_token` in token response: reject as an invalid OAuth response. |
| 246 | +- Expired OAuth token: block v3-only workflows and prompt reconnect. |
| 247 | +- Network failure during exchange: return a retryable OAuth failure message. |
| 248 | + |
| 249 | +## Testing |
| 250 | + |
| 251 | +Unit tests: |
| 252 | + |
| 253 | +- PKCE verifier generation produces URL-safe values with sufficient entropy. |
| 254 | +- PKCE challenge generation uses SHA-256 and base64url encoding. |
| 255 | +- Enterprise authorization URL includes client ID, redirect URI, scopes, state, challenge, and `code_challenge_method=S256`. |
| 256 | +- Enterprise token endpoint URL targets `/oauth/access_token/json`. |
| 257 | +- Scope normalization omits `no_expiry` unless explicitly requested. |
| 258 | +- OAuth start rejects malformed URLs, non-Enterprise hosts, and missing client IDs. |
| 259 | +- OAuth callback rejects missing code, mismatched state, and missing verifier. |
| 260 | +- OAuth callback returns a session credential on successful token exchange. |
| 261 | +- OAuth callback redacts sensitive values from exchange errors. |
| 262 | +- Credential validation requires PAT for Basic/Business live calls. |
| 263 | +- Credential validation requires non-expired OAuth PKCE token for Enterprise v3-only workflows. |
| 264 | +- Credential validation still requires API key for Enterprise v2.3 workflows. |
| 265 | +- Credential validation rejects expired OAuth tokens. |
| 266 | + |
| 267 | +UI tests: |
| 268 | + |
| 269 | +- Basic/Business credentials show PAT and hide Enterprise OAuth controls. |
| 270 | +- Enterprise credentials show OAuth controls and API key support. |
| 271 | +- Direct Enterprise access-token entry is not shown in the normal credentials form. |
| 272 | +- User Group Sync accepts OAuth-produced access tokens. |
| 273 | +- User Group Sync blocks missing or expired OAuth credentials. |
| 274 | +- `no_expiry` is unchecked by default and only appears in requested scopes after explicit opt-in. |
| 275 | + |
| 276 | +## Security Notes |
| 277 | + |
| 278 | +- Do not log access tokens, authorization codes, code verifiers, or raw token exchange URLs. |
| 279 | +- Redact sensitive OAuth values from server and browser-visible errors. |
| 280 | +- Keep credentials in memory only. |
| 281 | +- Do not introduce a client secret path for PKCE. |
| 282 | +- Require HTTPS Stack Enterprise instance URLs for OAuth. |
| 283 | +- Keep the existing non-Enterprise host rejection posture for guarded write workflows. |
| 284 | + |
| 285 | +## Rollout |
| 286 | + |
| 287 | +The first implementation should wire OAuth PKCE into the Credentials panel and User Group Sync. Mixed v2.3/v3 reporting workflows keep API key entry for v2.3 and can consume OAuth-produced v3 tokens when available. Their report-specific UX can be refined after the first User Group Sync path proves the OAuth flow. |
| 288 | + |
| 289 | +Future v3-only workflows can reuse the OAuth helper functions and credential validation rules. |
0 commit comments