Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add support for capturing id token returned by Azure OIDC login#20991

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
rowansmithau wants to merge3 commits intomain
base:main
Choose a base branch
Loading
fromrowansmithau/feat/add-oidc-id-token-env-var
Open
Show file tree
Hide file tree
Changes fromall 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
1 change: 1 addition & 0 deletionscoderd/coderdtest/oidctest/helper.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -88,6 +88,7 @@ func (*LoginHelper) ExpireOauthToken(t *testing.T, db database.Store, user *code
OAuthExpiry: time.Now().Add(time.Hour * -1),
UserID: link.UserID,
LoginType: link.LoginType,
OAuthIDToken: link.OAuthIDToken,
Claims: database.UserLinkClaims{},
})
require.NoError(t, err, "expire user link")
Expand Down
1 change: 1 addition & 0 deletionscoderd/database/dbgen/dbgen.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1037,6 +1037,7 @@ func UserLink(t testing.TB, db database.Store, orig database.UserLink) database.
OAuthAccessTokenKeyID: takeFirst(orig.OAuthAccessTokenKeyID, sql.NullString{}),
OAuthRefreshToken: takeFirst(orig.OAuthRefreshToken, uuid.NewString()),
OAuthRefreshTokenKeyID: takeFirst(orig.OAuthRefreshTokenKeyID, sql.NullString{}),
OAuthIDToken: takeFirst(orig.OAuthIDToken),
OAuthExpiry: takeFirst(orig.OAuthExpiry, dbtime.Now().Add(time.Hour*24)),
Claims: orig.Claims,
})
Expand Down
3 changes: 2 additions & 1 deletioncoderd/database/dump.sql
View file
Open in desktop

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

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- Remove oauth_id_token column from user_links table
ALTER TABLE user_links DROP COLUMN oauth_id_token;
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
-- Add oauth_id_token column to user_links table to support ID token storage for OIDC providers like Azure
ALTER TABLE user_links ADD COLUMN oauth_id_token text DEFAULT ''::text NOT NULL;
3 changes: 2 additions & 1 deletioncoderd/database/models.go
View file
Open in desktop

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

26 changes: 19 additions & 7 deletionscoderd/database/queries.sql.go
View file
Open in desktop

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

8 changes: 5 additions & 3 deletionscoderd/database/queries/user_links.sql
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,10 +32,11 @@ INSERT INTO
oauth_refresh_token,
oauth_refresh_token_key_id,
oauth_expiry,
oauth_id_token,
claims
)
VALUES
( $1, $2, $3, $4, $5, $6, $7, $8, $9 ) RETURNING *;
( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10 ) RETURNING *;

-- name: UpdateUserLinkedID :one
UPDATE
Expand All@@ -54,9 +55,10 @@ SET
oauth_refresh_token = $3,
oauth_refresh_token_key_id = $4,
oauth_expiry = $5,
claims = $6
oauth_id_token = $6,
claims = $7
WHERE
user_id = $7 AND login_type = $8 RETURNING *;
user_id = $8 AND login_type = $9 RETURNING *;

-- name: OIDCClaimFields :many
-- OIDCClaimFields returns a list of distinct keys in the the merged_claims fields.
Expand Down
1 change: 1 addition & 0 deletionscoderd/httpmw/apikey.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -354,6 +354,7 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
OAuthAccessTokenKeyID: sql.NullString{}, // dbcrypt will update as required
OAuthRefreshToken: link.OAuthRefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // dbcrypt will update as required
OAuthIDToken: link.OAuthIDToken,
OAuthExpiry: link.OAuthExpiry,
// Refresh should keep the same debug context because we use
// the original claims for the group/role sync.
Expand Down
65 changes: 65 additions & 0 deletionscoderd/provisionerdserver/provisionerdserver.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -544,13 +544,18 @@ func (s *server) acquireProtoJob(ctx context.Context, job database.ProvisionerJo
}

var workspaceOwnerOIDCAccessToken string
var workspaceOwnerOIDCIdToken string
// The check `s.OIDCConfig != nil` is not as strict, since it can be an interface
// pointing to a typed nil.
if !reflect.ValueOf(s.OIDCConfig).IsNil() {
workspaceOwnerOIDCAccessToken, err = obtainOIDCAccessToken(ctx, s.Database, s.OIDCConfig, owner.ID)
if err != nil {
return nil, failJob(fmt.Sprintf("obtain OIDC access token: %s", err))
}
workspaceOwnerOIDCIdToken, err = obtainOIDCIdToken(ctx, s.Database, s.OIDCConfig, owner.ID)
if err != nil {
return nil, failJob(fmt.Sprintf("obtain OIDC ID token: %s", err))
}
}

