Skip to content

feat: allow external auth providers to expose extra metadata #10157

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 1 commit into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
48 changes: 33 additions & 15 deletions cli/externalauth.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package cli

import (
"encoding/json"
"os/signal"

"golang.org/x/xerrors"

"github.com/tidwall/gjson"

"github.com/coder/coder/v2/cli/clibase"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk/agentsdk"
Expand All @@ -25,7 +28,7 @@ func (r *RootCmd) externalAuth() *clibase.Cmd {
}

func (r *RootCmd) externalAuthAccessToken() *clibase.Cmd {
var silent bool
var extra string
return &clibase.Cmd{
Use: "access-token <provider>",
Short: "Print auth for an external provider",
Expand All @@ -45,12 +48,16 @@ else
fi
`,
},
example{
Description: "Obtain an extra property of an access token for additional metadata.",
Command: "coder external-auth access-token slack --extra \"authed_user.id\"",
},
),
Options: clibase.OptionSet{{
Name: "Silent",
Flag: "s",
Description: "Do not print the URL or access token.",
Value: clibase.BoolOf(&silent),
Name: "Extra",
Flag: "extra",
Description: "Extract a field from the \"extra\" properties of the OAuth token.",
Value: clibase.StringOf(&extra),
}},

Handler: func(inv *clibase.Invocation) error {
Expand All @@ -64,26 +71,37 @@ fi
return xerrors.Errorf("create agent client: %w", err)
}

token, err := client.ExternalAuth(ctx, agentsdk.ExternalAuthRequest{
extAuth, err := client.ExternalAuth(ctx, agentsdk.ExternalAuthRequest{
ID: inv.Args[0],
})
if err != nil {
return xerrors.Errorf("get external auth token: %w", err)
}

if !silent {
if token.URL != "" {
_, err = inv.Stdout.Write([]byte(token.URL))
} else {
_, err = inv.Stdout.Write([]byte(token.AccessToken))
if extAuth.URL != "" {
_, err = inv.Stdout.Write([]byte(extAuth.URL))
if err != nil {
return err
}
return cliui.Canceled
}
if extra != "" {
if extAuth.TokenExtra == nil {
return xerrors.Errorf("no extra properties found for token")
}
data, err := json.Marshal(extAuth.TokenExtra)
if err != nil {
return xerrors.Errorf("marshal extra properties: %w", err)
}
result := gjson.GetBytes(data, extra)
_, err = inv.Stdout.Write([]byte(result.String()))
if err != nil {
return err
}
return nil
}

if token.URL != "" {
return cliui.Canceled
_, err = inv.Stdout.Write([]byte(extAuth.AccessToken))
if err != nil {
return err
}
return nil
},
Expand Down
18 changes: 18 additions & 0 deletions cli/externalauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,22 @@ func TestExternalAuth(t *testing.T) {
clitest.Start(t, inv)
pty.ExpectMatch("bananas")
})
t.Run("SuccessWithExtra", func(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httpapi.Write(context.Background(), w, http.StatusOK, agentsdk.ExternalAuthResponse{
AccessToken: "bananas",
TokenExtra: map[string]interface{}{
"hey": "there",
},
})
}))
t.Cleanup(srv.Close)
url := srv.URL
inv, _ := clitest.New(t, "--agent-url", url, "external-auth", "access-token", "github", "--extra", "hey")
pty := ptytest.New(t)
inv.Stdout = pty.Output()
clitest.Start(t, inv)
pty.ExpectMatch("there")
})
}
8 changes: 6 additions & 2 deletions cli/testdata/coder_external-auth_access-token_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ USAGE:
echo "Please authenticate with GitHub:"
echo $OUTPUT
fi

- Obtain an extra property of an access token for additional metadata.:

$ coder external-auth access-token slack --extra "authed_user.id"

OPTIONS:
--s bool
Do not print the URL or access token.
--extra string
Extract a field from the "extra" properties of the OAuth token.

———
Run `coder --help` for a list of global options.
4 changes: 4 additions & 0 deletions coderd/apidoc/docs.go

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

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

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

30 changes: 26 additions & 4 deletions coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (

"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/sqlc-dev/pqtype"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/mod/semver"
Expand Down Expand Up @@ -2306,7 +2307,15 @@ func (api *API) workspaceAgentsExternalAuth(rw http.ResponseWriter, r *http.Requ
if !valid {
continue
}
httpapi.Write(ctx, rw, http.StatusOK, createExternalAuthResponse(externalAuthConfig.Type, externalAuthLink.OAuthAccessToken))
resp, err := createExternalAuthResponse(externalAuthConfig.Type, externalAuthLink.OAuthAccessToken, externalAuthLink.OAuthExtra)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to create external auth response.",
Detail: err.Error(),
})
return
}
httpapi.Write(ctx, rw, http.StatusOK, resp)
return
}
}
Expand Down Expand Up @@ -2354,13 +2363,21 @@ func (api *API) workspaceAgentsExternalAuth(rw http.ResponseWriter, r *http.Requ
})
return
}
httpapi.Write(ctx, rw, http.StatusOK, createExternalAuthResponse(externalAuthConfig.Type, externalAuthLink.OAuthAccessToken))
resp, err := createExternalAuthResponse(externalAuthConfig.Type, externalAuthLink.OAuthAccessToken, externalAuthLink.OAuthExtra)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to create external auth response.",
Detail: err.Error(),
})
return
}
httpapi.Write(ctx, rw, http.StatusOK, resp)
}

// createExternalAuthResponse creates an ExternalAuthResponse based on the
// provider type. This is to support legacy `/workspaceagents/me/gitauth`
// which uses `Username` and `Password`.
func createExternalAuthResponse(typ, token string) agentsdk.ExternalAuthResponse {
func createExternalAuthResponse(typ, token string, extra pqtype.NullRawMessage) (agentsdk.ExternalAuthResponse, error) {
var resp agentsdk.ExternalAuthResponse
switch typ {
case string(codersdk.EnhancedExternalAuthProviderGitLab):
Expand All @@ -2382,7 +2399,12 @@ func createExternalAuthResponse(typ, token string) agentsdk.ExternalAuthResponse
}
resp.AccessToken = token
resp.Type = typ
return resp

var err error
if extra.Valid {
err = json.Unmarshal(extra.RawMessage, &resp.TokenExtra)
}
return resp, err
}

// wsNetConn wraps net.Conn created by websocket.NetConn(). Cancel func
Expand Down
7 changes: 4 additions & 3 deletions codersdk/agentsdk/agentsdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -711,9 +711,10 @@ func (c *Client) GetServiceBanner(ctx context.Context) (codersdk.ServiceBannerCo
}

type ExternalAuthResponse struct {
AccessToken string `json:"access_token"`
URL string `json:"url"`
Type string `json:"type"`
AccessToken string `json:"access_token"`
TokenExtra map[string]interface{} `json:"token_extra"`
URL string `json:"url"`
Type string `json:"type"`

// Deprecated: Only supported on `/workspaceagents/me/gitauth`
// for backwards compatibility.
Expand Down
2 changes: 2 additions & 0 deletions docs/api/agents.md

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

2 changes: 2 additions & 0 deletions docs/api/schemas.md

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

14 changes: 9 additions & 5 deletions docs/cli/external-auth_access-token.md

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

3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,9 @@ require (
github.com/tcnksm/go-httpstat v0.2.0 // indirect
github.com/tdewolff/parse/v2 v2.6.6 // indirect
github.com/tdewolff/test v1.0.9 // indirect
github.com/tidwall/gjson v1.17.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tinylib/msgp v1.1.8 // indirect
github.com/u-root/uio v0.0.0-20230305220412-3e8cd9d6bf63 // indirect
github.com/ulikunitz/xz v0.5.11 // indirect
Expand Down
Loading