2022-04-23 17:58:57 -05:00
package coderd
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
2022-10-17 14:14:49 -05:00
"net/mail"
2023-04-05 09:07:43 +01:00
"sort"
2022-08-17 18:00:53 -05:00
"strconv"
2022-07-31 23:05:35 -05:00
"strings"
2023-06-30 08:38:48 -04:00
"sync"
2024-10-31 17:55:42 -05:00
"sync/atomic"
2023-06-30 08:38:48 -04:00
"time"
2022-04-23 17:58:57 -05:00
2022-07-31 23:05:35 -05:00
"github.com/coreos/go-oidc/v3/oidc"
2024-10-25 17:14:35 +01:00
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
2022-04-23 17:58:57 -05:00
"github.com/google/go-github/v43/github"
"github.com/google/uuid"
"golang.org/x/oauth2"
2022-08-17 18:00:53 -05:00
"golang.org/x/xerrors"
2022-04-23 17:58:57 -05:00
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/audit"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/cryptokeys"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
2023-09-01 19:50:12 +03:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2024-08-02 11:49:36 -05:00
"github.com/coder/coder/v2/coderd/externalauth"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/idpsync"
"github.com/coder/coder/v2/coderd/jwtutils"
2024-10-04 11:53:25 +01:00
"github.com/coder/coder/v2/coderd/notifications"
2024-01-10 09:13:30 -06:00
"github.com/coder/coder/v2/coderd/promoauth"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/rbac"
2024-07-08 15:38:50 +02:00
"github.com/coder/coder/v2/coderd/render"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/telemetry"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/userpassword"
2026-01-09 15:40:26 -07:00
"github.com/coder/coder/v2/coderd/util/namesgenerator"
2026-01-08 15:24:11 +04:00
"github.com/coder/coder/v2/coderd/util/ptr"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/cryptorand"
2026-03-16 11:56:59 -04:00
"github.com/coder/coder/v2/site"
2022-04-23 17:58:57 -05:00
)
2025-02-24 13:38:20 -06:00
type MergedClaimsSource string
var (
MergedClaimsSourceNone MergedClaimsSource = "none"
MergedClaimsSourceUserInfo MergedClaimsSource = "user_info"
MergedClaimsSourceAccessToken MergedClaimsSource = "access_token"
)
2023-06-22 20:09:33 +02:00
const (
2023-06-30 08:38:48 -04:00
userAuthLoggerName = "userauth"
OAuthConvertCookieValue = "coder_oauth_convert_jwt"
mergeStateStringPrefix = "convert-"
2023-06-22 20:09:33 +02:00
)
2023-06-30 08:38:48 -04:00
type OAuthConvertStateClaims struct {
2024-10-25 17:14:35 +01:00
jwtutils . RegisteredClaims
2023-06-30 08:38:48 -04:00
UserID uuid . UUID `json:"user_id"`
State string `json:"state"`
FromLoginType codersdk . LoginType `json:"from_login_type"`
ToLoginType codersdk . LoginType `json:"to_login_type"`
}
2024-10-25 17:14:35 +01:00
func ( o * OAuthConvertStateClaims ) Validate ( e jwt . Expected ) error {
return o . RegisteredClaims . Validate ( e )
}
2023-06-30 08:38:48 -04:00
// postConvertLoginType replies with an oauth state token capable of converting
// the user to an oauth user.
//
// @Summary Convert user from password to oauth authentication
// @ID convert-user-from-password-to-oauth-authentication
// @Security CoderSessionToken
// @Accept json
// @Produce json
// @Tags Authorization
// @Param request body codersdk.ConvertLoginRequest true "Convert request"
// @Param user path string true "User ID, name, or me"
// @Success 201 {object} codersdk.OAuthConversionResponse
// @Router /users/{user}/convert-login [post]
func ( api * API ) postConvertLoginType ( rw http . ResponseWriter , r * http . Request ) {
var (
user = httpmw . UserParam ( r )
ctx = r . Context ()
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . AuditOAuthConvertState ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionCreate ,
})
)
aReq . Old = database . AuditOAuthConvertState {}
defer commitAudit ()
var req codersdk . ConvertLoginRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
switch req . ToType {
case codersdk . LoginTypeGithub , codersdk . LoginTypeOIDC :
// Allowed!
case codersdk . LoginTypeNone , codersdk . LoginTypePassword , codersdk . LoginTypeToken :
// These login types are not allowed to be converted to at this time.
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Cannot convert to login type %q." , req . ToType ),
})
return
default :
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : fmt . Sprintf ( "Unknown login type %q." , req . ToType ),
})
return
}
// This handles the email/pass checking.
user , _ , ok := api . loginRequest ( ctx , rw , codersdk . LoginWithPasswordRequest {
Email : user . Email ,
Password : req . Password ,
})
if ! ok {
return
}
// Only support converting from password auth.
if user . LoginType != database . LoginTypePassword {
// This is checked in loginRequest, but checked again here in case that shared
// function changes its checks. Just some defensive programming.
// This login type is **required** to be password based to prevent
// users from converting other login types to OIDC.
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "User account must have password based authentication." ,
})
return
}
stateString , err := cryptorand . String ( 32 )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error generating state string." ,
Detail : err . Error (),
})
return
}
// The prefix is used to identify this state string as a conversion state
// without needing to hit the database. The random string is the CSRF protection.
stateString = fmt . Sprintf ( "%s%s" , mergeStateStringPrefix , stateString )
// This JWT is the signed payload to authorize the convert to oauth request.
// When the user does the oauth flow, this jwt will be sent back to coderd.
// The included information in this payload links it to a state string, so
// this request is tied 1:1 with an oauth state.
// This JWT also includes information to tie it 1:1 with a coder deployment
// and user account. This is mainly to inform the user if they are accidentally
// switching between coder deployments if the OIDC is misconfigured.
// Eg: Developers with more than 1 deployment.
now := time . Now ()
claims := & OAuthConvertStateClaims {
2024-10-25 17:14:35 +01:00
RegisteredClaims : jwtutils . RegisteredClaims {
2023-06-30 08:38:48 -04:00
Issuer : api . DeploymentID ,
Subject : stateString ,
Audience : [] string { user . ID . String ()},
2024-10-25 17:14:35 +01:00
Expiry : jwt . NewNumericDate ( now . Add ( time . Minute * 5 )),
2023-06-30 08:38:48 -04:00
NotBefore : jwt . NewNumericDate ( now . Add ( time . Second * - 1 )),
IssuedAt : jwt . NewNumericDate ( now ),
ID : uuid . NewString (),
},
UserID : user . ID ,
State : stateString ,
FromLoginType : codersdk . LoginType ( user . LoginType ),
ToLoginType : req . ToType ,
}
2024-10-25 17:14:35 +01:00
token , err := jwtutils . Sign ( ctx , api . OIDCConvertKeyCache , claims )
2023-06-30 08:38:48 -04:00
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error signing state jwt." ,
Detail : err . Error (),
})
return
}
aReq . New = database . AuditOAuthConvertState {
2024-10-25 17:14:35 +01:00
CreatedAt : claims . IssuedAt . Time (),
ExpiresAt : claims . Expiry . Time (),
2023-06-30 08:38:48 -04:00
FromLoginType : database . LoginType ( claims . FromLoginType ),
ToLoginType : database . LoginType ( claims . ToLoginType ),
UserID : claims . UserID ,
}
http . SetCookie ( rw , & http . Cookie {
Name : OAuthConvertCookieValue ,
Path : "/" ,
2024-10-25 17:14:35 +01:00
Value : token ,
Expires : claims . Expiry . Time (),
2025-04-08 14:15:14 -05:00
Secure : api . DeploymentValues . HTTPCookies . Secure . Value (),
2023-06-30 08:38:48 -04:00
HttpOnly : true ,
2023-08-16 12:50:44 -05:00
// Must be SameSite to work on the redirected auth flow from the
// oauth provider.
SameSite : http . SameSiteLaxMode ,
2023-06-30 08:38:48 -04:00
})
httpapi . Write ( ctx , rw , http . StatusCreated , codersdk . OAuthConversionResponse {
StateString : stateString ,
2024-10-25 17:14:35 +01:00
ExpiresAt : claims . Expiry . Time (),
2023-06-30 08:38:48 -04:00
ToType : claims . ToLoginType ,
UserID : claims . UserID ,
})
}
2024-10-04 11:53:25 +01:00
// Requests a one-time passcode for a user.
//
// @Summary Request one-time passcode
// @ID request-one-time-passcode
// @Accept json
// @Tags Authorization
// @Param request body codersdk.RequestOneTimePasscodeRequest true "One-time passcode request"
// @Success 204
// @Router /users/otp/request [post]
func ( api * API ) postRequestOneTimePasscode ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
auditor = api . Auditor . Load ()
logger = api . Logger . Named ( userAuthLoggerName )
aReq , commitAudit = audit . InitRequest [ database . User ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
2024-10-22 13:47:30 +01:00
Action : database . AuditActionRequestPasswordReset ,
2024-10-04 11:53:25 +01:00
})
)
defer commitAudit ()
if api . DeploymentValues . DisablePasswordAuth {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "Password authentication is disabled." ,
})
return
}
var req codersdk . RequestOneTimePasscodeRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
defer func () {
// We always send the same response. If we give a more detailed response
// it would open us up to an enumeration attack.
rw . WriteHeader ( http . StatusNoContent )
}()
//nolint:gocritic // In order to request a one-time passcode, we need to get the user first - and can only do that in the system auth context.
user , err := api . Database . GetUserByEmailOrUsername ( dbauthz . AsSystemRestricted ( ctx ), database . GetUserByEmailOrUsernameParams {
Email : req . Email ,
})
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
logger . Error ( ctx , "unable to get user by email" , slog . Error ( err ))
return
}
// We continue if err == sql.ErrNoRows to help prevent a timing-based attack.
aReq . Old = user
2024-10-22 13:47:30 +01:00
aReq . UserID = user . ID
2024-10-04 11:53:25 +01:00
passcode := uuid . New ()
passcodeExpiresAt := dbtime . Now (). Add ( api . OneTimePasscodeValidityPeriod )
hashedPasscode , err := userpassword . Hash ( passcode . String ())
if err != nil {
logger . Error ( ctx , "unable to hash passcode" , slog . Error ( err ))
return
}
//nolint:gocritic // We need the system auth context to be able to save the one-time passcode.
err = api . Database . UpdateUserHashedOneTimePasscode ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserHashedOneTimePasscodeParams {
ID : user . ID ,
HashedOneTimePasscode : [] byte ( hashedPasscode ),
OneTimePasscodeExpiresAt : sql . NullTime { Time : passcodeExpiresAt , Valid : true },
})
if err != nil {
logger . Error ( ctx , "unable to set user hashed one-time passcode" , slog . Error ( err ))
return
}
auditUser := user
auditUser . HashedOneTimePasscode = [] byte ( hashedPasscode )
auditUser . OneTimePasscodeExpiresAt = sql . NullTime { Time : passcodeExpiresAt , Valid : true }
aReq . New = auditUser
if user . ID != uuid . Nil {
// Send the one-time passcode to the user.
err = api . notifyUserRequestedOneTimePasscode ( ctx , user , passcode . String ())
if err != nil {
logger . Error ( ctx , "unable to notify user about one-time passcode request" , slog . Error ( err ))
}
2024-10-29 12:19:56 +00:00
} else {
logger . Warn ( ctx , "password reset requested for account that does not exist" , slog . F ( "email" , req . Email ))
2024-10-04 11:53:25 +01:00
}
}
func ( api * API ) notifyUserRequestedOneTimePasscode ( ctx context . Context , user database . User , passcode string ) error {
_ , err := api . NotificationsEnqueuer . Enqueue (
2024-10-31 17:01:51 +00:00
//nolint:gocritic // We need the notifier auth context to be able to send the user their one-time passcode.
dbauthz . AsNotifier ( ctx ),
2024-10-04 11:53:25 +01:00
user . ID ,
notifications . TemplateUserRequestedOneTimePasscode ,
map [ string ] string { "one_time_passcode" : passcode },
"change-password-with-one-time-passcode" ,
user . ID ,
)
if err != nil {
return xerrors . Errorf ( "enqueue notification: %w" , err )
}
return nil
}
// Change a users password with a one-time passcode.
//
// @Summary Change password with a one-time passcode
// @ID change-password-with-a-one-time-passcode
// @Accept json
// @Tags Authorization
// @Param request body codersdk.ChangePasswordWithOneTimePasscodeRequest true "Change password request"
// @Success 204
// @Router /users/otp/change-password [post]
func ( api * API ) postChangePasswordWithOneTimePasscode ( rw http . ResponseWriter , r * http . Request ) {
var (
err error
ctx = r . Context ()
auditor = api . Auditor . Load ()
logger = api . Logger . Named ( userAuthLoggerName )
aReq , commitAudit = audit . InitRequest [ database . User ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
})
)
defer commitAudit ()
if api . DeploymentValues . DisablePasswordAuth {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "Password authentication is disabled." ,
})
return
}
var req codersdk . ChangePasswordWithOneTimePasscodeRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
if err := userpassword . Validate ( req . Password ); err != nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Invalid password." ,
Validations : [] codersdk . ValidationError {
{
Field : "password" ,
Detail : err . Error (),
},
},
})
return
}
err = api . Database . InTx ( func ( tx database . Store ) error {
//nolint:gocritic // In order to change a user's password, we need to get the user first - and can only do that in the system auth context.
user , err := tx . GetUserByEmailOrUsername ( dbauthz . AsSystemRestricted ( ctx ), database . GetUserByEmailOrUsernameParams {
Email : req . Email ,
})
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
logger . Error ( ctx , "unable to fetch user by email" , slog . F ( "email" , req . Email ), slog . Error ( err ))
return xerrors . Errorf ( "get user by email: %w" , err )
}
// We continue if err == sql.ErrNoRows to help prevent a timing-based attack.
aReq . Old = user
2024-10-22 13:47:30 +01:00
aReq . UserID = user . ID
2024-10-04 11:53:25 +01:00
equal , err := userpassword . Compare ( string ( user . HashedOneTimePasscode ), req . OneTimePasscode )
if err != nil {
logger . Error ( ctx , "unable to compare one-time passcode" , slog . Error ( err ))
return xerrors . Errorf ( "compare one-time passcode: %w" , err )
}
now := dbtime . Now ()
if ! equal || now . After ( user . OneTimePasscodeExpiresAt . Time ) {
2024-10-29 12:19:56 +00:00
logger . Warn ( ctx , "password reset attempted with invalid or expired one-time passcode" , slog . F ( "email" , req . Email ))
2024-10-04 11:53:25 +01:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Incorrect email or one-time passcode." ,
})
return nil
}
equal , err = userpassword . Compare ( string ( user . HashedPassword ), req . Password )
if err != nil {
logger . Error ( ctx , "unable to compare password" , slog . Error ( err ))
return xerrors . Errorf ( "compare password: %w" , err )
}
if equal {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "New password cannot match old password." ,
})
return nil
}
newHashedPassword , err := userpassword . Hash ( req . Password )
if err != nil {
logger . Error ( ctx , "unable to hash user's password" , slog . Error ( err ))
return xerrors . Errorf ( "hash user password: %w" , err )
}
//nolint:gocritic // We need the system auth context to be able to update the user's password.
err = tx . UpdateUserHashedPassword ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserHashedPasswordParams {
ID : user . ID ,
HashedPassword : [] byte ( newHashedPassword ),
})
if err != nil {
logger . Error ( ctx , "unable to delete user's hashed password" , slog . Error ( err ))
return xerrors . Errorf ( "update user hashed password: %w" , err )
}
//nolint:gocritic // We need the system auth context to be able to delete all API keys for the user.
err = tx . DeleteAPIKeysByUserID ( dbauthz . AsSystemRestricted ( ctx ), user . ID )
if err != nil {
logger . Error ( ctx , "unable to delete user's api keys" , slog . Error ( err ))
return xerrors . Errorf ( "delete api keys for user: %w" , err )
}
auditUser := user
auditUser . HashedPassword = [] byte ( newHashedPassword )
auditUser . OneTimePasscodeExpiresAt = sql . NullTime {}
auditUser . HashedOneTimePasscode = nil
aReq . New = auditUser
rw . WriteHeader ( http . StatusNoContent )
return nil
}, nil )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error." ,
Detail : err . Error (),
})
return
}
}
2024-11-05 17:22:32 +01:00
// ValidateUserPassword validates the complexity of a user password and that it is secured enough.
//
// @Summary Validate user password
// @ID validate-user-password
// @Security CoderSessionToken
// @Produce json
// @Accept json
// @Tags Authorization
// @Param request body codersdk.ValidateUserPasswordRequest true "Validate user password request"
// @Success 200 {object} codersdk.ValidateUserPasswordResponse
// @Router /users/validate-password [post]
func ( * API ) validateUserPassword ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
valid = true
details = ""
)
var req codersdk . ValidateUserPasswordRequest
if ! httpapi . Read ( ctx , rw , r , & req ) {
return
}
err := userpassword . Validate ( req . Password )
if err != nil {
valid = false
details = err . Error ()
}
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . ValidateUserPasswordResponse {
Valid : valid ,
Details : details ,
})
}
2023-02-06 15:12:50 -05:00
// Authenticates the user with an email and password.
//
// @Summary Log in user
// @ID log-in-user
// @Accept json
// @Produce json
// @Tags Authorization
// @Param request body codersdk.LoginWithPasswordRequest true "Login request"
// @Success 201 {object} codersdk.LoginWithPasswordResponse
// @Router /users/login [post]
func ( api * API ) postLogin ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
auditor = api . Auditor . Load ()
2023-06-30 08:38:48 -04:00
logger = api . Logger . Named ( userAuthLoggerName )
2023-02-06 15:12:50 -05:00
aReq , commitAudit = audit . InitRequest [ database . APIKey ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionLogin ,
})
)
aReq . Old = database . APIKey {}
defer commitAudit ()
var loginWithPassword codersdk . LoginWithPasswordRequest
if ! httpapi . Read ( ctx , rw , r , & loginWithPassword ) {
return
}
2024-06-21 06:30:02 -10:00
user , actor , ok := api . loginRequest ( ctx , rw , loginWithPassword )
2023-06-30 08:38:48 -04:00
// 'user.ID' will be empty, or will be an actual value. Either is correct
// here.
2023-02-06 15:12:50 -05:00
aReq . UserID = user . ID
2023-06-30 08:38:48 -04:00
if ! ok {
// user failed to login
2023-02-06 15:12:50 -05:00
return
}
2023-02-14 08:27:06 -06:00
//nolint:gocritic // Creating the API key as the user instead of as system.
2024-06-21 06:30:02 -10:00
cookie , key , err := api . createAPIKey ( dbauthz . As ( ctx , actor ), apikey . CreateParams {
2024-01-22 11:42:55 -09:00
UserID : user . ID ,
LoginType : database . LoginTypePassword ,
RemoteAddr : r . RemoteAddr ,
2024-04-10 10:34:49 -05:00
DefaultLifetime : api . DeploymentValues . Sessions . DefaultDuration . Value (),
2023-02-06 15:12:50 -05:00
})
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "unable to create API key" , slog . Error ( err ))
2023-02-06 15:12:50 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to create API key." ,
Detail : err . Error (),
})
return
}
aReq . New = * key
http . SetCookie ( rw , cookie )
httpapi . Write ( ctx , rw , http . StatusCreated , codersdk . LoginWithPasswordResponse {
SessionToken : cookie . Value ,
})
}
2023-06-30 08:38:48 -04:00
// loginRequest will process a LoginWithPasswordRequest and return the user if
// the credentials are correct. If 'false' is returned, the authentication failed
// and the appropriate error will be written to the ResponseWriter.
//
// The user struct is always returned, even if authentication failed. This is
// to support knowing what user attempted to login.
2024-06-21 06:30:02 -10:00
func ( api * API ) loginRequest ( ctx context . Context , rw http . ResponseWriter , req codersdk . LoginWithPasswordRequest ) ( database . User , rbac . Subject , bool ) {
2023-06-30 08:38:48 -04:00
logger := api . Logger . Named ( userAuthLoggerName )
//nolint:gocritic // In order to login, we need to get the user first!
user , err := api . Database . GetUserByEmailOrUsername ( dbauthz . AsSystemRestricted ( ctx ), database . GetUserByEmailOrUsernameParams {
Email : req . Email ,
})
if err != nil && ! xerrors . Is ( err , sql . ErrNoRows ) {
logger . Error ( ctx , "unable to fetch user by email" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error." ,
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
// If the user doesn't exist, it will be a default struct.
equal , err := userpassword . Compare ( string ( user . HashedPassword ), req . Password )
if err != nil {
logger . Error ( ctx , "unable to compare passwords" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error." ,
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
if ! equal {
// This message is the same as above to remove ease in detecting whether
// users are registered or not. Attackers still could with a timing attack.
httpapi . Write ( ctx , rw , http . StatusUnauthorized , codersdk . Response {
Message : "Incorrect email or password." ,
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
// If password authentication is disabled and the user does not have the
// owner role, block the request.
if api . DeploymentValues . DisablePasswordAuth {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : "Password authentication is disabled." ,
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
if user . LoginType != database . LoginTypePassword {
httpapi . Write ( ctx , rw , http . StatusForbidden , codersdk . Response {
Message : fmt . Sprintf ( "Incorrect login type, attempting to use %q but user is of login type %q" , database . LoginTypePassword , user . LoginType ),
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
2024-10-31 17:55:42 -05:00
user , err = ActivateDormantUser ( api . Logger , & api . Auditor , api . Database )( ctx , user )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error." ,
Detail : err . Error (),
2023-08-02 16:31:25 +02:00
})
2024-10-31 17:55:42 -05:00
return user , rbac . Subject {}, false
2023-08-02 16:31:25 +02:00
}
2024-06-21 06:30:02 -10:00
subject , userStatus , err := httpmw . UserRBACSubject ( ctx , api . Database , user . ID , rbac . ScopeAll )
2023-06-30 08:38:48 -04:00
if err != nil {
logger . Error ( ctx , "unable to fetch authorization user roles" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error." ,
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
// If the user logged into a suspended account, reject the login request.
2024-06-21 06:30:02 -10:00
if userStatus != database . UserStatusActive {
2023-06-30 08:38:48 -04:00
httpapi . Write ( ctx , rw , http . StatusUnauthorized , codersdk . Response {
2024-06-21 06:30:02 -10:00
Message : fmt . Sprintf ( "Your account is %s. Contact an admin to reactivate your account." , userStatus ),
2023-06-30 08:38:48 -04:00
})
2024-06-21 06:30:02 -10:00
return user , rbac . Subject {}, false
2023-06-30 08:38:48 -04:00
}
2024-06-21 06:30:02 -10:00
return user , subject , true
2023-06-30 08:38:48 -04:00
}
2024-10-31 17:55:42 -05:00
func ActivateDormantUser ( logger slog . Logger , auditor * atomic . Pointer [ audit . Auditor ], db database . Store ) func ( ctx context . Context , user database . User ) ( database . User , error ) {
return func ( ctx context . Context , user database . User ) ( database . User , error ) {
if user . ID == uuid . Nil || user . Status != database . UserStatusDormant {
return user , nil
}
//nolint:gocritic // System needs to update status of the user account (dormant -> active).
newUser , err := db . UpdateUserStatus ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserStatusParams {
2025-12-17 16:49:40 +04:00
ID : user . ID ,
Status : database . UserStatusActive ,
UpdatedAt : dbtime . Now (),
UserIsSeen : true ,
2024-10-31 17:55:42 -05:00
})
if err != nil {
logger . Error ( ctx , "unable to update user status to active" , slog . Error ( err ))
return user , xerrors . Errorf ( "update user status: %w" , err )
}
oldAuditUser := user
newAuditUser := user
newAuditUser . Status = database . UserStatusActive
audit . BackgroundAudit ( ctx , & audit . BackgroundAuditParams [ database . User ]{
Audit : * auditor . Load (),
Log : logger ,
UserID : user . ID ,
Action : database . AuditActionWrite ,
Old : oldAuditUser ,
New : newAuditUser ,
Status : http . StatusOK ,
AdditionalFields : audit . BackgroundTaskFieldsBytes ( ctx , logger , audit . BackgroundSubsystemDormancy ),
})
return newUser , nil
}
}
2023-02-06 15:12:50 -05:00
// Clear the user's session cookie.
//
// @Summary Log out user
// @ID log-out-user
// @Security CoderSessionToken
// @Produce json
// @Tags Users
// @Success 200 {object} codersdk.Response
// @Router /users/logout [post]
func ( api * API ) postLogout ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . APIKey ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionLogout ,
})
)
defer commitAudit ()
// Get a blank token cookie.
cookie := & http . Cookie {
// MaxAge < 0 means to delete the cookie now.
MaxAge : - 1 ,
Name : codersdk . SessionTokenCookie ,
Path : "/" ,
}
2026-02-20 09:01:00 -06:00
http . SetCookie ( rw , api . DeploymentValues . HTTPCookies . Apply ( cookie ))
2023-02-06 15:12:50 -05:00
// Delete the session token from database.
apiKey := httpmw . APIKey ( r )
aReq . Old = apiKey
2023-06-22 20:09:33 +02:00
logger := api . Logger . Named ( userAuthLoggerName )
2023-02-06 15:12:50 -05:00
err := api . Database . DeleteAPIKeyByID ( ctx , apiKey . ID )
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "unable to delete API key" , slog . F ( "api_key" , apiKey . ID ), slog . Error ( err ))
2023-02-06 15:12:50 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error deleting API key." ,
Detail : err . Error (),
})
return
}
2023-04-06 04:41:55 +10:00
// Invalidate all subdomain app tokens. This saves us from having to
// track which app tokens are associated which this browser session and
// doesn't inconvenience the user as they'll just get redirected if they try
// to access the app again.
err = api . Database . DeleteApplicationConnectAPIKeysByUserID ( ctx , apiKey . UserID )
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "unable to invalidate subdomain app tokens" , slog . F ( "user_id" , apiKey . UserID ), slog . Error ( err ))
2023-04-06 04:41:55 +10:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error deleting app tokens." ,
Detail : err . Error (),
})
return
2023-02-06 15:12:50 -05:00
}
aReq . New = database . APIKey {}
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . Response {
Message : "Logged out!" ,
})
}
2022-07-08 21:37:18 -05:00
// GithubOAuth2Team represents a team scoped to an organization.
type GithubOAuth2Team struct {
Organization string
Slug string
}
2022-04-23 17:58:57 -05:00
// GithubOAuth2Provider exposes required functions for the Github authentication flow.
type GithubOAuth2Config struct {
2024-01-10 09:13:30 -06:00
promoauth . OAuth2Config
2022-04-23 17:58:57 -05:00
AuthenticatedUser func ( ctx context . Context , client * http . Client ) ( * github . User , error )
ListEmails func ( ctx context . Context , client * http . Client ) ([] * github . UserEmail , error )
ListOrganizationMemberships func ( ctx context . Context , client * http . Client ) ([] * github . Membership , error )
2022-07-22 13:54:08 -05:00
TeamMembership func ( ctx context . Context , client * http . Client , org , team , username string ) ( * github . Membership , error )
2022-04-23 17:58:57 -05:00
2025-02-21 18:42:16 +01:00
DeviceFlowEnabled bool
ExchangeDeviceCode func ( ctx context . Context , deviceCode string ) ( * oauth2 . Token , error )
AuthorizeDevice func ( ctx context . Context ) ( * codersdk . ExternalAuthDevice , error )
2022-04-23 17:58:57 -05:00
AllowSignups bool
2022-11-15 18:56:46 +02:00
AllowEveryone bool
2022-04-23 17:58:57 -05:00
AllowOrganizations [] string
2022-07-08 21:37:18 -05:00
AllowTeams [] GithubOAuth2Team
2025-02-25 16:31:33 +01:00
DefaultProviderConfigured bool
2022-04-23 17:58:57 -05:00
}
2025-12-15 11:41:47 -06:00
func ( * GithubOAuth2Config ) PKCESupported () [] promoauth . Oauth2PKCEChallengeMethod {
return [] promoauth . Oauth2PKCEChallengeMethod { promoauth . PKCEChallengeMethodSha256 }
}
2025-02-21 18:42:16 +01:00
func ( c * GithubOAuth2Config ) Exchange ( ctx context . Context , code string , opts ... oauth2 . AuthCodeOption ) ( * oauth2 . Token , error ) {
if ! c . DeviceFlowEnabled {
return c . OAuth2Config . Exchange ( ctx , code , opts ... )
}
return c . ExchangeDeviceCode ( ctx , code )
}
func ( c * GithubOAuth2Config ) AuthCodeURL ( state string , opts ... oauth2 . AuthCodeOption ) string {
if ! c . DeviceFlowEnabled {
return c . OAuth2Config . AuthCodeURL ( state , opts ... )
}
// This is an absolute path in the Coder app. The device flow is orchestrated
// by the Coder frontend, so we need to redirect the user to the device flow page.
return "/login/device?state=" + state
}
2023-01-11 14:08:04 +01:00
// @Summary Get authentication methods
// @ID get-authentication-methods
// @Security CoderSessionToken
// @Produce json
// @Tags Users
// @Success 200 {object} codersdk.AuthMethods
// @Router /users/authmethods [get]
2022-09-21 17:07:00 -05:00
func ( api * API ) userAuthMethods ( rw http . ResponseWriter , r * http . Request ) {
2023-01-31 13:33:25 -05:00
var signInText string
var iconURL string
if api . OIDCConfig != nil {
signInText = api . OIDCConfig . SignInText
}
if api . OIDCConfig != nil {
iconURL = api . OIDCConfig . IconURL
}
2022-09-21 17:07:00 -05:00
httpapi . Write ( r . Context (), rw , http . StatusOK , codersdk . AuthMethods {
2024-04-25 16:36:51 -06:00
TermsOfServiceURL : api . DeploymentValues . TermsOfServiceURL . Value (),
2023-02-07 01:58:21 +11:00
Password : codersdk . AuthMethod {
2023-03-07 15:10:01 -06:00
Enabled : ! api . DeploymentValues . DisablePasswordAuth . Value (),
2023-02-07 01:58:21 +11:00
},
2025-02-25 16:31:33 +01:00
Github : codersdk . GithubAuthMethod {
Enabled : api . GithubOAuth2Config != nil ,
DefaultProviderConfigured : api . GithubOAuth2Config != nil && api . GithubOAuth2Config . DefaultProviderConfigured ,
},
2023-01-31 13:33:25 -05:00
OIDC : codersdk . OIDCAuthMethod {
AuthMethod : codersdk . AuthMethod { Enabled : api . OIDCConfig != nil },
SignInText : signInText ,
IconURL : iconURL ,
},
2022-04-23 17:58:57 -05:00
})
}
2025-02-21 18:42:16 +01:00
// @Summary Get Github device auth.
// @ID get-github-device-auth
// @Security CoderSessionToken
// @Produce json
// @Tags Users
// @Success 200 {object} codersdk.ExternalAuthDevice
// @Router /users/oauth2/github/device [get]
func ( api * API ) userOAuth2GithubDevice ( rw http . ResponseWriter , r * http . Request ) {
var (
ctx = r . Context ()
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . APIKey ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionLogin ,
})
)
aReq . Old = database . APIKey {}
defer commitAudit ()
if api . GithubOAuth2Config == nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Github OAuth2 is not enabled." ,
})
return
}
if ! api . GithubOAuth2Config . DeviceFlowEnabled {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Device flow is not enabled for Github OAuth2." ,
})
return
}
deviceAuth , err := api . GithubOAuth2Config . AuthorizeDevice ( ctx )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to authorize device." ,
Detail : err . Error (),
})
return
}
httpapi . Write ( ctx , rw , http . StatusOK , deviceAuth )
}
2023-01-11 14:08:04 +01:00
// @Summary OAuth 2.0 GitHub Callback
2023-01-13 12:27:21 +01:00
// @ID oauth-20-github-callback
2023-01-11 14:08:04 +01:00
// @Security CoderSessionToken
// @Tags Users
// @Success 307
// @Router /users/oauth2/github/callback [get]
2022-05-25 22:14:08 -05:00
func ( api * API ) userOAuth2Github ( rw http . ResponseWriter , r * http . Request ) {
2022-08-17 18:00:53 -05:00
var (
2023-03-04 14:32:07 -06:00
// userOAuth2Github is a system function.
//nolint:gocritic
ctx = dbauthz . AsSystemRestricted ( r . Context ())
2023-02-06 15:12:50 -05:00
state = httpmw . OAuth2 ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . APIKey ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionLogin ,
})
2022-08-17 18:00:53 -05:00
)
2023-02-06 15:12:50 -05:00
aReq . Old = database . APIKey {}
defer commitAudit ()
2022-04-23 17:58:57 -05:00
2022-08-17 18:00:53 -05:00
oauthClient := oauth2 . NewClient ( ctx , oauth2 . StaticTokenSource ( state . Token ))
2022-11-15 18:56:46 +02:00
2023-06-22 20:09:33 +02:00
logger := api . Logger . Named ( userAuthLoggerName )
2022-11-15 18:56:46 +02:00
var selectedMemberships [] * github . Membership
var organizationNames [] string
2023-12-07 09:19:31 -05:00
redirect := state . Redirect
2022-11-15 18:56:46 +02:00
if ! api . GithubOAuth2Config . AllowEveryone {
memberships , err := api . GithubOAuth2Config . ListOrganizationMemberships ( ctx , oauthClient )
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "unable to list organization members" , slog . Error ( err ))
2022-11-15 18:56:46 +02:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Internal error fetching authenticated Github user organizations." ,
Detail : err . Error (),
})
return
2022-10-07 19:53:58 +03:00
}
2022-11-15 18:56:46 +02:00
for _ , membership := range memberships {
if membership . GetState () != "active" {
2022-04-23 17:58:57 -05:00
continue
}
2022-11-15 18:56:46 +02:00
for _ , allowed := range api . GithubOAuth2Config . AllowOrganizations {
if * membership . Organization . Login != allowed {
continue
}
selectedMemberships = append ( selectedMemberships , membership )
organizationNames = append ( organizationNames , membership . Organization . GetLogin ())
break
}
}
if len ( selectedMemberships ) == 0 {
2025-03-03 16:05:45 +01:00
status := http . StatusUnauthorized
msg := "You aren't a member of the authorized Github organizations!"
if api . GithubOAuth2Config . DeviceFlowEnabled {
// In the device flow, the error is rendered client-side.
httpapi . Write ( ctx , rw , status , codersdk . Response {
Message : "Unauthorized" ,
Detail : msg ,
})
} else {
httpmw . CustomRedirectToLogin ( rw , r , redirect , msg , status )
}
2022-11-15 18:56:46 +02:00
return
2022-04-23 17:58:57 -05:00
}
}
2022-08-17 18:00:53 -05:00
ghUser , err := api . GithubOAuth2Config . AuthenticatedUser ( ctx , oauthClient )
2022-07-22 13:54:08 -05:00
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: unable to fetch authenticated user" , slog . Error ( err ))
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-07-22 13:54:08 -05:00
Message : "Internal error fetching authenticated Github user." ,
Detail : err . Error (),
})
return
}
2022-07-08 21:37:18 -05:00
// The default if no teams are specified is to allow all.
2022-11-15 18:56:46 +02:00
if ! api . GithubOAuth2Config . AllowEveryone && len ( api . GithubOAuth2Config . AllowTeams ) > 0 {
2022-07-22 13:54:08 -05:00
var allowedTeam * github . Membership
2022-07-12 19:45:43 -05:00
for _ , allowTeam := range api . GithubOAuth2Config . AllowTeams {
2022-11-15 18:56:46 +02:00
if allowedTeam != nil {
break
2022-07-12 19:45:43 -05:00
}
2022-11-15 18:56:46 +02:00
for _ , selectedMembership := range selectedMemberships {
if allowTeam . Organization != * selectedMembership . Organization . Login {
// This needs to continue because multiple organizations
// could exist in the allow/team listings.
continue
}
2022-07-12 19:45:43 -05:00
2022-11-15 18:56:46 +02:00
allowedTeam , err = api . GithubOAuth2Config . TeamMembership ( ctx , oauthClient , allowTeam . Organization , allowTeam . Slug , * ghUser . Login )
// The calling user may not have permission to the requested team!
if err != nil {
continue
}
2022-07-08 21:37:18 -05:00
}
}
if allowedTeam == nil {
2025-03-03 16:05:45 +01:00
msg := fmt . Sprintf ( "You aren't a member of an authorized team in the %v Github organization(s)!" , organizationNames )
status := http . StatusUnauthorized
if api . GithubOAuth2Config . DeviceFlowEnabled {
// In the device flow, the error is rendered client-side.
httpapi . Write ( ctx , rw , status , codersdk . Response {
Message : "Unauthorized" ,
Detail : msg ,
})
} else {
httpmw . CustomRedirectToLogin ( rw , r , redirect , msg , status )
}
2022-07-08 21:37:18 -05:00
return
}
}
2022-08-17 18:00:53 -05:00
emails , err := api . GithubOAuth2Config . ListEmails ( ctx , oauthClient )
2022-04-23 17:58:57 -05:00
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: unable to list emails" , slog . Error ( err ))
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-06-07 09:33:06 -05:00
Message : "Internal error fetching personal Github user." ,
2022-06-03 16:48:09 -05:00
Detail : err . Error (),
2022-04-23 17:58:57 -05:00
})
return
}
2022-08-22 18:13:46 -05:00
var verifiedEmail * github . UserEmail
2022-04-23 17:58:57 -05:00
for _ , email := range emails {
2022-08-22 18:13:46 -05:00
if email . GetVerified () && email . GetPrimary () {
verifiedEmail = email
break
2022-04-23 17:58:57 -05:00
}
2022-08-17 18:00:53 -05:00
}
2022-08-22 18:13:46 -05:00
if verifiedEmail == nil {
2023-01-13 14:30:48 +00:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-08-22 18:13:46 -05:00
Message : "Your primary email must be verified on GitHub!" ,
2022-04-23 17:58:57 -05:00
})
2022-08-17 18:00:53 -05:00
return
}
2024-06-06 13:37:08 +01:00
ghName := ghUser . GetName ()
2024-09-04 18:17:53 +10:00
normName := codersdk . NormalizeRealUsername ( ghName )
2024-06-06 13:37:08 +01:00
2024-01-29 09:13:46 -06:00
// If we have a nil GitHub ID, that is a big problem. That would mean we link
// this user and all other users with this bug to the same uuid.
// We should instead throw an error. This should never occur in production.
//
// Verified that the lowest ID on GitHub is "1", so 0 should never occur.
if ghUser . GetID () == 0 {
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "The GitHub user ID is missing, this should never happen. Please report this error." ,
// If this happens, the User could either be:
// - Empty, in which case all these fields would also be empty.
// - Not a user, in which case the "Type" would be something other than "User"
Detail : fmt . Sprintf ( "Other user fields: name=%q, email=%q, type=%q" ,
ghUser . GetName (),
ghUser . GetEmail (),
ghUser . GetType (),
),
})
return
}
2023-02-06 15:12:50 -05:00
user , link , err := findLinkedUser ( ctx , api . Database , githubLinkedID ( ghUser ), verifiedEmail . GetEmail ())
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: unable to find linked user" , slog . F ( "gh_user" , ghUser . Name ), slog . Error ( err ))
2023-02-06 15:12:50 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to find linked user." ,
Detail : err . Error (),
})
return
}
2023-04-12 11:46:16 -07:00
// If a new user is authenticating for the first time
// the audit action is 'register', not 'login'
if user . ID == uuid . Nil {
aReq . Action = database . AuditActionRegister
}
2024-06-11 09:34:05 -04:00
// See: https://github.com/coder/coder/discussions/13340
// In GitHub Enterprise, admins are permitted to have `_`
// in their usernames. This is janky, but much better
// than changing the username format globally.
username := ghUser . GetLogin ()
if strings . Contains ( username , "_" ) {
api . Logger . Warn ( ctx , "login associates a github username that contains underscores. underscores are not permitted in usernames, replacing with `-`" , slog . F ( "username" , username ))
username = strings . ReplaceAll ( username , "_" , "-" )
}
2023-06-30 08:38:48 -04:00
params := ( & oauthLoginParams {
2023-02-06 15:12:50 -05:00
User : user ,
Link : link ,
2022-08-22 18:13:46 -05:00
State : state ,
LinkedID : githubLinkedID ( ghUser ),
LoginType : database . LoginTypeGithub ,
AllowSignups : api . GithubOAuth2Config . AllowSignups ,
Email : verifiedEmail . GetEmail (),
2024-06-11 09:34:05 -04:00
Username : username ,
2022-09-04 11:44:27 -05:00
AvatarURL : ghUser . GetAvatarURL (),
2024-06-06 13:37:08 +01:00
Name : normName ,
2024-11-14 10:05:44 -06:00
UserClaims : database . UserLinkClaims {},
2024-09-11 13:43:50 -05:00
GroupSync : idpsync . GroupParams {
2024-11-08 08:44:14 -06:00
SyncEntitled : false ,
2024-09-11 13:43:50 -05:00
},
2024-08-30 11:19:36 -05:00
OrganizationSync : idpsync . OrganizationParams {
2024-11-08 08:44:14 -06:00
SyncEntitled : false ,
2024-08-30 11:19:36 -05:00
},
2023-06-30 08:38:48 -04:00
}). SetInitAuditRequest ( func ( params * audit . RequestParams ) ( * audit . Request [ database . User ], func ()) {
return audit . InitRequest [ database . User ]( rw , params )
2022-08-22 18:13:46 -05:00
})
2024-08-02 11:49:36 -05:00
cookies , user , key , err := api . oauthLogin ( r , params )
2023-06-30 08:38:48 -04:00
defer params . CommitAuditLogs ()
2022-08-17 18:00:53 -05:00
if err != nil {
2024-08-30 11:19:36 -05:00
if httpErr := idpsync . IsHTTPError ( err ); httpErr != nil {
2025-02-25 15:54:38 +01:00
// In the device flow, the error page is rendered client-side.
if api . GithubOAuth2Config . DeviceFlowEnabled && httpErr . RenderStaticPage {
httpErr . RenderStaticPage = false
}
2024-08-30 11:19:36 -05:00
httpErr . Write ( rw , r )
return
}
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: login failed" , slog . F ( "user" , user . Username ), slog . Error ( err ))
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-08-22 18:13:46 -05:00
Message : "Failed to process OAuth login." ,
2022-08-17 18:00:53 -05:00
Detail : err . Error (),
})
return
}
2024-08-02 11:49:36 -05:00
// If the user is logging in with github.com we update their associated
// GitHub user ID to the new one.
2025-03-20 14:24:38 +01:00
// We use AuthCodeURL from the OAuth2Config field instead of the one on
// GithubOAuth2Config because when device flow is configured, AuthCodeURL
// is overridden and returns a value that doesn't pass the URL check.
2025-03-27 16:06:58 -05:00
// codeql[go/constant-oauth2-state] -- We are solely using the AuthCodeURL from the OAuth2Config field in order to validate the hostname of the external auth provider.
2025-03-20 14:24:38 +01:00
if externalauth . IsGithubDotComURL ( api . GithubOAuth2Config . OAuth2Config . AuthCodeURL ( "" )) && user . GithubComUserID . Int64 != ghUser . GetID () {
2024-08-02 11:49:36 -05:00
err = api . Database . UpdateUserGithubComUserID ( ctx , database . UpdateUserGithubComUserIDParams {
ID : user . ID ,
GithubComUserID : sql . NullInt64 {
Int64 : ghUser . GetID (),
Valid : true ,
},
})
if err != nil {
logger . Error ( ctx , "oauth2: unable to update user github id" , slog . F ( "user" , user . Username ), slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to update user GitHub ID." ,
Detail : err . Error (),
})
return
}
}
2023-02-06 15:12:50 -05:00
aReq . New = key
2023-03-22 12:52:13 -07:00
aReq . UserID = key . UserID
2022-08-17 18:00:53 -05:00
2023-06-30 08:38:48 -04:00
for _ , cookie := range cookies {
http . SetCookie ( rw , cookie )
}
2022-04-23 17:58:57 -05:00
2024-09-10 15:58:50 +01:00
redirect = uriFromURL ( redirect )
2025-02-21 18:42:16 +01:00
if api . GithubOAuth2Config . DeviceFlowEnabled {
// In the device flow, the redirect is handled client-side.
httpapi . Write ( ctx , rw , http . StatusOK , codersdk . OAuth2DeviceFlowCallbackResponse {
RedirectURL : redirect ,
})
} else {
http . Redirect ( rw , r , redirect , http . StatusTemporaryRedirect )
}
2022-04-23 17:58:57 -05:00
}
2022-07-31 23:05:35 -05:00
type OIDCConfig struct {
2024-01-10 09:13:30 -06:00
promoauth . OAuth2Config
2022-07-31 23:05:35 -05:00
2023-01-16 16:06:39 -06:00
Provider * oidc . Provider
2022-07-31 23:05:35 -05:00
Verifier * oidc . IDTokenVerifier
2022-12-06 05:20:53 +11:00
// EmailDomains are the domains to enforce when a user authenticates.
EmailDomain [] string
2022-07-31 23:05:35 -05:00
AllowSignups bool
2022-11-25 10:10:09 +00:00
// IgnoreEmailVerified allows ignoring the email_verified claim
// from an upstream OIDC provider. See #5065 for context.
IgnoreEmailVerified bool
2023-01-04 22:16:31 +01:00
// UsernameField selects the claim field to be used as the created user's
// username.
UsernameField string
2023-03-30 09:36:57 +01:00
// EmailField selects the claim field to be used as the created user's
// email.
EmailField string
2024-06-06 13:37:08 +01:00
// NameField selects the claim field to be used as the created user's
// full / given name.
NameField string
2023-03-30 09:36:57 +01:00
// AuthURLParams are additional parameters to be passed to the OIDC provider
// when requesting an access token.
AuthURLParams map [ string ] string
2025-02-24 13:38:20 -06:00
// SecondaryClaims indicates where to source additional claim information from.
// The standard is either 'MergedClaimsSourceNone' or 'MergedClaimsSourceUserInfo'.
//
// The OIDC compliant way is to use the userinfo endpoint. This option
// is useful when the userinfo endpoint does not exist or causes undesirable
// behavior.
SecondaryClaims MergedClaimsSource
2023-01-31 13:33:25 -05:00
// SignInText is the text to display on the OIDC login button
SignInText string
// IconURL points to the URL of an icon to display on the OIDC login button
IconURL string
2024-02-01 18:01:25 +01:00
// SignupsDisabledText is the text do display on the static error page.
SignupsDisabledText string
2025-12-15 11:41:47 -06:00
PKCEMethods [] promoauth . Oauth2PKCEChallengeMethod
}
// PKCESupported is to prevent nil pointer dereference.
func ( o * OIDCConfig ) PKCESupported () [] promoauth . Oauth2PKCEChallengeMethod {
if o == nil {
return nil
}
return o . PKCEMethods
2022-07-31 23:05:35 -05:00
}
2023-01-11 14:08:04 +01:00
// @Summary OpenID Connect Callback
2023-01-13 12:27:21 +01:00
// @ID openid-connect-callback
2023-01-11 14:08:04 +01:00
// @Security CoderSessionToken
// @Tags Users
// @Success 307
// @Router /users/oidc/callback [get]
2022-07-31 23:05:35 -05:00
func ( api * API ) userOIDC ( rw http . ResponseWriter , r * http . Request ) {
2022-08-17 18:00:53 -05:00
var (
2023-03-04 14:32:07 -06:00
// userOIDC is a system function.
//nolint:gocritic
ctx = dbauthz . AsSystemRestricted ( r . Context ())
2023-02-06 15:12:50 -05:00
state = httpmw . OAuth2 ( r )
auditor = api . Auditor . Load ()
aReq , commitAudit = audit . InitRequest [ database . APIKey ]( rw , & audit . RequestParams {
Audit : * auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionLogin ,
})
2022-08-17 18:00:53 -05:00
)
2023-02-06 15:12:50 -05:00
aReq . Old = database . APIKey {}
defer commitAudit ()
2022-07-31 23:05:35 -05:00
// See the example here: https://github.com/coreos/go-oidc
rawIDToken , ok := state . Token . Extra ( "id_token" ).( string )
if ! ok {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-07-31 23:05:35 -05:00
Message : "id_token not found in response payload. Ensure your OIDC callback is configured correctly!" ,
})
return
}
2022-08-17 18:00:53 -05:00
idToken , err := api . OIDCConfig . Verifier . Verify ( ctx , rawIDToken )
2022-07-31 23:05:35 -05:00
if err != nil {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-07-31 23:05:35 -05:00
Message : "Failed to verify OIDC token." ,
Detail : err . Error (),
})
return
}
2023-06-22 20:09:33 +02:00
logger := api . Logger . Named ( userAuthLoggerName )
2022-09-08 09:06:00 -05:00
// "email_verified" is an optional claim that changes the behavior
// of our OIDC handler, so each property must be pulled manually out
// of the claim mapping.
2023-11-27 10:47:23 -06:00
idtokenClaims := map [ string ] interface {}{}
err = idToken . Claims ( & idtokenClaims )
2022-07-31 23:05:35 -05:00
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: unable to extract OIDC claims" , slog . Error ( err ))
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-07-31 23:05:35 -05:00
Message : "Failed to extract OIDC claims." ,
Detail : err . Error (),
})
return
}
2023-01-16 16:06:39 -06:00
2025-02-10 09:31:08 -06:00
if idToken . Subject == "" {
logger . Error ( ctx , "oauth2: missing 'sub' claim field in OIDC token" ,
slog . F ( "source" , "id_token" ),
slog . F ( "claim_fields" , claimFields ( idtokenClaims )),
slog . F ( "blank" , blankFields ( idtokenClaims )),
)
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "OIDC token missing 'sub' claim field or 'sub' claim field is empty." ,
Detail : "'sub' claim field is required to be unique for all users by a given issue, " +
"an empty field is invalid and this authentication attempt is rejected." ,
})
return
}
2023-06-22 20:09:33 +02:00
logger . Debug ( ctx , "got oidc claims" ,
2023-04-05 09:07:43 +01:00
slog . F ( "source" , "id_token" ),
2023-11-27 10:47:23 -06:00
slog . F ( "claim_fields" , claimFields ( idtokenClaims )),
slog . F ( "blank" , blankFields ( idtokenClaims )),
2023-04-05 09:07:43 +01:00
)
2023-01-16 16:06:39 -06:00
// Not all claims are necessarily embedded in the `id_token`.
// In GitLab, the username is left empty and must be fetched in UserInfo.
//
// The OIDC specification says claims can be in either place, so we fetch
2023-04-05 09:07:43 +01:00
// user info if required and merge the two claim sets to be sure we have
// all of the correct data.
//
// Some providers (e.g. ADFS) do not support custom OIDC claims in the
// UserInfo endpoint, so we allow users to disable it and only rely on the
// ID token.
2025-02-24 13:38:20 -06:00
//
2023-11-27 10:47:23 -06:00
// If user info is skipped, the idtokenClaims are the claims.
mergedClaims := idtokenClaims
2025-02-24 13:38:20 -06:00
supplementaryClaims := make ( map [ string ] interface {})
switch api . OIDCConfig . SecondaryClaims {
case MergedClaimsSourceUserInfo :
supplementaryClaims , ok = api . userInfoClaims ( ctx , rw , state , logger )
if ! ok {
2023-01-16 16:06:39 -06:00
return
}
2025-02-24 13:38:20 -06:00
// The precedence ordering is userInfoClaims > idTokenClaims.
// Note: Unsure why exactly this is the case. idTokenClaims feels more
// important?
mergedClaims = mergeClaims ( idtokenClaims , supplementaryClaims )
case MergedClaimsSourceAccessToken :
supplementaryClaims , ok = api . accessTokenClaims ( ctx , rw , state , logger )
if ! ok {
return
}
// idTokenClaims take priority over accessTokenClaims. The order should
// not matter. It is just safer to assume idTokenClaims is the truth,
// and accessTokenClaims are supplemental.
mergedClaims = mergeClaims ( supplementaryClaims , idtokenClaims )
case MergedClaimsSourceNone :
// noop, keep the userInfoClaims empty
default :
// This should never happen and is a developer error
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Invalid source for secondary user claims." ,
Detail : fmt . Sprintf ( "invalid source: %q" , api . OIDCConfig . SecondaryClaims ),
})
return // Invalid MergedClaimsSource
2023-03-16 19:33:45 -05:00
}
2023-11-27 10:47:23 -06:00
usernameRaw , ok := mergedClaims [ api . OIDCConfig . UsernameField ]
2022-10-17 14:14:49 -05:00
var username string
if ok {
username , _ = usernameRaw .( string )
}
2023-02-02 13:53:48 -06:00
2023-11-27 10:47:23 -06:00
emailRaw , ok := mergedClaims [ api . OIDCConfig . EmailField ]
2022-09-08 09:06:00 -05:00
if ! ok {
2022-10-17 14:14:49 -05:00
// Email is an optional claim in OIDC and
// instead the email is frequently sent in
// "preferred_username". See:
// https://github.com/coder/coder/issues/4472
_ , err = mail . ParseAddress ( username )
if err != nil {
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "No email found in OIDC payload!" ,
})
return
}
emailRaw = username
2022-07-31 23:05:35 -05:00
}
2023-02-02 13:53:48 -06:00
2022-09-08 09:06:00 -05:00
email , ok := emailRaw .( string )
if ! ok {
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
2022-09-08 09:06:00 -05:00
Message : fmt . Sprintf ( "Email in OIDC payload isn't a string. Got: %t" , emailRaw ),
2022-07-31 23:05:35 -05:00
})
return
}
2023-02-02 13:53:48 -06:00
2023-11-27 10:47:23 -06:00
verifiedRaw , ok := mergedClaims [ "email_verified" ]
2022-09-08 09:06:00 -05:00
if ok {
verified , ok := verifiedRaw .( bool )
if ok && ! verified {
2022-11-25 10:10:09 +00:00
if ! api . OIDCConfig . IgnoreEmailVerified {
2026-03-16 11:56:59 -04:00
site . RenderStaticErrorPage ( rw , r , site . ErrorPageData {
Status : http . StatusForbidden ,
HideStatus : true ,
Title : "Email not verified" ,
Description : fmt . Sprintf (
"Verify the %q email address on your OIDC provider to authenticate!" ,
email ,
),
Actions : [] site . Action {
{ URL : "/login" , Text : "Back to login" },
},
2022-11-25 10:10:09 +00:00
})
return
}
2026-03-16 11:56:59 -04:00
logger . Warn ( ctx , "allowing unverified oidc email" , slog . F ( "email" , email ))
2022-09-08 09:06:00 -05:00
}
}
2023-02-02 13:53:48 -06:00
2022-07-31 23:05:35 -05:00
// The username is a required property in Coder. We make a best-effort
// attempt at using what the claims provide, but if that fails we will
// generate a random username.
2024-09-04 18:17:53 +10:00
usernameValid := codersdk . NameValid ( username )
2022-10-24 19:46:24 -05:00
if usernameValid != nil {
2022-07-31 23:05:35 -05:00
// If no username is provided, we can default to use the email address.
// This will be converted in the from function below, so it's safe
// to keep the domain.
2022-09-08 09:06:00 -05:00
if username == "" {
username = email
2022-07-31 23:05:35 -05:00
}
2024-09-04 18:17:53 +10:00
username = codersdk . UsernameFrom ( username )
2022-07-31 23:05:35 -05:00
}
2023-02-02 13:53:48 -06:00
2022-12-06 05:20:53 +11:00
if len ( api . OIDCConfig . EmailDomain ) > 0 {
ok = false
2024-03-04 11:52:03 -06:00
emailSp := strings . Split ( email , "@" )
if len ( emailSp ) == 1 {
2026-03-16 11:56:59 -04:00
site . RenderStaticErrorPage ( rw , r , site . ErrorPageData {
Status : http . StatusForbidden ,
HideStatus : true ,
Title : "Unauthorized email" ,
Description : fmt . Sprintf (
"Your email %q is not from an authorized domain! Please contact your administrator." ,
email ,
),
Actions : [] site . Action {
{ URL : "/login" , Text : "Back to login" },
},
2024-03-04 11:52:03 -06:00
})
return
}
userEmailDomain := emailSp [ len ( emailSp ) - 1 ]
2022-12-06 05:20:53 +11:00
for _ , domain := range api . OIDCConfig . EmailDomain {
2024-06-14 09:29:07 +01:00
// Folks sometimes enter EmailDomain with a leading '@'.
domain = strings . TrimPrefix ( domain , "@" )
2024-03-04 11:52:03 -06:00
if strings . EqualFold ( userEmailDomain , domain ) {
2022-12-06 05:20:53 +11:00
ok = true
break
}
}
if ! ok {
2026-03-16 11:56:59 -04:00
site . RenderStaticErrorPage ( rw , r , site . ErrorPageData {
Status : http . StatusForbidden ,
HideStatus : true ,
Title : "Unauthorized email" ,
Description : fmt . Sprintf (
"Your email %q is not from an authorized domain! Please contact your administrator." ,
email ,
),
Actions : [] site . Action {
{ URL : "/login" , Text : "Back to login" },
},
2022-07-31 23:05:35 -05:00
})
return
}
}
2023-02-02 13:53:48 -06:00
2024-06-06 13:37:08 +01:00
// The 'name' is an optional property in Coder. If not specified,
// it will be left blank.
var name string
nameRaw , ok := mergedClaims [ api . OIDCConfig . NameField ]
if ok {
name , _ = nameRaw .( string )
2024-09-04 18:17:53 +10:00
name = codersdk . NormalizeRealUsername ( name )
2024-06-06 13:37:08 +01:00
}
2022-09-08 09:06:00 -05:00
var picture string
2023-11-27 10:47:23 -06:00
pictureRaw , ok := mergedClaims [ "picture" ]
2022-09-08 09:06:00 -05:00
if ok {
picture , _ = pictureRaw .( string )
}
2024-06-06 13:37:08 +01:00
ctx = slog . With ( ctx , slog . F ( "email" , email ), slog . F ( "username" , username ), slog . F ( "name" , name ))
2023-11-29 09:24:00 -06:00
2023-02-06 15:12:50 -05:00
user , link , err := findLinkedUser ( ctx , api . Database , oidcLinkedID ( idToken ), email )
if err != nil {
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: unable to find linked user" , slog . F ( "email" , email ), slog . Error ( err ))
2023-02-06 15:12:50 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to find linked user." ,
Detail : err . Error (),
})
return
}
2024-08-30 11:19:36 -05:00
orgSync , orgSyncErr := api . IDPSync . ParseOrganizationClaims ( ctx , mergedClaims )
if orgSyncErr != nil {
orgSyncErr . Write ( rw , r )
return
}
2024-09-11 13:43:50 -05:00
groupSync , groupSyncErr := api . IDPSync . ParseGroupClaims ( ctx , mergedClaims )
if groupSyncErr != nil {
groupSyncErr . Write ( rw , r )
return
}
2024-09-16 19:03:25 -05:00
roleSync , roleSyncErr := api . IDPSync . ParseRoleClaims ( ctx , mergedClaims )
if roleSyncErr != nil {
roleSyncErr . Write ( rw , r )
return
}
2023-04-12 11:46:16 -07:00
// If a new user is authenticating for the first time
// the audit action is 'register', not 'login'
if user . ID == uuid . Nil {
aReq . Action = database . AuditActionRegister
}
2023-06-30 08:38:48 -04:00
params := ( & oauthLoginParams {
2024-09-11 13:43:50 -05:00
User : user ,
Link : link ,
State : state ,
LinkedID : oidcLinkedID ( idToken ),
LoginType : database . LoginTypeOIDC ,
AllowSignups : api . OIDCConfig . AllowSignups ,
Email : email ,
Username : username ,
Name : name ,
AvatarURL : picture ,
OrganizationSync : orgSync ,
GroupSync : groupSync ,
2024-09-16 19:03:25 -05:00
RoleSync : roleSync ,
2024-11-14 10:05:44 -06:00
UserClaims : database . UserLinkClaims {
2023-11-27 10:47:23 -06:00
IDTokenClaims : idtokenClaims ,
2025-02-24 13:38:20 -06:00
UserInfoClaims : supplementaryClaims ,
2024-11-18 11:58:19 -06:00
MergedClaims : mergedClaims ,
2023-11-27 10:47:23 -06:00
},
2023-06-30 08:38:48 -04:00
}). SetInitAuditRequest ( func ( params * audit . RequestParams ) ( * audit . Request [ database . User ], func ()) {
return audit . InitRequest [ database . User ]( rw , params )
2022-08-22 18:13:46 -05:00
})
2024-08-02 11:49:36 -05:00
cookies , user , key , err := api . oauthLogin ( r , params )
2023-06-30 08:38:48 -04:00
defer params . CommitAuditLogs ()
2022-08-17 18:00:53 -05:00
if err != nil {
2024-08-30 11:19:36 -05:00
if hErr := idpsync . IsHTTPError ( err ); hErr != nil {
hErr . Write ( rw , r )
return
}
2023-06-22 20:09:33 +02:00
logger . Error ( ctx , "oauth2: login failed" , slog . F ( "user" , user . Username ), slog . Error ( err ))
2022-09-21 17:07:00 -05:00
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
2022-08-22 18:13:46 -05:00
Message : "Failed to process OAuth login." ,
2022-08-17 18:00:53 -05:00
Detail : err . Error (),
})
return
}
2023-02-06 15:12:50 -05:00
aReq . New = key
2023-03-22 12:52:13 -07:00
aReq . UserID = key . UserID
2022-08-17 18:00:53 -05:00
2023-06-30 08:38:48 -04:00
for i := range cookies {
http . SetCookie ( rw , cookies [ i ])
}
2022-07-31 23:05:35 -05:00
redirect := state . Redirect
2024-09-10 15:58:50 +01:00
// Strip the host if it exists on the URL to prevent
// any nefarious redirects.
redirect = uriFromURL ( redirect )
2022-07-31 23:05:35 -05:00
http . Redirect ( rw , r , redirect , http . StatusTemporaryRedirect )
}
2022-08-17 18:00:53 -05:00
2025-02-24 13:38:20 -06:00
func ( api * API ) accessTokenClaims ( ctx context . Context , rw http . ResponseWriter , state httpmw . OAuth2State , logger slog . Logger ) ( accessTokenClaims map [ string ] interface {}, ok bool ) {
// Assume the access token is a jwt, and signed by the provider.
accessToken , err := api . OIDCConfig . Verifier . Verify ( ctx , state . Token . AccessToken )
if err != nil {
logger . Error ( ctx , "oauth2: unable to verify access token as secondary claims source" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "Failed to verify access token." ,
Detail : fmt . Sprintf ( "sourcing secondary claims from access token: %s" , err . Error ()),
})
return nil , false
}
rawClaims := make ( map [ string ] any )
err = accessToken . Claims ( & rawClaims )
if err != nil {
logger . Error ( ctx , "oauth2: unable to unmarshal access token claims" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to unmarshal access token claims." ,
Detail : err . Error (),
})
return nil , false
}
return rawClaims , true
}
func ( api * API ) userInfoClaims ( ctx context . Context , rw http . ResponseWriter , state httpmw . OAuth2State , logger slog . Logger ) ( userInfoClaims map [ string ] interface {}, ok bool ) {
userInfoClaims = make ( map [ string ] interface {})
userInfo , err := api . OIDCConfig . Provider . UserInfo ( ctx , oauth2 . StaticTokenSource ( state . Token ))
2025-03-26 01:56:39 -05:00
switch {
case err == nil :
2025-02-24 13:38:20 -06:00
err = userInfo . Claims ( & userInfoClaims )
if err != nil {
logger . Error ( ctx , "oauth2: unable to unmarshal user info claims" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to unmarshal user info claims." ,
Detail : err . Error (),
})
return nil , false
}
logger . Debug ( ctx , "got oidc claims" ,
slog . F ( "source" , "userinfo" ),
slog . F ( "claim_fields" , claimFields ( userInfoClaims )),
slog . F ( "blank" , blankFields ( userInfoClaims )),
)
2025-03-26 01:56:39 -05:00
case ! strings . Contains ( err . Error (), "user info endpoint is not supported by this provider" ):
2025-02-24 13:38:20 -06:00
logger . Error ( ctx , "oauth2: unable to obtain user information claims" , slog . Error ( err ))
httpapi . Write ( ctx , rw , http . StatusInternalServerError , codersdk . Response {
Message : "Failed to obtain user information claims." ,
Detail : "The attempt to fetch claims via the UserInfo endpoint failed: " + err . Error (),
})
return nil , false
2025-03-26 01:56:39 -05:00
default :
2025-02-24 13:38:20 -06:00
// The OIDC provider does not support the UserInfo endpoint.
// This is not an error, but we should log it as it may mean
// that some claims are missing.
logger . Warn ( ctx , "OIDC provider does not support the user info endpoint, ensure that all required claims are present in the id_token" ,
slog . Error ( err ),
)
}
return userInfoClaims , true
}
2023-04-05 09:07:43 +01:00
// claimFields returns the sorted list of fields in the claims map.
func claimFields ( claims map [ string ] interface {}) [] string {
fields := [] string {}
for field := range claims {
fields = append ( fields , field )
}
sort . Strings ( fields )
return fields
}
// blankFields returns the list of fields in the claims map that are
// an empty string.
func blankFields ( claims map [ string ] interface {}) [] string {
fields := make ([] string , 0 )
for field , value := range claims {
if valueStr , ok := value .( string ); ok && valueStr == "" {
fields = append ( fields , field )
}
}
sort . Strings ( fields )
return fields
}
// mergeClaims merges the claims from a and b and returns the merged set.
// claims from b take precedence over claims from a.
func mergeClaims ( a , b map [ string ] interface {}) map [ string ] interface {} {
c := make ( map [ string ] interface {})
for k , v := range a {
c [ k ] = v
}
for k , v := range b {
c [ k ] = v
}
return c
}
2022-08-22 18:13:46 -05:00
type oauthLoginParams struct {
2023-02-06 15:12:50 -05:00
User database . User
Link database . UserLink
2022-08-22 18:13:46 -05:00
State httpmw . OAuth2State
LinkedID string
LoginType database . LoginType
// The following are necessary in order to
// create new users.
AllowSignups bool
Email string
Username string
2024-06-06 13:37:08 +01:00
Name string
2022-09-04 11:44:27 -05:00
AvatarURL string
2024-08-30 11:19:36 -05:00
// OrganizationSync has the organizations that the user will be assigned to.
OrganizationSync idpsync . OrganizationParams
2024-09-11 13:43:50 -05:00
GroupSync idpsync . GroupParams
2024-09-16 19:03:25 -05:00
RoleSync idpsync . RoleParams
2023-06-30 08:38:48 -04:00
2024-11-14 10:05:44 -06:00
// UserClaims should only be populated for OIDC logins.
// It is used to save the user's claims on login.
UserClaims database . UserLinkClaims
2023-11-27 10:47:23 -06:00
2023-06-30 08:38:48 -04:00
commitLock sync . Mutex
initAuditRequest func ( params * audit . RequestParams ) * audit . Request [ database . User ]
commits [] func ()
}
func ( p * oauthLoginParams ) SetInitAuditRequest ( f func ( params * audit . RequestParams ) ( * audit . Request [ database . User ], func ())) * oauthLoginParams {
p . initAuditRequest = func ( params * audit . RequestParams ) * audit . Request [ database . User ] {
p . commitLock . Lock ()
defer p . commitLock . Unlock ()
req , commit := f ( params )
p . commits = append ( p . commits , commit )
return req
}
return p
}
func ( p * oauthLoginParams ) CommitAuditLogs () {
p . commitLock . Lock ()
defer p . commitLock . Unlock ()
for _ , f := range p . commits {
f ()
}
2022-08-22 18:13:46 -05:00
}
2024-08-02 11:49:36 -05:00
func ( api * API ) oauthLogin ( r * http . Request , params * oauthLoginParams ) ([] * http . Cookie , database . User , database . APIKey , error ) {
2022-08-22 18:13:46 -05:00
var (
2024-10-31 17:55:42 -05:00
ctx = r . Context ()
user database . User
cookies [] * http . Cookie
logger = api . Logger . Named ( userAuthLoggerName )
auditor = * api . Auditor . Load ()
dormantConvertAudit * audit . Request [ database . User ]
initDormantAuditOnce = sync . OnceFunc ( func () {
dormantConvertAudit = params . initAuditRequest ( & audit . RequestParams {
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
OrganizationID : uuid . Nil ,
AdditionalFields : audit . BackgroundTaskFields ( audit . BackgroundSubsystemDormancy ),
})
})
2022-08-22 18:13:46 -05:00
)
2023-07-10 10:25:41 -04:00
var isConvertLoginType bool
2022-08-22 18:13:46 -05:00
err := api . Database . InTx ( func ( tx database . Store ) error {
var (
link database . UserLink
err error
)
2023-02-06 15:12:50 -05:00
user = params . User
link = params . Link
2022-08-22 18:13:46 -05:00
2023-06-30 08:38:48 -04:00
// If you do a convert to OIDC and your email does not match, we need to
// catch this and not make a new account.
if isMergeStateString ( params . State . StateString ) {
// Always clear this cookie. If it succeeds, we no longer need it.
// If it fails, we no longer care about it.
cookies = append ( cookies , clearOAuthConvertCookie ())
user , err = api . convertUserToOauth ( ctx , r , tx , params )
if err != nil {
return err
}
params . User = user
2023-07-10 10:25:41 -04:00
isConvertLoginType = true
2023-06-30 08:38:48 -04:00
}
2025-02-25 15:54:38 +01:00
// nolint:gocritic // Getting user count is a system function.
2025-03-25 14:18:06 +02:00
userCount , err := tx . GetUserCount ( dbauthz . AsSystemRestricted ( ctx ), false )
2025-02-25 15:54:38 +01:00
if err != nil {
return xerrors . Errorf ( "unable to fetch user count: %w" , err )
}
// Allow the first user to sign up with OIDC, regardless of
// whether signups are enabled or not.
allowSignup := userCount == 0 || params . AllowSignups
if user . ID == uuid . Nil && ! allowSignup {
2024-02-01 18:01:25 +01:00
signupsDisabledText := "Please contact your Coder administrator to request access."
if api . OIDCConfig != nil && api . OIDCConfig . SignupsDisabledText != "" {
2024-07-08 15:38:50 +02:00
signupsDisabledText = render . HTMLFromMarkdown ( api . OIDCConfig . SignupsDisabledText )
2024-02-01 18:01:25 +01:00
}
2024-08-30 11:19:36 -05:00
return & idpsync . HTTPError {
Code : http . StatusForbidden ,
Msg : "Signups are disabled" ,
Detail : signupsDisabledText ,
RenderStaticPage : true ,
RenderDetailMarkdown : true ,
2022-08-22 18:13:46 -05:00
}
}
if user . ID != uuid . Nil && user . LoginType != params . LoginType {
2023-07-07 11:33:31 -04:00
return wrongLoginTypeHTTPError ( user . LoginType , params . LoginType )
2022-08-22 18:13:46 -05:00
}
// This can happen if a user is a built-in user but is signing in
// with OIDC for the first time.
if user . ID == uuid . Nil {
2023-02-14 08:27:06 -06:00
//nolint:gocritic
2024-03-06 07:29:28 -06:00
_ , err = tx . GetUserByEmailOrUsername ( dbauthz . AsSystemRestricted ( ctx ), database . GetUserByEmailOrUsernameParams {
2022-10-17 22:07:11 -05:00
Username : params . Username ,
})
if err == nil {
var (
original = params . Username
validUsername bool
)
for i := 0 ; i < 10 ; i ++ {
2026-01-09 15:40:26 -07:00
alternate := fmt . Sprintf ( "%s-%s" , original , namesgenerator . NameDigitWith ( "_" ))
2022-10-17 22:07:11 -05:00
2024-09-04 18:17:53 +10:00
params . Username = codersdk . UsernameFrom ( alternate )
2022-10-17 22:07:11 -05:00
2023-02-14 08:27:06 -06:00
//nolint:gocritic
2023-02-15 16:14:37 +00:00
_ , err := tx . GetUserByEmailOrUsername ( dbauthz . AsSystemRestricted ( ctx ), database . GetUserByEmailOrUsernameParams {
2022-10-17 22:07:11 -05:00
Username : params . Username ,
})
if xerrors . Is ( err , sql . ErrNoRows ) {
validUsername = true
break
}
if err != nil {
return xerrors . Errorf ( "get user by email/username: %w" , err )
}
}
if ! validUsername {
2024-08-30 11:19:36 -05:00
return & idpsync . HTTPError {
Code : http . StatusConflict ,
Msg : fmt . Sprintf ( "exhausted alternatives for taken username %q" , original ),
2022-10-17 22:07:11 -05:00
}
}
}
2024-11-08 08:44:14 -06:00
//nolint:gocritic
defaultOrganization , err := tx . GetDefaultOrganization ( dbauthz . AsSystemRestricted ( ctx ))
if err != nil {
return xerrors . Errorf ( "unable to fetch default organization: %w" , err )
2024-08-30 11:19:36 -05:00
}
2025-02-25 15:54:38 +01:00
rbacRoles := [] string {}
// If this is the first user, add the owner role.
if userCount == 0 {
rbacRoles = append ( rbacRoles , rbac . RoleOwner (). String ())
}
2023-02-14 08:27:06 -06:00
//nolint:gocritic
2024-08-23 16:23:51 -05:00
user , err = api . CreateUser ( dbauthz . AsSystemRestricted ( ctx ), tx , CreateUserRequest {
CreateUserRequestWithOrgs : codersdk . CreateUserRequestWithOrgs {
2024-11-08 08:44:14 -06:00
Email : params . Email ,
Username : params . Username ,
// This is a kludge, but all users are defaulted into the default
// organization. This exists as the default behavior.
// If org sync is enabled and configured, the user's groups
// will change based on the org sync settings.
OrganizationIDs : [] uuid . UUID { defaultOrganization . ID },
2024-10-31 17:55:42 -05:00
UserStatus : ptr . Ref ( codersdk . UserStatusActive ),
2022-08-22 18:13:46 -05:00
},
2024-10-10 00:31:12 +02:00
LoginType : params . LoginType ,
accountCreatorName : "oauth" ,
2025-02-25 15:54:38 +01:00
RBACRoles : rbacRoles ,
2022-08-22 18:13:46 -05:00
})
if err != nil {
return xerrors . Errorf ( "create user: %w" , err )
}
2025-02-25 15:54:38 +01:00
if userCount == 0 {
telemetryUser := telemetry . ConvertUser ( user )
// The email is not anonymized for the first user.
telemetryUser . Email = & user . Email
api . Telemetry . Report ( & telemetry . Snapshot {
Users : [] telemetry . User { telemetryUser },
})
}
2022-08-22 18:13:46 -05:00
}
2024-10-10 00:31:12 +02:00
// Activate dormant user on sign-in
2023-08-02 16:31:25 +02:00
if user . Status == database . UserStatusDormant {
2024-10-31 17:55:42 -05:00
// This is necessary because transactions can be retried, and we
// only want to add the audit log a single time.
initDormantAuditOnce ()
dormantConvertAudit . UserID = user . ID
dormantConvertAudit . Old = user
2023-08-02 16:31:25 +02:00
//nolint:gocritic // System needs to update status of the user account (dormant -> active).
user , err = tx . UpdateUserStatus ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserStatusParams {
2025-12-17 16:49:40 +04:00
ID : user . ID ,
Status : database . UserStatusActive ,
UpdatedAt : dbtime . Now (),
UserIsSeen : true ,
2023-08-02 16:31:25 +02:00
})
if err != nil {
logger . Error ( ctx , "unable to update user status to active" , slog . Error ( err ))
return xerrors . Errorf ( "update user status: %w" , err )
}
2024-10-31 17:55:42 -05:00
dormantConvertAudit . New = user
2023-08-02 16:31:25 +02:00
}
2022-08-22 18:13:46 -05:00
if link . UserID == uuid . Nil {
2023-10-03 09:23:45 +01:00
//nolint:gocritic // System needs to insert the user link (linked_id, oauth_token, oauth_expiry).
2023-02-15 16:14:37 +00:00
link , err = tx . InsertUserLink ( dbauthz . AsSystemRestricted ( ctx ), database . InsertUserLinkParams {
2023-10-03 09:23:45 +01:00
UserID : user . ID ,
LoginType : params . LoginType ,
LinkedID : params . LinkedID ,
OAuthAccessToken : params . State . Token . AccessToken ,
OAuthAccessTokenKeyID : sql . NullString {}, // set by dbcrypt if required
OAuthRefreshToken : params . State . Token . RefreshToken ,
OAuthRefreshTokenKeyID : sql . NullString {}, // set by dbcrypt if required
OAuthExpiry : params . State . Token . Expiry ,
2024-11-14 10:05:44 -06:00
Claims : params . UserClaims ,
2022-08-22 18:13:46 -05:00
})
if err != nil {
return xerrors . Errorf ( "insert user link: %w" , err )
}
}
if link . UserID != uuid . Nil {
2023-10-03 09:23:45 +01:00
//nolint:gocritic // System needs to update the user link (linked_id, oauth_token, oauth_expiry).
2023-02-15 16:14:37 +00:00
link , err = tx . UpdateUserLink ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserLinkParams {
2023-10-03 09:23:45 +01:00
UserID : user . ID ,
LoginType : params . LoginType ,
OAuthAccessToken : params . State . Token . AccessToken ,
OAuthAccessTokenKeyID : sql . NullString {}, // set by dbcrypt if required
OAuthRefreshToken : params . State . Token . RefreshToken ,
OAuthRefreshTokenKeyID : sql . NullString {}, // set by dbcrypt if required
OAuthExpiry : params . State . Token . Expiry ,
2024-11-14 10:05:44 -06:00
Claims : params . UserClaims ,
2022-08-22 18:13:46 -05:00
})
if err != nil {
return xerrors . Errorf ( "update user link: %w" , err )
}
}
2024-08-30 11:19:36 -05:00
err = api . IDPSync . SyncOrganizations ( ctx , tx , user , params . OrganizationSync )
if err != nil {
return xerrors . Errorf ( "sync organizations: %w" , err )
}
2024-09-11 13:43:50 -05:00
// Group sync needs to occur after org sync, since a user can join an org,
// then have their groups sync to said org.
err = api . IDPSync . SyncGroups ( ctx , tx , user , params . GroupSync )
if err != nil {
return xerrors . Errorf ( "sync groups: %w" , err )
2023-02-02 13:53:48 -06:00
}
2024-09-16 19:03:25 -05:00
// Role sync needs to occur after org sync.
err = api . IDPSync . SyncRoles ( ctx , tx , user , params . RoleSync )
if err != nil {
return xerrors . Errorf ( "sync roles: %w" , err )
2023-07-24 08:34:24 -04:00
}
2022-09-04 11:44:27 -05:00
needsUpdate := false
2023-12-11 10:09:51 -07:00
if user . AvatarURL != params . AvatarURL {
user . AvatarURL = params . AvatarURL
2022-09-04 11:44:27 -05:00
needsUpdate = true
}
2024-06-06 13:37:08 +01:00
if user . Name != params . Name {
user . Name = params . Name
needsUpdate = true
}
2022-09-04 11:44:27 -05:00
2022-08-22 18:13:46 -05:00
// If the upstream email or username has changed we should mirror
// that in Coder. Many enterprises use a user's email/username as
// security auditing fields so they need to stay synced.
// NOTE: username updating has been halted since it can have infrastructure
// provisioning consequences (updates to usernames may delete persistent
// resources such as user home volumes).
if user . Email != params . Email {
2022-09-04 11:44:27 -05:00
user . Email = params . Email
needsUpdate = true
}
if needsUpdate {
2022-08-22 18:13:46 -05:00
// TODO(JonA): Since we're processing updates to a user's upstream
// email/username, it's possible for a different built-in user to
// have already claimed the username.
// In such cases in the current implementation this user can now no
// longer sign in until an administrator finds the offending built-in
// user and changes their username.
2023-02-14 08:27:06 -06:00
//nolint:gocritic
2023-02-15 16:14:37 +00:00
user , err = tx . UpdateUserProfile ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserProfileParams {
2022-08-22 18:13:46 -05:00
ID : user . ID ,
2022-09-04 11:44:27 -05:00
Email : user . Email ,
2024-01-17 13:20:45 +01:00
Name : user . Name ,
2022-08-22 18:13:46 -05:00
Username : user . Username ,
2023-09-01 19:50:12 +03:00
UpdatedAt : dbtime . Now (),
2022-09-04 11:44:27 -05:00
AvatarURL : user . AvatarURL ,
2022-08-22 18:13:46 -05:00
})
if err != nil {
return xerrors . Errorf ( "update user profile: %w" , err )
}
}
return nil
2022-11-14 11:57:33 -06:00
}, nil )
2022-08-22 18:13:46 -05:00
if err != nil {
2024-08-02 11:49:36 -05:00
return nil , database . User {}, database . APIKey {}, xerrors . Errorf ( "in tx: %w" , err )
2022-08-22 18:13:46 -05:00
}
2023-07-10 10:25:41 -04:00
var key database . APIKey
2023-08-08 10:05:12 -05:00
oldKey , _ , ok := httpmw . APIKeyFromRequest ( ctx , api . Database , nil , r )
if ok && oldKey != nil && isConvertLoginType {
2023-07-10 10:25:41 -04:00
// If this is a convert login type, and it succeeds, then delete the old
// session. Force the user to log back in.
err := api . Database . DeleteAPIKeyByID ( r . Context (), oldKey . ID )
if err != nil {
// Do not block this login if we fail to delete the old API key.
// Just delete the cookie and continue.
api . Logger . Warn ( r . Context (), "failed to delete old API key in convert to oidc" ,
slog . Error ( err ),
slog . F ( "old_api_key_id" , oldKey . ID ),
slog . F ( "user_id" , user . ID ),
)
}
2025-04-08 14:15:14 -05:00
cookies = append ( cookies , api . DeploymentValues . HTTPCookies . Apply ( & http . Cookie {
2023-07-10 10:25:41 -04:00
Name : codersdk . SessionTokenCookie ,
Path : "/" ,
MaxAge : - 1 ,
HttpOnly : true ,
2025-04-08 14:15:14 -05:00
}))
2023-08-08 10:05:12 -05:00
// This is intentional setting the key to the deleted old key,
// as the user needs to be forced to log back in.
key = * oldKey
2023-07-10 10:25:41 -04:00
} else {
//nolint:gocritic
cookie , newKey , err := api . createAPIKey ( dbauthz . AsSystemRestricted ( ctx ), apikey . CreateParams {
2024-01-22 11:42:55 -09:00
UserID : user . ID ,
LoginType : params . LoginType ,
2024-04-10 10:34:49 -05:00
DefaultLifetime : api . DeploymentValues . Sessions . DefaultDuration . Value (),
2024-01-22 11:42:55 -09:00
RemoteAddr : r . RemoteAddr ,
2023-07-10 10:25:41 -04:00
})
if err != nil {
2024-08-02 11:49:36 -05:00
return nil , database . User {}, database . APIKey {}, xerrors . Errorf ( "create API key: %w" , err )
2023-07-10 10:25:41 -04:00
}
cookies = append ( cookies , cookie )
key = * newKey
2022-08-22 18:13:46 -05:00
}
2024-08-02 11:49:36 -05:00
return cookies , user , key , nil
2023-06-30 08:38:48 -04:00
}
// convertUserToOauth will convert a user from password base loginType to
// an oauth login type. If it fails, it will return a httpError
func ( api * API ) convertUserToOauth ( ctx context . Context , r * http . Request , db database . Store , params * oauthLoginParams ) ( database . User , error ) {
user := params . User
// Trying to convert to OIDC, but the email does not match.
// So do not make a new user, just block the request.
if user . ID == uuid . Nil {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusBadRequest ,
Msg : fmt . Sprintf ( "The oidc account with the email %q does not match the email of the account you are trying to convert. Contact your administrator to resolve this issue." , params . Email ),
2023-06-30 08:38:48 -04:00
}
}
jwtCookie , err := r . Cookie ( OAuthConvertCookieValue )
if err != nil {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusBadRequest ,
Msg : fmt . Sprintf ( "Convert to oauth cookie not found. Missing signed jwt to authorize this action. " +
2023-06-30 08:38:48 -04:00
"Please try again." ),
}
}
var claims OAuthConvertStateClaims
2024-10-25 17:14:35 +01:00
err = jwtutils . Verify ( ctx , api . OIDCConvertKeyCache , jwtCookie . Value , & claims )
if xerrors . Is ( err , cryptokeys . ErrKeyNotFound ) || xerrors . Is ( err , cryptokeys . ErrKeyInvalid ) || xerrors . Is ( err , jose . ErrCryptoFailure ) || xerrors . Is ( err , jwtutils . ErrMissingKeyID ) {
2023-06-30 08:38:48 -04:00
// These errors are probably because the user is mixing 2 coder deployments.
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusBadRequest ,
Msg : "Using an invalid jwt to authorize this action. Ensure there is only 1 coder deployment and try again." ,
2023-06-30 08:38:48 -04:00
}
}
if err != nil {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusInternalServerError ,
Msg : fmt . Sprintf ( "Error parsing jwt: %v" , err ),
2023-06-30 08:38:48 -04:00
}
}
// At this point, this request could be an attempt to convert from
// password auth to oauth auth. Always log these attempts.
var (
auditor = * api . Auditor . Load ()
oauthConvertAudit = params . initAuditRequest ( & audit . RequestParams {
Audit : auditor ,
Log : api . Logger ,
Request : r ,
Action : database . AuditActionWrite ,
})
)
oauthConvertAudit . UserID = claims . UserID
oauthConvertAudit . Old = user
2024-10-25 17:14:35 +01:00
if claims . Issuer != api . DeploymentID {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusForbidden ,
Msg : "Request to convert login type failed. Issuer mismatch. Found a cookie from another coder deployment, please try again." ,
2023-06-30 08:38:48 -04:00
}
}
if params . State . StateString != claims . State {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusForbidden ,
Msg : "Request to convert login type failed. State mismatch." ,
2023-06-30 08:38:48 -04:00
}
}
// Make sure the merge state generated matches this OIDC login request.
// It needs to have the correct login type information for this
// user.
if user . ID != claims . UserID ||
codersdk . LoginType ( user . LoginType ) != claims . FromLoginType ||
codersdk . LoginType ( params . LoginType ) != claims . ToLoginType {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusForbidden ,
Msg : fmt . Sprintf ( "Request to convert login type from %s to %s failed" , user . LoginType , params . LoginType ),
2023-06-30 08:38:48 -04:00
}
}
// Convert the user and default to the normal login flow.
// If the login succeeds, this transaction will commit and the user
// will be converted.
// nolint:gocritic // system query to update user login type. The user already
// provided their password to authenticate this request.
user , err = db . UpdateUserLoginType ( dbauthz . AsSystemRestricted ( ctx ), database . UpdateUserLoginTypeParams {
NewLoginType : params . LoginType ,
UserID : user . ID ,
})
if err != nil {
2024-08-30 11:19:36 -05:00
return database . User {}, idpsync . HTTPError {
Code : http . StatusInternalServerError ,
Msg : "Failed to convert user to new login type" ,
2023-06-30 08:38:48 -04:00
}
}
oauthConvertAudit . New = user
return user , nil
2022-08-22 18:13:46 -05:00
}
2022-08-17 18:00:53 -05:00
// githubLinkedID returns the unique ID for a GitHub user.
func githubLinkedID ( u * github . User ) string {
return strconv . FormatInt ( u . GetID (), 10 )
}
// oidcLinkedID returns the uniqued ID for an OIDC user.
// See https://openid.net/specs/openid-connect-core-1_0.html#ClaimStability .
func oidcLinkedID ( tok * oidc . IDToken ) string {
return strings . Join ([] string { tok . Issuer , tok . Subject }, "||" )
}
// findLinkedUser tries to find a user by their unique OAuth-linked ID.
// If it doesn't not find it, it returns the user by their email.
func findLinkedUser ( ctx context . Context , db database . Store , linkedID string , emails ... string ) ( database . User , database . UserLink , error ) {
var (
user database . User
link database . UserLink
)
link , err := db . GetUserLinkByLinkedID ( ctx , linkedID )
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return user , link , xerrors . Errorf ( "get user auth by linked ID: %w" , err )
}
if err == nil {
user , err = db . GetUserByID ( ctx , link . UserID )
if err != nil {
return database . User {}, database . UserLink {}, xerrors . Errorf ( "get user by id: %w" , err )
}
2022-09-13 07:33:35 -05:00
if ! user . Deleted {
return user , link , nil
}
// If the user was deleted, act as if no account link exists.
user = database . User {}
2022-08-17 18:00:53 -05:00
}
for _ , email := range emails {
user , err = db . GetUserByEmailOrUsername ( ctx , database . GetUserByEmailOrUsernameParams {
Email : email ,
})
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return user , link , xerrors . Errorf ( "get user by email: %w" , err )
}
if errors . Is ( err , sql . ErrNoRows ) {
continue
}
break
}
if user . ID == uuid . Nil {
// No user found.
return database . User {}, database . UserLink {}, nil
}
// LEGACY: This is annoying but we have to search for the user_link
// again except this time we search by user_id and login_type. It's
// possible that a user_link exists without a populated 'linked_id'.
link , err = db . GetUserLinkByUserIDLoginType ( ctx , database . GetUserLinkByUserIDLoginTypeParams {
UserID : user . ID ,
LoginType : user . LoginType ,
})
if err != nil && ! errors . Is ( err , sql . ErrNoRows ) {
return database . User {}, database . UserLink {}, xerrors . Errorf ( "get user link by user id and login type: %w" , err )
}
return user , link , nil
}
2023-06-30 08:38:48 -04:00
func isMergeStateString ( state string ) bool {
return strings . HasPrefix ( state , mergeStateStringPrefix )
}
func clearOAuthConvertCookie () * http . Cookie {
return & http . Cookie {
Name : OAuthConvertCookieValue ,
Path : "/" ,
MaxAge : - 1 ,
}
}
2023-07-07 11:33:31 -04:00
2024-08-30 11:19:36 -05:00
func wrongLoginTypeHTTPError ( user database . LoginType , params database . LoginType ) idpsync . HTTPError {
2023-07-07 11:33:31 -04:00
addedMsg := ""
if user == database . LoginTypePassword {
2023-08-09 03:05:46 -07:00
addedMsg = " You can convert your account to use this login type by visiting your account settings."
2023-07-07 11:33:31 -04:00
}
2024-08-30 11:19:36 -05:00
return idpsync . HTTPError {
Code : http . StatusForbidden ,
RenderStaticPage : true ,
Msg : "Incorrect login type" ,
Detail : fmt . Sprintf ( "Attempting to use login type %q, but the user has the login type %q.%s" ,
2023-07-07 11:33:31 -04:00
params , user , addedMsg ),
}
}