oauth.go 15 KB

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