oauth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/coreos/go-oidc/v3/oidc"
  7. "github.com/gin-gonic/gin"
  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(c *gin.Context, 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. host := c.GetHeader("Origin")
  91. if host == "" {
  92. host = Config.Rustdesk.ApiServer
  93. }
  94. url = host + "/_admin/#/oauth/" + state
  95. //url = "http://localhost:8888/_admin/#/oauth/" + code
  96. return nil, state, verifier, nonce, url
  97. }
  98. err, oauthInfo, oauthConfig, _ := os.GetOauthConfig(c, op)
  99. if err == nil {
  100. extras := make([]oauth2.AuthCodeOption, 0, 3)
  101. nonce = utils.RandomString(10)
  102. extras = append(extras, oauth2.SetAuthURLParam("nonce", nonce))
  103. if oauthInfo.PkceEnable != nil && *oauthInfo.PkceEnable {
  104. extras = append(extras, oauth2.AccessTypeOffline)
  105. verifier = oauth2.GenerateVerifier()
  106. switch oauthInfo.PkceMethod {
  107. case model.PKCEMethodS256:
  108. extras = append(extras, oauth2.S256ChallengeOption(verifier))
  109. case model.PKCEMethodPlain:
  110. // oauth2 does not have a plain challenge option, so we add it manually
  111. extras = append(extras, oauth2.SetAuthURLParam("code_challenge_method", "plain"), oauth2.SetAuthURLParam("code_challenge", verifier))
  112. }
  113. }
  114. return err, state, verifier, nonce, oauthConfig.AuthCodeURL(state, extras...)
  115. }
  116. return err, state, verifier, nonce, ""
  117. }
  118. func (os *OauthService) FetchOidcProvider(issuer string) (error, *oidc.Provider) {
  119. // Get the HTTP client (with or without proxy based on configuration)
  120. client := getHTTPClientWithProxy()
  121. ctx := oidc.ClientContext(context.Background(), client)
  122. provider, err := oidc.NewProvider(ctx, issuer)
  123. if err != nil {
  124. return err, nil
  125. }
  126. return nil, provider
  127. }
  128. func (os *OauthService) GithubProvider() *oidc.Provider {
  129. return (&oidc.ProviderConfig{
  130. IssuerURL: "",
  131. AuthURL: github.Endpoint.AuthURL,
  132. TokenURL: github.Endpoint.TokenURL,
  133. DeviceAuthURL: github.Endpoint.DeviceAuthURL,
  134. UserInfoURL: model.UserEndpointGithub,
  135. JWKSURL: "",
  136. Algorithms: nil,
  137. }).NewProvider(context.Background())
  138. }
  139. func (os *OauthService) LinuxdoProvider() *oidc.Provider {
  140. return (&oidc.ProviderConfig{
  141. IssuerURL: "",
  142. AuthURL: "https://connect.linux.do/oauth2/authorize",
  143. TokenURL: "https://connect.linux.do/oauth2/token",
  144. DeviceAuthURL: "",
  145. UserInfoURL: model.UserEndpointLinuxdo,
  146. JWKSURL: "",
  147. Algorithms: nil,
  148. }).NewProvider(context.Background())
  149. }
  150. // GetOauthConfig retrieves the OAuth2 configuration based on the provider name
  151. func (os *OauthService) GetOauthConfig(c *gin.Context, op string) (err error, oauthInfo *model.Oauth, oauthConfig *oauth2.Config, provider *oidc.Provider) {
  152. //err, oauthInfo, oauthConfig = os.getOauthConfigGeneral(op)
  153. oauthInfo = os.InfoByOp(op)
  154. if oauthInfo.Id == 0 || oauthInfo.ClientId == "" || oauthInfo.ClientSecret == "" {
  155. return errors.New("ConfigNotFound"), nil, nil, nil
  156. }
  157. redirectUrl := os.buildRedirectURL(c)
  158. Logger.Debug("Redirect URL: ", redirectUrl)
  159. oauthConfig = &oauth2.Config{
  160. ClientID: oauthInfo.ClientId,
  161. ClientSecret: oauthInfo.ClientSecret,
  162. RedirectURL: redirectUrl,
  163. }
  164. // Maybe should validate the oauthConfig here
  165. oauthType := oauthInfo.OauthType
  166. err = model.ValidateOauthType(oauthType)
  167. if err != nil {
  168. return err, nil, nil, nil
  169. }
  170. switch oauthType {
  171. case model.OauthTypeGithub:
  172. oauthConfig.Endpoint = github.Endpoint
  173. oauthConfig.Scopes = []string{"read:user", "user:email"}
  174. provider = os.GithubProvider()
  175. case model.OauthTypeLinuxdo:
  176. provider = os.LinuxdoProvider()
  177. oauthConfig.Endpoint = provider.Endpoint()
  178. oauthConfig.Scopes = []string{"profile"}
  179. //case model.OauthTypeGoogle: //google单独出来,可以少一次FetchOidcEndpoint请求
  180. // oauthConfig.Endpoint = google.Endpoint
  181. // oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  182. case model.OauthTypeOidc, model.OauthTypeGoogle:
  183. err, provider = os.FetchOidcProvider(oauthInfo.Issuer)
  184. if err != nil {
  185. return err, nil, nil, nil
  186. }
  187. oauthConfig.Endpoint = provider.Endpoint()
  188. oauthConfig.Scopes = os.constructScopes(oauthInfo.Scopes)
  189. default:
  190. return errors.New("unsupported OAuth type"), nil, nil, nil
  191. }
  192. return nil, oauthInfo, oauthConfig, provider
  193. }
  194. func getHTTPClientWithProxy() *http.Client {
  195. //add timeout 30s
  196. timeout := time.Duration(60) * time.Second
  197. if Config.Proxy.Enable {
  198. if Config.Proxy.Host == "" {
  199. Logger.Warn("Proxy is enabled but proxy host is empty.")
  200. return http.DefaultClient
  201. }
  202. proxyURL, err := url.Parse(Config.Proxy.Host)
  203. if err != nil {
  204. Logger.Warn("Invalid proxy URL: ", err)
  205. return http.DefaultClient
  206. }
  207. transport := &http.Transport{
  208. Proxy: http.ProxyURL(proxyURL),
  209. }
  210. return &http.Client{Transport: transport, Timeout: timeout}
  211. }
  212. return http.DefaultClient
  213. }
  214. func (os *OauthService) callbackBase(oauthConfig *oauth2.Config, provider *oidc.Provider, code string, verifier string, nonce string, userData interface{}) (err error, client *http.Client) {
  215. // 设置代理客户端
  216. httpClient := getHTTPClientWithProxy()
  217. ctx := context.WithValue(context.Background(), oauth2.HTTPClient, httpClient)
  218. exchangeOpts := make([]oauth2.AuthCodeOption, 0, 1)
  219. if verifier != "" {
  220. exchangeOpts = append(exchangeOpts, oauth2.VerifierOption(verifier))
  221. }
  222. token, err := oauthConfig.Exchange(ctx, code, exchangeOpts...)
  223. if err != nil {
  224. Logger.Warn("oauthConfig.Exchange() failed: ", err)
  225. return errors.New("GetOauthTokenError"), nil
  226. }
  227. // 获取 ID Token, github没有id_token
  228. rawIDToken, ok := token.Extra("id_token").(string)
  229. if ok && rawIDToken != "" {
  230. // 验证 ID Token
  231. v := provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID})
  232. idToken, err2 := v.Verify(ctx, rawIDToken)
  233. if err2 != nil {
  234. Logger.Warn("IdTokenVerifyError: ", err2)
  235. return errors.New("IdTokenVerifyError"), nil
  236. }
  237. if nonce != "" {
  238. // 验证 nonce
  239. var claims struct {
  240. Nonce string `json:"nonce"`
  241. }
  242. if err2 = idToken.Claims(&claims); err2 != nil {
  243. Logger.Warn("Failed to parse ID Token claims: ", err)
  244. return errors.New("IDTokenClaimsError"), nil
  245. }
  246. if claims.Nonce != nonce {
  247. Logger.Warn("Nonce does not match")
  248. return errors.New("NonceDoesNotMatch"), nil
  249. }
  250. }
  251. }
  252. // 获取用户信息
  253. client = oauthConfig.Client(ctx, token)
  254. resp, err := client.Get(provider.UserInfoEndpoint())
  255. if err != nil {
  256. Logger.Warn("failed getting user info: ", err)
  257. return errors.New("GetOauthUserInfoError"), nil
  258. }
  259. defer func() {
  260. if closeErr := resp.Body.Close(); closeErr != nil {
  261. Logger.Warn("failed closing response body: ", closeErr)
  262. }
  263. }()
  264. // 解析用户信息
  265. if err = json.NewDecoder(resp.Body).Decode(userData); err != nil {
  266. Logger.Warn("failed decoding user info: ", err)
  267. return errors.New("DecodeOauthUserInfoError"), nil
  268. }
  269. return nil, client
  270. }
  271. // githubCallback github回调
  272. func (os *OauthService) githubCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  273. var user = &model.GithubUser{}
  274. err, client := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user)
  275. if err != nil {
  276. return err, nil
  277. }
  278. err = os.getGithubPrimaryEmail(client, user)
  279. if err != nil {
  280. return err, nil
  281. }
  282. return nil, user.ToOauthUser()
  283. }
  284. // linuxdoCallback linux.do回调
  285. func (os *OauthService) linuxdoCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  286. var user = &model.LinuxdoUser{}
  287. err, _ := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user)
  288. if err != nil {
  289. return err, nil
  290. }
  291. return nil, user.ToOauthUser()
  292. }
  293. // oidcCallback oidc回调, 通过code获取用户信息
  294. func (os *OauthService) oidcCallback(oauthConfig *oauth2.Config, provider *oidc.Provider, code, verifier, nonce string) (error, *model.OauthUser) {
  295. var user = &model.OidcUser{}
  296. if err, _ := os.callbackBase(oauthConfig, provider, code, verifier, nonce, user); err != nil {
  297. return err, nil
  298. }
  299. return nil, user.ToOauthUser()
  300. }
  301. // Callback: Get user information by code and op(Oauth provider)
  302. func (os *OauthService) Callback(c *gin.Context, code, verifier, op, nonce string) (err error, oauthUser *model.OauthUser) {
  303. err, oauthInfo, oauthConfig, provider := os.GetOauthConfig(c, op)
  304. // oauthType is already validated in GetOauthConfig
  305. if err != nil {
  306. return err, nil
  307. }
  308. oauthType := oauthInfo.OauthType
  309. switch oauthType {
  310. case model.OauthTypeGithub:
  311. err, oauthUser = os.githubCallback(oauthConfig, provider, code, verifier, nonce)
  312. case model.OauthTypeLinuxdo:
  313. err, oauthUser = os.linuxdoCallback(oauthConfig, provider, code, verifier, nonce)
  314. case model.OauthTypeOidc, model.OauthTypeGoogle:
  315. err, oauthUser = os.oidcCallback(oauthConfig, provider, code, verifier, nonce)
  316. default:
  317. return errors.New("unsupported OAuth type"), nil
  318. }
  319. return err, oauthUser
  320. }
  321. func (os *OauthService) UserThirdInfo(op string, openId string) *model.UserThird {
  322. ut := &model.UserThird{}
  323. DB.Where("open_id = ? and op = ?", openId, op).First(ut)
  324. return ut
  325. }
  326. // BindOauthUser: Bind third party account
  327. func (os *OauthService) BindOauthUser(userId uint, oauthUser *model.OauthUser, op string) error {
  328. utr := &model.UserThird{}
  329. err, oauthType := os.GetTypeByOp(op)
  330. if err != nil {
  331. return err
  332. }
  333. utr.FromOauthUser(userId, oauthUser, oauthType, op)
  334. return DB.Create(utr).Error
  335. }
  336. // UnBindOauthUser: Unbind third party account
  337. func (os *OauthService) UnBindOauthUser(userId uint, op string) error {
  338. return os.UnBindThird(op, userId)
  339. }
  340. // UnBindThird: Unbind third party account
  341. func (os *OauthService) UnBindThird(op string, userId uint) error {
  342. return DB.Where("user_id = ? and op = ?", userId, op).Delete(&model.UserThird{}).Error
  343. }
  344. // DeleteUserByUserId: When user is deleted, delete all third party bindings
  345. func (os *OauthService) DeleteUserByUserId(userId uint) error {
  346. return DB.Where("user_id = ?", userId).Delete(&model.UserThird{}).Error
  347. }
  348. // InfoById 根据id获取Oauth信息
  349. func (os *OauthService) InfoById(id uint) *model.Oauth {
  350. oauthInfo := &model.Oauth{}
  351. DB.Where("id = ?", id).First(oauthInfo)
  352. return oauthInfo
  353. }
  354. // InfoByOp 根据op获取Oauth信息
  355. func (os *OauthService) InfoByOp(op string) *model.Oauth {
  356. oauthInfo := &model.Oauth{}
  357. DB.Where("op = ?", op).First(oauthInfo)
  358. return oauthInfo
  359. }
  360. // Helper function to get scopes by operation
  361. func (os *OauthService) getScopesByOp(op string) []string {
  362. scopes := os.InfoByOp(op).Scopes
  363. return os.constructScopes(scopes)
  364. }
  365. // Helper function to construct scopes
  366. func (os *OauthService) constructScopes(scopes string) []string {
  367. scopes = strings.TrimSpace(scopes)
  368. if scopes == "" {
  369. scopes = model.OIDC_DEFAULT_SCOPES
  370. }
  371. return strings.Split(scopes, ",")
  372. }
  373. func (os *OauthService) List(page, pageSize uint, where func(tx *gorm.DB)) (res *model.OauthList) {
  374. res = &model.OauthList{}
  375. res.Page = int64(page)
  376. res.PageSize = int64(pageSize)
  377. tx := DB.Model(&model.Oauth{})
  378. if where != nil {
  379. where(tx)
  380. }
  381. tx.Count(&res.Total)
  382. tx.Scopes(Paginate(page, pageSize))
  383. tx.Find(&res.Oauths)
  384. return
  385. }
  386. // GetTypeByOp 根据op获取OauthType
  387. func (os *OauthService) GetTypeByOp(op string) (error, string) {
  388. oauthInfo := &model.Oauth{}
  389. if DB.Where("op = ?", op).First(oauthInfo).Error != nil {
  390. return fmt.Errorf("OAuth provider with op '%s' not found", op), ""
  391. }
  392. return nil, oauthInfo.OauthType
  393. }
  394. // ValidateOauthProvider 验证Oauth提供者是否正确
  395. func (os *OauthService) ValidateOauthProvider(op string) error {
  396. if !os.IsOauthProviderExist(op) {
  397. return fmt.Errorf("OAuth provider with op '%s' not found", op)
  398. }
  399. return nil
  400. }
  401. // IsOauthProviderExist 验证Oauth提供者是否存在
  402. func (os *OauthService) IsOauthProviderExist(op string) bool {
  403. oauthInfo := &model.Oauth{}
  404. // 使用 Gorm 的 Take 方法查找符合条件的记录
  405. if err := DB.Where("op = ?", op).Take(oauthInfo).Error; err != nil {
  406. return false
  407. }
  408. return true
  409. }
  410. // Create 创建
  411. func (os *OauthService) Create(oauthInfo *model.Oauth) error {
  412. err := oauthInfo.FormatOauthInfo()
  413. if err != nil {
  414. return err
  415. }
  416. res := DB.Create(oauthInfo).Error
  417. return res
  418. }
  419. func (os *OauthService) Delete(oauthInfo *model.Oauth) error {
  420. return DB.Delete(oauthInfo).Error
  421. }
  422. // Update 更新
  423. func (os *OauthService) Update(oauthInfo *model.Oauth) error {
  424. err := oauthInfo.FormatOauthInfo()
  425. if err != nil {
  426. return err
  427. }
  428. return DB.Model(oauthInfo).Updates(oauthInfo).Error
  429. }
  430. // GetOauthProviders 获取所有的provider
  431. func (os *OauthService) GetOauthProviders() []string {
  432. var res []string
  433. DB.Model(&model.Oauth{}).Pluck("op", &res)
  434. return res
  435. }
  436. // getGithubPrimaryEmail: Get the primary email of the user from Github
  437. func (os *OauthService) getGithubPrimaryEmail(client *http.Client, githubUser *model.GithubUser) error {
  438. // the client is already set with the token
  439. resp, err := client.Get("https://api.github.com/user/emails")
  440. if err != nil {
  441. return fmt.Errorf("failed to fetch emails: %w", err)
  442. }
  443. defer resp.Body.Close()
  444. // check the response status code
  445. if resp.StatusCode != http.StatusOK {
  446. return fmt.Errorf("failed to fetch emails: %s", resp.Status)
  447. }
  448. // decode the response
  449. var emails []struct {
  450. Email string `json:"email"`
  451. Primary bool `json:"primary"`
  452. Verified bool `json:"verified"`
  453. }
  454. if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
  455. return fmt.Errorf("failed to decode response: %w", err)
  456. }
  457. // find the primary verified email
  458. for _, e := range emails {
  459. if e.Primary && e.Verified {
  460. githubUser.Email = e.Email
  461. githubUser.VerifiedEmail = e.Verified
  462. return nil
  463. }
  464. }
  465. return fmt.Errorf("no primary verified email found")
  466. }
  467. func (os *OauthService) buildRedirectURL(c *gin.Context) string {
  468. baseUrl := Config.Rustdesk.ApiServer
  469. host := c.Request.Host
  470. if host != "" {
  471. scheme := c.GetHeader("X-Forwarded-Proto")
  472. if scheme == "" {
  473. if c.Request.TLS != nil {
  474. scheme = "https"
  475. } else {
  476. scheme = "http"
  477. }
  478. }
  479. baseUrl = fmt.Sprintf("%s://%s", scheme, host)
  480. }
  481. return fmt.Sprintf("%s/api/oidc/callback", baseUrl)
  482. }