oauth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/coreos/go-oidc/v3/oidc"
  7. "github.com/lejianwen/rustdesk-api/v2/global"
  8. "github.com/lejianwen/rustdesk-api/v2/model"
  9. "github.com/lejianwen/rustdesk-api/v2/utils"
  10. "golang.org/x/oauth2"
  11. "golang.org/x/oauth2/github"
  12. // "golang.org/x/oauth2/google"
  13. "gorm.io/gorm"
  14. // "io"
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. )
  23. type OauthService struct {
  24. }
  25. // Define a struct to parse the .well-known/openid-configuration response
  26. type OidcEndpoint struct {
  27. Issuer string `json:"issuer"`
  28. AuthURL string `json:"authorization_endpoint"`
  29. TokenURL string `json:"token_endpoint"`
  30. UserInfo string `json:"userinfo_endpoint"`
  31. }
  32. type OauthCacheItem struct {
  33. UserId uint `json:"user_id"`
  34. Id string `json:"id"` //rustdesk的设备ID
  35. Op string `json:"op"`
  36. Action string `json:"action"`
  37. Uuid string `json:"uuid"`
  38. DeviceName string `json:"device_name"`
  39. DeviceOs string `json:"device_os"`
  40. DeviceType string `json:"device_type"`
  41. OpenId string `json:"open_id"`
  42. Username string `json:"username"`
  43. Name string `json:"name"`
  44. Email string `json:"email"`
  45. Verifier string `json:"verifier"` // used for oauth pkce
  46. Nonce string `json:"nonce"`
  47. }
  48. func (oci *OauthCacheItem) ToOauthUser() *model.OauthUser {
  49. return &model.OauthUser{
  50. OpenId: oci.OpenId,
  51. Username: oci.Username,
  52. Name: oci.Name,
  53. Email: oci.Email,
  54. }
  55. }
  56. var OauthCache = &sync.Map{}
  57. const (
  58. OauthActionTypeLogin = "login"
  59. OauthActionTypeBind = "bind"
  60. )
  61. func (oci *OauthCacheItem) UpdateFromOauthUser(oauthUser *model.OauthUser) {
  62. oci.OpenId = oauthUser.OpenId
  63. oci.Username = oauthUser.Username
  64. oci.Name = oauthUser.Name
  65. oci.Email = oauthUser.Email
  66. }
  67. func (os *OauthService) GetOauthCache(key string) *OauthCacheItem {
  68. v, ok := OauthCache.Load(key)
  69. if !ok {
  70. return nil
  71. }
  72. return v.(*OauthCacheItem)
  73. }
  74. func (os *OauthService) SetOauthCache(key string, item *OauthCacheItem, expire uint) {
  75. OauthCache.Store(key, item)
  76. if expire > 0 {
  77. time.AfterFunc(time.Duration(expire)*time.Second, func() {
  78. os.DeleteOauthCache(key)
  79. })
  80. }
  81. }
  82. func (os *OauthService) DeleteOauthCache(key string) {
  83. OauthCache.Delete(key)
  84. }
  85. func (os *OauthService) BeginAuth(op string) (error error, state, verifier, nonce, url string) {
  86. state = utils.RandomString(10) + strconv.FormatInt(time.Now().Unix(), 10)
  87. verifier = ""
  88. nonce = ""
  89. if op == model.OauthTypeWebauth {
  90. url = global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/" + state
  91. //url = "http://localhost:8888/_admin/#/oauth/" + code
  92. return nil, state, verifier, nonce, url
  93. }
  94. err, oauthInfo, oauthConfig, _ := os.GetOauthConfig(op)
  95. if err == nil {
  96. extras := make([]oauth2.AuthCodeOption, 0, 3)
  97. nonce = utils.RandomString(10)
  98. extras = append(extras, oauth2.SetAuthURLParam("nonce", nonce))
  99. if oauthInfo.PkceEnable != nil && *oauthInfo.PkceEnable {
  100. extras = append(extras, oauth2.AccessTypeOffline)
  101. verifier = oauth2.GenerateVerifier()
  102. switch oauthInfo.PkceMethod {
  103. case model.PKCEMethodS256:
  104. extras = append(extras, oauth2.S256ChallengeOption(verifier))
  105. case model.PKCEMethodPlain:
  106. // oauth2 does not have a plain challenge option, so we add it manually
  107. extras = append(extras, oauth2.SetAuthURLParam("code_challenge_method", "plain"), oauth2.SetAuthURLParam("code_challenge", verifier))
  108. }
  109. }
  110. return err, state, verifier, nonce, oauthConfig.AuthCodeURL(state, extras...)
  111. }
  112. return err, state, verifier, nonce, ""
  113. }
  114. func (os *OauthService) FetchOidcProvider(issuer string) (error, *oidc.Provider) {
  115. // Get the HTTP client (with or without proxy based on configuration)
  116. client := getHTTPClientWithProxy()
  117. ctx := oidc.ClientContext(context.Background(), client)
  118. provider, err := oidc.NewProvider(ctx, issuer)
  119. if err != nil {
  120. return err, nil
  121. }
  122. return nil, provider
  123. }
  124. func (os *OauthService) GithubProvider() *oidc.Provider {
  125. return (&oidc.ProviderConfig{
  126. IssuerURL: "",
  127. AuthURL: github.Endpoint.AuthURL,
  128. TokenURL: github.Endpoint.TokenURL,
  129. DeviceAuthURL: github.Endpoint.DeviceAuthURL,
  130. UserInfoURL: model.UserEndpointGithub,
  131. JWKSURL: "",
  132. Algorithms: nil,
  133. }).NewProvider(context.Background())
  134. }
  135. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  136. func (os *OauthService) GetOauthConfig(op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config, provider *oidc.Provider) {
  137. //err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
  138. oauthInfo = os.InfoByOp(op)
  139. if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
  140. return errors.New("ConfigNotFound"), nil, nil, nil
  141. }
  142. // If the redirect URL is empty, use the default redirect URL
  143. if oauthInfo.RedirectUrl == "" {
  144. oauthInfo.RedirectUrl = global.Config.Rustdesk.ApiServer + "/api/oidc/callback"
  145. }
  146. oauthConfig = &oauth2.Config{
  147. ClientID: oauthInfo.ClientId,
  148. ClientSecret: oauthInfo.ClientSecret,
  149. RedirectURL: oauthInfo.RedirectUrl,
  150. }
  151. // Maybe should validate the oauthConfig here
  152. oauthType := oauthInfo.OauthType
  153. err = model.ValidateOauthType(oauthType)
  154. if err != nil {
  155. return err, nil, nil, nil
  156. }
  157. switch oauthType {
  158. case model.OauthTypeGithub:
  159. oauthConfig.Endpoint = github.Endpoint
  160. oauthConfig.Scopes = []string{"read:user", "user:email"}
  161. provider = os.GithubProvider()
  162. //case model.OauthTypeGoogle: //google单独出来,可以少一次FetchOidcEndpoint请求
  163. // oauthConfig.Endpoint = google.Endpoint
  164. // oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  165. case model.OauthTypeOidc, model.OauthTypeGoogle:
  166. err, provider = os.FetchOidcProvider(oauthInfo.Issuer)
  167. if err != nil {
  168. return err, nil, nil, nil
  169. }
  170. oauthConfig.Endpoint = provider.Endpoint()
  171. oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  172. default:
  173. return errors.New("unsupported OAuth type"), nil, nil, nil
  174. }
  175. return nil, oauthInfo, oauthConfig, provider
  176. }
  177. func getHTTPClientWithProxy() *http.Client {
  178. //add timeout 30s
  179. timeout := time.Duration(60) * time.Second
  180. if global.Config.Proxy.Enable {
  181. if global.Config.Proxy.Host == "" {
  182. global.Logger.Warn("Proxy is enabled but proxy host is empty.")
  183. return http.DefaultClient
  184. }
  185. proxyURL, err := url.Parse(global.Config.Proxy.Host)
  186. if err != nil {
  187. global.Logger.Warn("Invalid proxy URL: ", err)
  188. return http.DefaultClient
  189. }
  190. transport := &http.Transport{
  191. Proxy: http.ProxyURL(proxyURL),
  192. }
  193. return &http.Client{Transport: transport, Timeout: timeout}
  194. }
  195. return http.DefaultClient
  196. }
  197. func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.Provider, code string, verifier string, nonce string, userData interface{}) (err error, client *http.Client) {
  198. // 设置代理客户端
  199. httpClient := getHTTPClientWithProxy()
  200. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  201. exchangeOpts := make([]oauth2.AuthCodeOption, 0, 1)
  202. if verifier != "" {
  203. exchangeOpts = append(exchangeOpts, oauth2.VerifierOption(verifier))
  204. }
  205. token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
  206. if err != nil {
  207. global.Logger.Warn("oauthConfig.Exchange() failed: ", err)
  208. return errors.New("GetOauthTokenError"), nil
  209. }
  210. // 获取 ID Token, github没有id_token
  211. rawIDToken, ok := token.Extra("id_token").(string)
  212. if ok && rawIDToken != "" {
  213. // 验证 ID Token
  214. v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
  215. idToken, err2 := v.Verify(ctx, rawIDToken)
  216. if err2 != nil {
  217. global.Logger.Warn("IdTokenVerifyError: ", err2)
  218. return errors.New("IdTokenVerifyError"), nil
  219. }
  220. if nonce != "" {
  221. // 验证 nonce
  222. var claims struct {
  223. Nonce string `json:"nonce"`
  224. }
  225. if err2 = idToken.Claims(&claims); err2 != nil {
  226. global.Logger.Warn("Failed to parse ID Token claims: ", err)
  227. return errors.New("IDTokenClaimsError"), nil
  228. }
  229. if claims.Nonce != nonce {
  230. global.Logger.Warn("Nonce does not match")
  231. return errors.New("NonceDoesNotMatch"), nil
  232. }
  233. }
  234. }
  235. // 获取用户信息
  236. client = oauthConfig.Client(ctx, token)
  237. resp, err := client.Get(provider.UserInfoEndpoint())
  238. if err != nil {
  239. global.Logger.Warn("failed getting user info: ", err)
  240. return errors.New("GetOauthUserInfoError"), nil
  241. }
  242. defer func() {
  243. if closeErr := resp.Body.Close(); closeErr != nil {
  244. global.Logger.Warn("failed closing response body: ", closeErr)
  245. }
  246. }()
  247. // 解析用户信息
  248. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  249. global.Logger.Warn("failed decoding user info: ", err)
  250. return errors.New("DecodeOauthUserInfoError"), nil
  251. }
  252. return nil, client
  253. }
  254. // githubCallback github回调
  255. func (os *OauthService) githubCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  256. var user = &model.GithubUser{}
  257. err, client := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user)
  258. if err != nil {
  259. return err, nil
  260. }
  261. err = os.getGithubPrimaryEmail(client, user)
  262. if err != nil {
  263. return err, nil
  264. }
  265. return nil, user.ToOauthUser()
  266. }
  267. // oidcCallback oidc回调, 通过code获取用户信息
  268. func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  269. var user = &model.OidcUser{}
  270. if err, _ := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user); err != nil {
  271. return err, nil
  272. }
  273. return nil, user.ToOauthUser()
  274. }
  275. // Callback: Get user information by code and op(Oauth provider)
  276. func (os *OauthService) Callback(code, verifier, op, nonce string) (err error, oauthUser *model.OauthUser) {
  277. err, oauthInfo, oauthConfig, provider := os.GetOauthConfig(op)
  278. // oauthType is already validated in GetOauthConfig
  279. if err != nil {
  280. return err, nil
  281. }
  282. oauthType := oauthInfo.OauthType
  283. switch oauthType {
  284. case model.OauthTypeGithub:
  285. err, oauthUser = os.githubCallback(oauthConfig, provider, code, verifier, nonce)
  286. case model.OauthTypeOidc, model.OauthTypeGoogle:
  287. err, oauthUser = os.oidcCallback(oauthConfig, provider, code, verifier, nonce)
  288. default:
  289. return errors.New("unsupported OAuth type"), nil
  290. }
  291. return err, oauthUser
  292. }
  293. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  294. ut := &model.UserThird{}
  295. global.DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  296. return ut
  297. }
  298. // BindOauthUser: Bind third party account
  299. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  300. utr := &model.UserThird{}
  301. err, oauthType := os.GetTypeByOp(op)
  302. if err != nil {
  303. return err
  304. }
  305. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  306. return global.DB.Create(utr).Error
  307. }
  308. // UnBindOauthUser: Unbind third party account
  309. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  310. return os.UnBindThird(op, userId)
  311. }
  312. // UnBindThird: Unbind third party account
  313. func (os *OauthService) UnBindThird(op string, userId uint) error {
  314. return global.DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  315. }
  316. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  317. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  318. return global.DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  319. }
  320. // InfoById 根据id获取Oauth信息
  321. func (os *OauthService) InfoById(id uint) *model.Oauth {
  322. oauthInfo := &model.Oauth{}
  323. global.DB.Where("id = ?", id).First(oauthInfo)
  324. return oauthInfo
  325. }
  326. // InfoByOp 根据op获取Oauth信息
  327. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  328. oauthInfo := &model.Oauth{}
  329. global.DB.Where("op = ?", op).First(oauthInfo)
  330. return oauthInfo
  331. }
  332. // Helper function to get scopes by operation
  333. func (os *OauthService) getScopesByOp(op string) []string {
  334. scopes := os.InfoByOp(op).Scopes
  335. return os.constructScopes(scopes)
  336. }
  337. // Helper function to construct scopes
  338. func (os *OauthService) constructScopes(scopes string) []string {
  339. scopes = strings.TrimSpace(scopes)
  340. if scopes == "" {
  341. scopes = model.OIDC_DEFAULT_SCOPES
  342. }
  343. return strings.Split(scopes, ",")
  344. }
  345. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  346. res = &model.OauthList{}
  347. res.Page = int64(page)
  348. res.PageSize = int64(pageSize)
  349. tx := global.DB.Model(&model.Oauth{})
  350. if where != nil {
  351. where(tx)
  352. }
  353. tx.Count(&res.Total)
  354. tx.Scopes(Paginate(page, pageSize))
  355. tx.Find(&res.Oauths)
  356. return
  357. }
  358. // GetTypeByOp 根据op获取OauthType
  359. func (os *OauthService) GetTypeByOp(op string) (error, string) {
  360. oauthInfo := &model.Oauth{}
  361. if global.DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  362. return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
  363. }
  364. return nil, oauthInfo.OauthType
  365. }
  366. // ValidateOauthProvider 验证Oauth提供者是否正确
  367. func (os *OauthService) ValidateOauthProvider(op string) error {
  368. if !os.IsOauthProviderExist(op) {
  369. return fmt.Errorf("OAuth provider with op '%s' not found", op)
  370. }
  371. return nil
  372. }
  373. // IsOauthProviderExist 验证Oauth提供者是否存在
  374. func (os *OauthService) IsOauthProviderExist(op string) bool {
  375. oauthInfo := &model.Oauth{}
  376. // 使用 Gorm 的 Take 方法查找符合条件的记录
  377. if err := global.DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  378. return false
  379. }
  380. return true
  381. }
  382. // Create 创建
  383. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  384. err := oauthInfo.FormatOauthInfo()
  385. if err != nil {
  386. return err
  387. }
  388. res := global.DB.Create(oauthInfo).Error
  389. return res
  390. }
  391. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  392. return global.DB.Delete(oauthInfo).Error
  393. }
  394. // Update 更新
  395. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  396. err := oauthInfo.FormatOauthInfo()
  397. if err != nil {
  398. return err
  399. }
  400. return global.DB.Model(oauthInfo).Updates(oauthInfo).Error
  401. }
  402. // GetOauthProviders 获取所有的provider
  403. func (os *OauthService) GetOauthProviders() []string {
  404. var res []string
  405. global.DB.Model(&model.Oauth{}).Pluck("op", &res)
  406. return res
  407. }
  408. // getGithubPrimaryEmail: Get the primary email of the user from Github
  409. func (os *OauthService) getGithubPrimaryEmail(client *http.Client, githubUser *model.GithubUser) error {
  410. // the client is already set with the token
  411. resp, err := client.Get("https://api.github.com/user/emails")
  412. if err != nil {
  413. return fmt.Errorf("failed to fetch emails: %w", err)
  414. }
  415. defer resp.Body.Close()
  416. // check the response status code
  417. if resp.StatusCode != http.StatusOK {
  418. return fmt.Errorf("failed to fetch emails: %s", resp.Status)
  419. }
  420. // decode the response
  421. var emails []struct {
  422. Email string `json:"email"`
  423. Primary bool `json:"primary"`
  424. Verified bool `json:"verified"`
  425. }
  426. if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
  427. return fmt.Errorf("failed to decode response: %w", err)
  428. }
  429. // find the primary verified email
  430. for _, e := range emails {
  431. if e.Primary && e.Verified {
  432. githubUser.Email = e.Email
  433. githubUser.VerifiedEmail = e.Verified
  434. return nil
  435. }
  436. }
  437. return fmt.Errorf("no primary verified email found")
  438. }