Skip to content
Closed
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
Next Next commit
feat(coderd): add OIDC ID token support with CODER_WORKSPACE_OWNER_OI…
…DC_ID_TOKEN env var

- Add oauth_id_token column to user_links table (migration 402)
- Capture and store ID token during OIDC authentication
- Implement token refresh with ID token preservation
- Add obtainOIDCIdToken() function for token retrieval
- Pass ID token to provisioner via proto metadata
- Expose as CODER_WORKSPACE_OWNER_OIDC_ID_TOKEN environment variable
- Fix OAuthIdToken -> OAuthIDToken field naming (Go conventions)
- Add OAuthIDToken to all UpdateUserLinkParams/InsertUserLinkParams structs
- Update TypeScript and Go proto bindings
- Regenerate database queries with correct column ordering

This enables Azure OIDC authentication which requires the ID token
for subsequent API calls.
  • Loading branch information
rowansmithau committed Dec 1, 2025
commit fa14946dfed614433fb413ce2a291877f958a540
1 change: 1 addition & 0 deletions coderd/coderdtest/oidctest/helper.go
Original file line number Diff line number Diff 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 deletions coderd/database/dbgen/dbgen.go
Original file line number Diff line number Diff 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 deletion coderd/database/dump.sql

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

2 changes: 2 additions & 0 deletions coderd/database/migrations/000402_add_oidc_id_token.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Remove oauth_id_token column from user_links table
ALTER TABLE user_links DROP COLUMN oauth_id_token;
2 changes: 2 additions & 0 deletions coderd/database/migrations/000402_add_oidc_id_token.up.sql
Original file line number Diff line number Diff 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 deletion coderd/database/models.go

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

26 changes: 19 additions & 7 deletions coderd/database/queries.sql.go

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

8 changes: 5 additions & 3 deletions coderd/database/queries/user_links.sql
Original file line number Diff line number Diff 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 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff 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 deletions coderd/provisionerdserver/provisionerdserver.go
Original file line number Diff line number Diff 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 Down Expand 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 Down Expand 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 deletions coderd/userauth.go
Original file line number Diff line number Diff 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 Down Expand 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 Down Expand 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 deletions codersdk/toolsdk/toolsdk.go
Original file line number Diff line number Diff 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 deletions enterprise/dbcrypt/cliutil.go
Original file line number Diff line number Diff 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 Down Expand 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 deletions provisioner/terraform/provision.go
Original file line number Diff line number Diff 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