Skip to content

feat: add github device flow for authentication #8232

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 17 commits into from
Jun 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Redesign the git auth page
  • Loading branch information
kylecarbs committed Jun 27, 2023
commit 0af6a37dca1591fde788e0ccd830f75c07ca7d63
4 changes: 4 additions & 0 deletions cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ func ReadGitAuthProvidersFromEnv(environ []string) ([]codersdk.GitAuthConfig, er
provider.NoRefresh = b
case "SCOPES":
provider.Scopes = strings.Split(v.Value, " ")
case "APP_INSTALL_URL":
provider.AppInstallURL = v.Value
case "APP_INSTALLATIONS_URL":
provider.AppInstallationsURL = v.Value
}
providers[providerNum] = provider
}
Expand Down
6 changes: 6 additions & 0 deletions coderd/apidoc/docs.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions coderd/apidoc/swagger.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion coderd/gitauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ func (api *API) gitAuthByID(w http.ResponseWriter, r *http.Request) {
res := codersdk.GitAuth{
Authenticated: false,
Device: config.DeviceAuth != nil,
AppInstallURL: config.AppInstallURL,
Type: config.Type.Pretty(),
}

link, err := api.Database.GetGitAuthLink(ctx, database.GetGitAuthLinkParams{
Expand All @@ -37,7 +39,7 @@ func (api *API) gitAuthByID(w http.ResponseWriter, r *http.Request) {
return err
})
eg.Go(func() (err error) {
res.AppInstallations, err = config.AppInstallations(ctx, link.OAuthAccessToken)
res.AppInstallations, res.AppInstallable, err = config.AppInstallations(ctx, link.OAuthAccessToken)
return err
})
err = eg.Wait()
Expand Down
22 changes: 12 additions & 10 deletions coderd/gitauth/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type Config struct {
// returning it to the user. If omitted, tokens will
// not be validated before being returned.
ValidateURL string
// InstallURL is for GitHub App's (and hopefully others eventually)
// AppInstallURL is for GitHub App's (and hopefully others eventually)
// to provide a link to install the app. There's installation
// of the application, and user authentication. It's possible
// for the user to authenticate but the application to not.
Expand Down Expand Up @@ -155,29 +155,31 @@ type AppInstallation struct {

// AppInstallations returns a list of app installations for the given token.
// If the provider does not support app installations, it returns nil.
func (c *Config) AppInstallations(ctx context.Context, token string) ([]codersdk.GitAuthAppInstallation, error) {
func (c *Config) AppInstallations(ctx context.Context, token string) ([]codersdk.GitAuthAppInstallation, bool, error) {
if c.AppInstallationsURL == "" {
return nil, nil
return nil, false, nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.AppInstallationsURL, nil)
if err != nil {
return nil, err
return nil, false, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
return nil, false, err
}
defer res.Body.Close()

installs := []codersdk.GitAuthAppInstallation{}
if c.Type == codersdk.GitProviderGitHub {
var ghInstalls []github.Installation
var ghInstalls struct {
Installations []*github.Installation `json:"installations"`
}
err = json.NewDecoder(res.Body).Decode(&ghInstalls)
if err != nil {
return nil, err
return nil, false, err
}
for _, installation := range ghInstalls {
for _, installation := range ghInstalls.Installations {
install := codersdk.GitAuthAppInstallation{
ID: int(installation.GetID()),
ConfigureURL: installation.GetHTMLURL(),
Expand All @@ -194,7 +196,7 @@ func (c *Config) AppInstallations(ctx context.Context, token string) ([]codersdk
installs = append(installs, install)
}
}
return installs, nil
return installs, true, nil
}

// ConvertConfig converts the SDK configuration entry format
Expand Down Expand Up @@ -301,7 +303,7 @@ func ConvertConfig(entries []codersdk.GitAuthConfig, accessURL *url.URL) ([]*Con
}
cfg.DeviceAuth = &DeviceAuth{
ClientID: entry.ClientID,
TokenURL: entry.TokenURL,
TokenURL: oc.Endpoint.TokenURL,
Scopes: entry.Scopes,
CodeURL: entry.DeviceAuthURL,
}
Expand Down
17 changes: 11 additions & 6 deletions codersdk/gitauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@ import (
)

type GitAuth struct {
Authenticated bool `json:"authenticated"`
Device bool `json:"device"`
Authenticated bool `json:"authenticated"`
Device bool `json:"device"`
Type string `json:"type"`

// User is the user that authenticated with the provider.
User *GitAuthUser `json:"user"`
// AppInstallable is true if the request for app installs was successful.
AppInstallable bool `json:"app_installable"`
// AppInstallations are the installations that the user has access to.
AppInstallations []GitAuthAppInstallation `json:"installations"`
// AppInstallURL is the URL to install the app.
AppInstallURL string `json:"app_install_url"`
}

type GitAuthAppInstallation struct {
Expand All @@ -24,10 +29,10 @@ type GitAuthAppInstallation struct {
}

type GitAuthUser struct {
Login string
AvatarURL string
ProfileURL string
Name string
Login string `json:"login"`
AvatarURL string `json:"avatar_url"`
ProfileURL string `json:"profile_url"`
Name string `json:"name"`
}

// GitAuthDevice is the response from the device authorization endpoint.
Expand Down
2 changes: 2 additions & 0 deletions docs/api/general.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ curl -X GET http://coder-server:8080/api/v2/deployment/config \
"git_auth": {
"value": [
{
"app_install_url": "string",
"app_installations_url": "string",
"auth_url": "string",
"client_id": "string",
"device_auth_url": "string",
Expand Down
36 changes: 23 additions & 13 deletions docs/api/schemas.md
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,8 @@
{
"value": [
{
"app_install_url": "string",
"app_installations_url": "string",
"auth_url": "string",
"client_id": "string",
"device_auth_url": "string",
Expand Down Expand Up @@ -1879,6 +1881,8 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
"git_auth": {
"value": [
{
"app_install_url": "string",
"app_installations_url": "string",
"auth_url": "string",
"client_id": "string",
"device_auth_url": "string",
Expand Down Expand Up @@ -2212,6 +2216,8 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in
"git_auth": {
"value": [
{
"app_install_url": "string",
"app_installations_url": "string",
"auth_url": "string",
"client_id": "string",
"device_auth_url": "string",
Expand Down Expand Up @@ -2581,6 +2587,8 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in

```json
{
"app_install_url": "string",
"app_installations_url": "string",
"auth_url": "string",
"client_id": "string",
"device_auth_url": "string",
Expand All @@ -2597,19 +2605,21 @@ AuthorizationObject can represent a "set" of objects, such as: all workspaces in

### Properties

| Name | Type | Required | Restrictions | Description |
| ----------------- | --------------- | -------- | ------------ | ----------- |
| `auth_url` | string | false | | |
| `client_id` | string | false | | |
| `device_auth_url` | string | false | | |
| `device_flow` | boolean | false | | |
| `id` | string | false | | |
| `no_refresh` | boolean | false | | |
| `regex` | string | false | | |
| `scopes` | array of string | false | | |
| `token_url` | string | false | | |
| `type` | string | false | | |
| `validate_url` | string | false | | |
| Name | Type | Required | Restrictions | Description |
| ----------------------- | --------------- | -------- | ------------ | ----------- |
| `app_install_url` | string | false | | |
| `app_installations_url` | string | false | | |
| `auth_url` | string | false | | |
| `client_id` | string | false | | |
| `device_auth_url` | string | false | | |
| `device_flow` | boolean | false | | |
| `id` | string | false | | |
| `no_refresh` | boolean | false | | |
| `regex` | string | false | | |
| `scopes` | array of string | false | | |
| `token_url` | string | false | | |
| `type` | string | false | | |
| `validate_url` | string | false | | |

## codersdk.GitProvider

Expand Down
7 changes: 1 addition & 6 deletions site/src/AppRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,7 @@ export const AppRouter: FC = () => {
<Route element={<DashboardLayout />}>
<Route index element={<IndexPage />} />

<Route path="gitauth">
<Route index element={<GitAuthPage />} />
<Route path=":provider">
<Route path="device" element={<GitAuthDevicePage />} />
</Route>
</Route>
<Route path="gitauth/:provider" element={<GitAuthPage />} />

<Route path="workspaces" element={<WorkspacesPage />} />

Expand Down
20 changes: 17 additions & 3 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -799,11 +799,25 @@ export const getExperiments = async (): Promise<TypesGen.Experiment[]> => {
}
}

export const exchangeGitAuth = async (
export const getGitAuthProvider = async (
provider: string,
req: TypesGen.ExchangeGitAuthRequest,
): Promise<TypesGen.GitAuth> => {
const resp = await axios.get(`/api/v2/gitauth/${provider}`)
return resp.data
}

export const getGitAuthDevice = async (
provider: string,
): Promise<TypesGen.GitAuthDevice> => {
const resp = await axios.get(`/api/v2/gitauth/${provider}/device`)
return resp.data
}

export const exchangeGitAuthDevice = async (
provider: string,
req: TypesGen.GitAuthDeviceExchange,
): Promise<void> => {
const resp = await axios.post(`/gitauth/${provider}/exchange`, req)
const resp = await axios.post(`/api/v2/gitauth/${provider}/device`, req)
return resp.data
}

Expand Down
47 changes: 42 additions & 5 deletions site/src/api/typesGenerated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,11 +392,6 @@ export interface Entitlements {
readonly require_telemetry: boolean
}

// From codersdk/authorization.go
export interface ExchangeGitAuthRequest {
readonly device_code: string
}

// From codersdk/deployment.go
export type Experiments = Experiment[]

Expand All @@ -419,6 +414,24 @@ export interface GetUsersResponse {
readonly count: number
}

// From codersdk/gitauth.go
export interface GitAuth {
readonly authenticated: boolean
readonly device: boolean
readonly type: string
readonly user?: GitAuthUser
readonly app_installable: boolean
readonly installations: GitAuthAppInstallation[]
readonly app_install_url: string
}

// From codersdk/gitauth.go
export interface GitAuthAppInstallation {
readonly id: number
readonly account?: GitAuthUser
readonly configure_url: string
}

// From codersdk/deployment.go
export interface GitAuthConfig {
readonly id: string
Expand All @@ -427,13 +440,37 @@ export interface GitAuthConfig {
readonly auth_url: string
readonly token_url: string
readonly validate_url: string
readonly app_install_url: string
readonly app_installations_url: string
readonly regex: string
readonly no_refresh: boolean
readonly scopes: string[]
readonly device_flow: boolean
readonly device_auth_url: string
}

// From codersdk/gitauth.go
export interface GitAuthDevice {
readonly device_code: string
readonly user_code: string
readonly verification_uri: string
readonly expires_in: number
readonly interval: number
}

// From codersdk/gitauth.go
export interface GitAuthDeviceExchange {
readonly device_code: string
}

// From codersdk/gitauth.go
export interface GitAuthUser {
readonly login: string
readonly avatar_url: string
readonly profile_url: string
readonly name: string
}

// From codersdk/gitsshkey.go
export interface GitSSHKey {
readonly user_id: string
Expand Down
1 change: 1 addition & 0 deletions site/src/components/Dashboard/DashboardLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,6 @@ const useStyles = makeStyles({
siteContent: {
flex: 1,
paddingBottom: dashboardContentBottomPadding, // Add bottom space since we don't use a footer
display: "flex",
},
})
2 changes: 1 addition & 1 deletion site/src/components/SignInLayout/SignInLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FC, ReactNode } from "react"

export const useStyles = makeStyles((theme) => ({
root: {
height: "100vh",
flex: 1,
display: "flex",
justifyContent: "center",
alignItems: "center",
Expand Down
2 changes: 1 addition & 1 deletion site/src/components/Welcome/Welcome.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const useStyles = makeStyles((theme) => ({
margin: 0,
marginBottom: theme.spacing(2),
marginTop: theme.spacing(2),
lineHeight: 1,
lineHeight: 1.25,

"& strong": {
fontWeight: 600,
Expand Down
Loading