-
Notifications
You must be signed in to change notification settings - Fork 7
feat: Add OAuth2 authentication flow for Coder #151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
b75669e
chore: fix dev server config
f0ssel 04d9ab2
feat: Add OAuth2 authentication flow for Coder
f0ssel 9e09c3e
tsc
f0ssel f7c5cec
fix: make clientId available via app-config file
buenos-nachos 6e50b24
fix: format package.json file
buenos-nachos 90695ae
fix: clean up CoderAuthInputForm
buenos-nachos 76bec6a
fix: update URL serialization
buenos-nachos c77b45f
refactor: clean up router
buenos-nachos 5d45128
fix: get all tests passing
buenos-nachos e6a2bd9
fix: update types for setup file
buenos-nachos 216b4e5
fix: update coder logo
buenos-nachos 993fb2b
docs: add new instructions
buenos-nachos dc8d0de
Merge branch 'f0ssel/oauth2' of github.com:coder/backstage-plugins in…
buenos-nachos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,3 +2,5 @@ dist | |
| dist-types | ||
| coverage | ||
| .vscode | ||
| .coder.yaml | ||
| app-config.local.yaml | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,13 @@ app: | |
| organization: | ||
| name: Coder | ||
|
|
||
| coder: | ||
| deployment: | ||
| accessUrl: https://dev.coder.com | ||
| oauth: | ||
| clientId: ${CODER_OAUTH_CLIENT_ID:-backstage} | ||
| clientSecret: ${CODER_OAUTH_CLIENT_SECRET:-change-me} | ||
|
Comment on lines
+8
to
+13
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure if this should be here or somewhere else, but is useful for development. |
||
|
|
||
| backend: | ||
| # Used for enabling authentication, secret is shared by all backend plugins | ||
| # See https://backstage.io/docs/auth/service-to-service-auth for | ||
|
|
@@ -15,8 +22,7 @@ backend: | |
| baseUrl: http://localhost:7007 | ||
| listen: | ||
| port: 7007 | ||
| # Uncomment the following host directive to bind to specific interfaces | ||
| # host: 127.0.0.1 | ||
| host: localhost | ||
| csp: | ||
| connect-src: ["'self'", 'http:', 'https:'] | ||
| # Content-Security-Policy directives follow the Helmet format: https://helmetjs.github.io/#reference | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| module.exports = require('@backstage/cli/config/eslint-factory')(__dirname); | ||
f0ssel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # `backstage-plugin-coder-backend` | ||
|
|
||
| > [!NOTE] | ||
| > This plugin is designed to be the backend counterpart of `backstage-plugin-coder`. In the future, this plugin may become more standalone, but for now, all functionality requires that you also have `backstage-plugin-coder` installed. [See that plugin's setup instructions](../backstage-plugin-coder/README.md#setup) for more information. | ||
|
|
||
| ## Features | ||
|
|
||
| - Management of OAuth2 state for requests sent from the Backstage backend. | ||
|
|
||
| ## Installing the plugin to support oauth2 | ||
|
|
||
| 1. Run the following command from your Backstage app to install the plugin: | ||
| ```bash | ||
| yarn --cwd packages/app add @coder/backstage-plugin-coder | ||
| ``` | ||
| 2. Import the `createRouter` function from the `@coder/backstage-plugin-coder` package: | ||
| ```ts | ||
| // Imports can be renamed if there would be a name conflict | ||
| import { createRouter as createCoderRouter } from '@coder/backstage-plugin-coder-backend'; | ||
| ``` | ||
| 3. Add support for Coder hot module reloading to `main` function in your deployment's `backend/src/index.ts` file: | ||
| ```ts | ||
| const coderEnv = useHotMemoize(module, () => createEnv('coder')); | ||
| ``` | ||
| 4. Register the plugin's oauth route with Backstage from inside the same `main` function: | ||
| ```ts | ||
| apiRouter.use( | ||
| '/auth/coder', | ||
| await createCoderRouter({ | ||
| logger: coderEnv.logger, | ||
| config: coderEnv.config, | ||
| }), | ||
| ); | ||
| ``` | ||
| 5. [If you haven't already, be sure to register Backstage as an oauth app through Coder](https://coder.com/docs/admin/integrations/oauth2-provider). | ||
| 6. Add the following values to one of your `app-config.yaml` files: | ||
| ```yaml | ||
| coder: | ||
| deployment: | ||
| # Change the value to match your Coder deployment | ||
| accessUrl: https://dev.coder.com | ||
| oauth: | ||
| clientId: oauth2-client-id-goes-here | ||
| # The client secret isn't used by the frontend plugin, but the backend | ||
| # plugin needs it for oauth functionality to work | ||
| clientSecret: oauth2-secret-goes-here | ||
| ``` | ||
|
|
||
| Note that the `clientSecret` value is given `secret`-level visibility, and will never be logged anywhere by Backstage. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| { | ||
| "name": "@coder/backstage-plugin-coder-backend", | ||
| "description": "Backend plugin for Coder OAuth2 authentication flow", | ||
| "version": "0.0.0", | ||
| "main": "src/index.ts", | ||
| "types": "src/index.ts", | ||
| "license": "Apache-2.0", | ||
| "publishConfig": { | ||
| "access": "public", | ||
| "main": "dist/index.cjs.js", | ||
| "types": "dist/index.d.ts" | ||
| }, | ||
| "backstage": { | ||
| "role": "backend-plugin" | ||
| }, | ||
| "scripts": { | ||
| "start": "backstage-cli package start", | ||
| "build": "backstage-cli package build", | ||
| "lint": "backstage-cli package lint", | ||
| "test": "backstage-cli package test", | ||
| "clean": "backstage-cli package clean", | ||
| "prepack": "backstage-cli package prepack", | ||
| "postpack": "backstage-cli package postpack" | ||
| }, | ||
| "dependencies": { | ||
| "@backstage/backend-common": "^0.20.1", | ||
| "@backstage/config": "^1.1.1", | ||
| "@backstage/errors": "^1.2.3", | ||
| "@types/express": "*", | ||
| "express": "^4.17.1", | ||
| "express-promise-router": "^4.1.0", | ||
| "winston": "^3.2.1", | ||
| "axios": "^1.6.8" | ||
| }, | ||
| "devDependencies": { | ||
| "@backstage/cli": "^0.25.1", | ||
| "@types/supertest": "^2.0.12", | ||
| "supertest": "^6.2.4" | ||
| }, | ||
| "files": [ | ||
| "dist" | ||
| ], | ||
| "keywords": [ | ||
| "backstage", | ||
| "coder", | ||
| "oauth2", | ||
| "authentication" | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| /** | ||
| * Backend plugin for Coder OAuth2 authentication | ||
| * | ||
| * @packageDocumentation | ||
| */ | ||
|
|
||
| export { createRouter } from './service/router'; |
136 changes: 136 additions & 0 deletions
136
plugins/backstage-plugin-coder-backend/src/service/router.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { errorHandler } from '@backstage/backend-common'; | ||
| import { Config } from '@backstage/config'; | ||
| import express from 'express'; | ||
| import Router from 'express-promise-router'; | ||
| import { Logger } from 'winston'; | ||
| import axios, { type AxiosResponse } from 'axios'; | ||
|
|
||
| export interface RouterOptions { | ||
| logger: Logger; | ||
| config: Config; | ||
| } | ||
|
|
||
| export async function createRouter( | ||
| options: RouterOptions, | ||
| ): Promise<express.Router> { | ||
| const { logger, config } = options; | ||
|
|
||
| const router = Router(); | ||
| router.use(express.json()); | ||
|
|
||
| // OAuth callback endpoint | ||
| router.get('/oauth/callback', async (req, res) => { | ||
| const { code } = req.query; | ||
|
|
||
| if (!code || typeof code !== 'string') { | ||
| logger.error('OAuth callback missing authorization code'); | ||
| res.status(400).send('Missing authorization code'); | ||
| return; | ||
| } | ||
|
|
||
| const coderConfig = config.getOptionalConfig('coder'); | ||
| const accessUrl = coderConfig?.getString('deployment.accessUrl') || ''; | ||
| const clientId = coderConfig?.getString('oauth.clientId') || ''; | ||
| const clientSecret = coderConfig?.getString('oauth.clientSecret') || ''; | ||
| const redirectUri = `${req.protocol}://${req.get( | ||
| 'host', | ||
| )}/api/auth/coder/oauth/callback`; | ||
|
|
||
| let tokenResponse: AxiosResponse<{ access_token?: string }, unknown>; | ||
| try { | ||
| // Exchange authorization code for access token | ||
| tokenResponse = await axios.post( | ||
| `${accessUrl}/oauth2/tokens`, | ||
| new URLSearchParams({ | ||
| grant_type: 'authorization_code', | ||
| code, | ||
| redirect_uri: redirectUri, | ||
| client_id: clientId, | ||
| client_secret: clientSecret, | ||
| }), | ||
| { | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded', | ||
| }, | ||
| }, | ||
| ); | ||
| } catch (error) { | ||
| logger.error('OAuth token exchange failed', error); | ||
| res | ||
| .status(500) | ||
| .send( | ||
| `<html><body><h1>Authentication failed</h1><p>${ | ||
| error instanceof Error ? error.message : 'Unknown error' | ||
| }</p></body></html>`, | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| const { access_token } = tokenResponse.data; | ||
| if (!access_token) { | ||
| const message = 'Coder deployment did not respond with access token'; | ||
| logger.error(message); | ||
| res.status(502).send( | ||
| `<!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <title>Authentication Failed</title> | ||
| </head> | ||
| <body> | ||
| <h1>Authentication failed</h1> | ||
| <p>${message}</p> | ||
| </body> | ||
| </html>`, | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| // Return HTML that sends the token to the opener window via postMessage | ||
| res.setHeader('Content-Security-Policy', "script-src 'unsafe-inline'"); | ||
| res.send(` | ||
| <!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <title>Authentication Successful</title> | ||
| </head> | ||
| <body> | ||
| <p>Authentication successful! This window will close automatically...</p> | ||
| <script> | ||
| (function() { | ||
| // Send token to opener window via postMessage | ||
| if (window.opener) { | ||
| var targetOrigin; | ||
| try { | ||
| // Try to get the opener's origin | ||
| targetOrigin = window.opener.location.origin; | ||
| } catch (e) { | ||
| // If we can't access it due to cross-origin, use wildcard | ||
| // This is safe since we're only sending to our own opener | ||
| targetOrigin = '*'; | ||
| } | ||
|
|
||
| window.opener.postMessage( | ||
| { type: 'coder-oauth-success', token: '${access_token}' }, | ||
| targetOrigin | ||
| ); | ||
| setTimeout(function() { window.close(); }, 500); | ||
| } else { | ||
| document.body.innerHTML = '<p>Authentication successful! You can close this window.</p>'; | ||
| } | ||
| })(); | ||
| </script> | ||
| </body> | ||
| </html> | ||
| `); | ||
|
|
||
| logger.info('OAuth authentication successful'); | ||
| }); | ||
|
|
||
| router.get('/health', (_, response) => { | ||
| logger.info('Health check'); | ||
| response.json({ status: 'ok' }); | ||
| }); | ||
|
|
||
| router.use(errorHandler()); | ||
| return router; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe unused