var sessionToken string
Expand DownExpand Up@@ -724,6 +729,7 @@ func (s *server) acquireProtoJob(ctx context.Context, job database.ProvisionerJo
WorkspaceOwnerName: owner.Name,
WorkspaceOwnerGroups: ownerGroupNames,
WorkspaceOwnerOidcAccessToken: workspaceOwnerOIDCAccessToken,
WorkspaceOwnerOidcIdToken: workspaceOwnerOIDCIdToken,
WorkspaceId: workspace.ID.String(),
WorkspaceOwnerId: owner.ID.String(),
TemplateId: template.ID.String(),
Expand DownExpand Up@@ -3145,6 +3151,9 @@ func obtainOIDCAccessToken(ctx context.Context, db database.Store, oidcConfig pr
link.OAuthRefreshToken = token.RefreshToken
link.OAuthExpiry = token.Expiry

// Extract the ID token from the refreshed token if available
idToken, _ := token.Extra("id_token").(string)

link, err = db.UpdateUserLink(ctx, database.UpdateUserLinkParams{
UserID: userID,
LoginType: database.LoginTypeOIDC,
Expand All@@ -3153,6 +3162,7 @@ func obtainOIDCAccessToken(ctx context.Context, db database.Store, oidcConfig pr
OAuthRefreshToken: link.OAuthRefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // set by dbcrypt if required
OAuthExpiry: link.OAuthExpiry,
OAuthIDToken: idToken,
Claims: link.Claims,
})
if err != nil {
Expand All@@ -3163,6 +3173,61 @@ func obtainOIDCAccessToken(ctx context.Context, db database.Store, oidcConfig pr
return link.OAuthAccessToken, nil
}

// obtainOIDCIdToken returns a valid OpenID Connect ID token
// for the user if it's able to obtain one, otherwise it returns an empty string.
// The ID token is used by some providers like Azure for authentication.
func obtainOIDCIdToken(ctx context.Context, db database.Store, oidcConfig promoauth.OAuth2Config, userID uuid.UUID) (string, error) {
link, err := db.GetUserLinkByUserIDLoginType(ctx, database.GetUserLinkByUserIDLoginTypeParams{
UserID: userID,
LoginType: database.LoginTypeOIDC,
})
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
if err != nil {
return "", xerrors.Errorf("get owner oidc link: %w", err)
}

// If the token is expired and we have a refresh token, refresh it
if link.OAuthExpiry.Before(dbtime.Now()) && !link.OAuthExpiry.IsZero() && link.OAuthRefreshToken != "" {
token, err := oidcConfig.TokenSource(ctx, &oauth2.Token{
AccessToken: link.OAuthAccessToken,
RefreshToken: link.OAuthRefreshToken,
Expiry: link.OAuthExpiry,
}).Token()
if err != nil {
// If OIDC fails to refresh, we return an empty string and don't fail.
// There isn't a way to hard-opt in to OIDC from a template, so we don't
// want to fail builds if users haven't authenticated for a while or something.
return "", nil
}

// Extract the ID token from the refreshed token
idToken, _ := token.Extra("id_token").(string)
link.OAuthAccessToken = token.AccessToken
link.OAuthRefreshToken = token.RefreshToken
link.OAuthExpiry = token.Expiry
link.OAuthIDToken = idToken

link, err = db.UpdateUserLink(ctx, database.UpdateUserLinkParams{
UserID: userID,
LoginType: database.LoginTypeOIDC,
OAuthAccessToken: link.OAuthAccessToken,
OAuthAccessTokenKeyID: sql.NullString{}, // set by dbcrypt if required
OAuthRefreshToken: link.OAuthRefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // set by dbcrypt if required
OAuthExpiry: link.OAuthExpiry,
OAuthIDToken: link.OAuthIDToken,
Claims: link.Claims,
})
if err != nil {
return "", xerrors.Errorf("update user link: %w", err)
}
}

return link.OAuthIDToken, nil
}

func convertLogLevel(logLevel sdkproto.LogLevel) (database.LogLevel, error) {
switch logLevel {
case sdkproto.LogLevel_TRACE:
Expand Down
8 changes: 8 additions & 0 deletionscoderd/userauth.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1450,6 +1450,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
UserInfoClaims: supplementaryClaims,
MergedClaims: mergedClaims,
},
RawOIDCIdToken: rawIDToken,
}).SetInitAuditRequest(func(params *audit.RequestParams) (*audit.Request[database.User], func()) {
return audit.InitRequest[database.User](rw, params)
})
Expand DownExpand Up@@ -1603,6 +1604,11 @@ type oauthLoginParams struct {
// It is used to save the user's claims on login.
UserClaims database.UserLinkClaims

// RawOIDCIdToken is the raw ID token string from the OIDC provider.
// This is stored separately from the access token for providers like Azure
// that require the ID token for authentication.
RawOIDCIdToken string

commitLock sync.Mutex
initAuditRequest func(params *audit.RequestParams) *audit.Request[database.User]
commits []func()
Expand DownExpand Up@@ -1808,6 +1814,7 @@ func (api *API) oauthLogin(r *http.Request, params *oauthLoginParams) ([]*http.C
OAuthRefreshToken: params.State.Token.RefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // set by dbcrypt if required
OAuthExpiry: params.State.Token.Expiry,
OAuthIDToken: params.RawOIDCIdToken,
Claims: params.UserClaims,
})
if err != nil {
Expand All@@ -1825,6 +1832,7 @@ func (api *API) oauthLogin(r *http.Request, params *oauthLoginParams) ([]*http.C
OAuthRefreshToken: params.State.Token.RefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // set by dbcrypt if required
OAuthExpiry: params.State.Token.Expiry,
OAuthIDToken: params.RawOIDCIdToken,
Claims: params.UserClaims,
})
if err != nil {
Expand Down
1 change: 1 addition & 0 deletionscodersdk/toolsdk/toolsdk.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -649,6 +649,7 @@ This data source provides the following fields:
- email: The email of the workspace owner.
- session_token: A token that can be used to authenticate the workspace owner. It is regenerated every time the workspace is started.
- oidc_access_token: A valid OpenID Connect access token of the workspace owner. This is only available if the workspace owner authenticated with OpenID Connect. If a valid token cannot be obtained, this value will be an empty string.
- oidc_id_token: A valid OpenID Connect ID token of the workspace owner. This is only available if the workspace owner authenticated with OpenID Connect. If a valid token cannot be obtained, this value will be an empty string. This is useful for providers like Azure that require the ID token for authentication.

Parameters are defined in the template version. They are rendered in the UI on the workspace creation page:

Expand Down
2 changes: 2 additions & 0 deletionsenterprise/dbcrypt/cliutil.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -41,6 +41,7 @@ func Rotate(ctx context.Context, log slog.Logger, sqlDB *sql.DB, ciphers []Ciphe
OAuthAccessTokenKeyID: sql.NullString{}, // dbcrypt will update as required
OAuthRefreshToken: userLink.OAuthRefreshToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // dbcrypt will update as required
OAuthIDToken: userLink.OAuthIDToken,
OAuthExpiry: userLink.OAuthExpiry,
UserID: uid,
LoginType: userLink.LoginType,
Expand DownExpand Up@@ -130,6 +131,7 @@ func Decrypt(ctx context.Context, log slog.Logger, sqlDB *sql.DB, ciphers []Ciph
OAuthAccessToken: userLink.OAuthAccessToken,
OAuthAccessTokenKeyID: sql.NullString{}, // we explicitly want to clear the key id
OAuthRefreshToken: userLink.OAuthRefreshToken,
OAuthIDToken: userLink.OAuthIDToken,
OAuthRefreshTokenKeyID: sql.NullString{}, // we explicitly want to clear the key id
OAuthExpiry: userLink.OAuthExpiry,
UserID: uid,
Expand Down
1 change: 1 addition & 0 deletionsprovisioner/terraform/provision.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -251,6 +251,7 @@ func provisionEnv(
"CODER_WORKSPACE_OWNER_EMAIL="+metadata.GetWorkspaceOwnerEmail(),
"CODER_WORKSPACE_OWNER_NAME="+metadata.GetWorkspaceOwnerName(),
"CODER_WORKSPACE_OWNER_OIDC_ACCESS_TOKEN="+metadata.GetWorkspaceOwnerOidcAccessToken(),
"CODER_WORKSPACE_OWNER_OIDC_ID_TOKEN="+metadata.GetWorkspaceOwnerOidcIdToken(),
"CODER_WORKSPACE_OWNER_GROUPS="+string(ownerGroups),
"CODER_WORKSPACE_OWNER_SSH_PUBLIC_KEY="+metadata.GetWorkspaceOwnerSshPublicKey(),
"CODER_WORKSPACE_OWNER_SSH_PRIVATE_KEY="+metadata.GetWorkspaceOwnerSshPrivateKey(),
Expand Down
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp