token3.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mcclient
  15. import (
  16. "fmt"
  17. "math/rand"
  18. "strings"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/utils"
  23. api "yunion.io/x/onecloud/pkg/apis/identity"
  24. "yunion.io/x/onecloud/pkg/httperrors"
  25. )
  26. const REGION_ZONE_SEP = '-'
  27. type KeystoneEndpointV3 struct {
  28. // endpoint ID
  29. // example: 75f4e36100184a5a8a3e36cb0f12aa87
  30. Id string `json:"id"`
  31. // endpoint接口类型,目前定义了一下集中类型
  32. //
  33. // | interface | 说明 |
  34. // |-----------|--------------------------------------------------------|
  35. // | internal | 内部接口,访问服务时默认用inernal类型的接口 |
  36. // | public | 外部接口 |
  37. // | admin | 管理类型接口,deprecated |
  38. // | console | web控制台接口,指定显示在web控制台的外部服务的接口地址 |
  39. // | slave | 从节点接口,用于读取数据 |
  40. //
  41. Interface string `json:"interface"`
  42. // 区域名称
  43. Region string `json:"region"`
  44. // 区域ID
  45. RegionId string `json:"region_id"`
  46. // 接口URL
  47. Url string `json:"url"`
  48. // 接口名称
  49. Name string `json:"name"`
  50. }
  51. type KeystoneServiceV3 struct {
  52. // service ID
  53. Id string `json:"id,omitempty"`
  54. // service Name
  55. Name string `json:"name,omitempty"`
  56. // service Type,例如identity, compute等
  57. Type string `json:"type,omitempty"`
  58. // service的访问endpoints
  59. Endpoints []KeystoneEndpointV3 `json:"endpoints,omitempty"`
  60. }
  61. type KeystoneDomainV3 api.SIdentityObject
  62. type KeystoneRoleV3 api.SIdentityObject
  63. type KeystoneProjectV3 struct {
  64. // 项目ID
  65. Id string
  66. // 项目名称
  67. Name string
  68. // 项目归属域
  69. Domain KeystoneDomainV3
  70. }
  71. type KeystoneUserV3 struct {
  72. // 用户ID
  73. Id string
  74. // 用户名称
  75. Name string
  76. // 用户归属域
  77. Domain KeystoneDomainV3
  78. // 用户密码过期时间
  79. PasswordExpiresAt time.Time
  80. // 是否为系统账号
  81. IsSystemAccount bool
  82. // 用户的显式名称,通常为中文名
  83. Displayname string
  84. // 用户Email
  85. Email string
  86. // 用户手机号
  87. Mobile string
  88. }
  89. type KeystoneServiceCatalogV3 []KeystoneServiceV3
  90. type KeystonePolicy struct {
  91. // 项目范围的权限
  92. Project []string
  93. // 域范围的权限
  94. Domain []string
  95. // 系统范围的权限
  96. System []string
  97. }
  98. type KeystoneTokenV3 struct {
  99. // AutdiIds, 没有什么用
  100. // swagger:ignore
  101. AuditIds []string `json:"audit_ids"`
  102. // token过期时间
  103. ExpiresAt time.Time `json:"expires_at"`
  104. // 是否为域的token
  105. IsDomain bool `json:"is_domain,allowfalse"`
  106. // token颁发时间
  107. IssuedAt time.Time `json:"issued_at"`
  108. // 获取token的认证方式
  109. Methods []string `json:"methods"`
  110. // token的关联项目,如果用户认证时scope为项目,则为改指定项目的信息
  111. Project KeystoneProjectV3 `json:"project"`
  112. // token的关联用户在关联项目的权限信息,只有项目scope的token才有这个属性
  113. Policies KeystonePolicy `json:"policies"`
  114. // token的关联用户在关联项目的角色列表,只有项目scope的token才有这个属性
  115. Roles []KeystoneRoleV3 `json:"roles"`
  116. // token的关联用户信息
  117. User KeystoneUserV3 `json:"user"`
  118. // 服务目录
  119. Catalog KeystoneServiceCatalogV3 `json:"catalog"`
  120. // 认证上下文
  121. Context SAuthContext `json:"context"`
  122. // 当用户认证时未指定scope时,会返回该用户所有的项目
  123. Projects []KeystoneProjectV3 `json:"projects"`
  124. // 返回用户在所有项目的所有角色信息
  125. RoleAssignments []api.SRoleAssignment `json:"role_assignments"`
  126. // 如果时AK/SK认证,返回用户的AccessKey/Secret信息,用于客户端后续的AK/SK认证,避免频繁访问keystone进行AK/SK认证
  127. AccessKey api.SAccessKeySecretInfo `json:"access_key"`
  128. }
  129. type TokenCredentialV3 struct {
  130. // keystone V3 token
  131. Token KeystoneTokenV3 `json:"token"`
  132. // swagger:ignore
  133. Id string `json:"id"`
  134. }
  135. func (token *TokenCredentialV3) GetTokenString() string {
  136. return token.Id
  137. }
  138. func (token *TokenCredentialV3) GetDomainId() string {
  139. return token.Token.User.Domain.Id
  140. }
  141. func (token *TokenCredentialV3) GetDomainName() string {
  142. return token.Token.User.Domain.Name
  143. }
  144. func (token *TokenCredentialV3) GetProjectId() string {
  145. return token.Token.Project.Id
  146. }
  147. func (token *TokenCredentialV3) GetProjectName() string {
  148. return token.Token.Project.Name
  149. }
  150. func (token *TokenCredentialV3) GetTenantId() string {
  151. return token.Token.Project.Id
  152. }
  153. func (token *TokenCredentialV3) GetTenantName() string {
  154. return token.Token.Project.Name
  155. }
  156. func (token *TokenCredentialV3) GetProjectDomainId() string {
  157. return token.Token.Project.Domain.Id
  158. }
  159. func (token *TokenCredentialV3) GetProjectDomain() string {
  160. return token.Token.Project.Domain.Name
  161. }
  162. func (token *TokenCredentialV3) GetUserName() string {
  163. return token.Token.User.Name
  164. }
  165. func (token *TokenCredentialV3) GetUserId() string {
  166. return token.Token.User.Id
  167. }
  168. func (token *TokenCredentialV3) IsSystemAccount() bool {
  169. return token.Token.User.IsSystemAccount
  170. }
  171. func (token *TokenCredentialV3) GetRoles() []string {
  172. roles := make([]string, 0)
  173. for i := 0; i < len(token.Token.Roles); i++ {
  174. roles = append(roles, token.Token.Roles[i].Name)
  175. }
  176. return roles
  177. }
  178. func (token *TokenCredentialV3) GetRoleIds() []string {
  179. roles := make([]string, 0)
  180. for i := 0; i < len(token.Token.Roles); i++ {
  181. roles = append(roles, token.Token.Roles[i].Id)
  182. }
  183. return roles
  184. }
  185. func (this *TokenCredentialV3) GetExpires() time.Time {
  186. return this.Token.ExpiresAt
  187. }
  188. func (this *TokenCredentialV3) IsValid() bool {
  189. return len(this.Id) > 0 && this.ValidDuration() > 0
  190. }
  191. func (this *TokenCredentialV3) ValidDuration() time.Duration {
  192. return time.Until(this.Token.ExpiresAt)
  193. }
  194. func (this *TokenCredentialV3) IsAdmin() bool {
  195. for i := 0; i < len(this.Token.Roles); i++ {
  196. if this.Token.Roles[i].Name == "admin" {
  197. return true
  198. }
  199. }
  200. return false
  201. }
  202. func (this *TokenCredentialV3) HasSystemAdminPrivilege() bool {
  203. return this.IsAdmin() && this.GetTenantName() == "system"
  204. }
  205. /*func (this *TokenCredentialV3) IsAllow(scope rbacscope.TRbacScope, service string, resource string, action string, extra ...string) rbacutils.SPolicyResult {
  206. if this.isAllow(scope, service, resource, action, extra...) {
  207. return rbacutils.PolicyAllow
  208. } else {
  209. return rbacutils.PolicyDeny
  210. }
  211. }
  212. func (this *TokenCredentialV3) isAllow(scope rbacscope.TRbacScope, service string, resource string, action string, extra ...string) bool {
  213. if scope == rbacscope.ScopeSystem || scope == rbacscope.ScopeDomain {
  214. return this.HasSystemAdminPrivilege()
  215. } else {
  216. return true
  217. }
  218. }*/
  219. func (this *TokenCredentialV3) GetRegions() []string {
  220. return this.Token.Catalog.getRegions()
  221. }
  222. func (this *TokenCredentialV3) Len() int {
  223. return this.Token.Catalog.Len()
  224. }
  225. func (this *TokenCredentialV3) getServiceURL(service, region, zone, endpointType string) (string, error) {
  226. return this.Token.Catalog.getServiceURL(service, region, zone, endpointType)
  227. }
  228. func (this *TokenCredentialV3) getServiceURLs(service, region, zone, endpointType string) ([]string, error) {
  229. return this.Token.Catalog.getServiceURLs(service, region, zone, endpointType)
  230. }
  231. func (this *TokenCredentialV3) GetInternalServices(region string) []string {
  232. return this.Token.Catalog.GetInternalServices(region)
  233. }
  234. func (this *TokenCredentialV3) GetExternalServices(region string) []ExternalService {
  235. return this.Token.Catalog.GetExternalServices(region)
  236. }
  237. func (this *TokenCredentialV3) GetServicesByInterface(region string, infType string) []ExternalService {
  238. return this.Token.Catalog.GetServicesByInterface(region, infType)
  239. }
  240. func (this *TokenCredentialV3) GetEndpoints(region string, endpointType string) []Endpoint {
  241. return this.Token.Catalog.getEndpoints(region, endpointType)
  242. }
  243. func (this *TokenCredentialV3) GetServiceCatalog() IServiceCatalog {
  244. return this.Token.Catalog
  245. }
  246. func (this *TokenCredentialV3) GetLoginSource() string {
  247. return this.Token.Context.Source
  248. }
  249. func (this *TokenCredentialV3) GetLoginIp() string {
  250. return this.Token.Context.Ip
  251. }
  252. func (catalog KeystoneServiceCatalogV3) GetInternalServices(region string) []string {
  253. services := make([]string, 0)
  254. for i := 0; i < len(catalog); i++ {
  255. exit := false
  256. for j := 0; j < len(catalog[i].Endpoints); j++ {
  257. if catalog[i].Endpoints[j].RegionId == region &&
  258. catalog[i].Endpoints[j].Interface == "internal" {
  259. exit = true
  260. break
  261. }
  262. }
  263. if exit {
  264. services = append(services, catalog[i].Type)
  265. }
  266. }
  267. return services
  268. }
  269. func (catalog KeystoneServiceCatalogV3) GetExternalServices(region string) []ExternalService {
  270. return catalog.GetServicesByInterface(region, "console")
  271. }
  272. func (catalog KeystoneServiceCatalogV3) GetServicesByInterface(region string, infType string) []ExternalService {
  273. services := make([]ExternalService, 0)
  274. for i := 0; i < len(catalog); i++ {
  275. for j := 0; j < len(catalog[i].Endpoints); j++ {
  276. if catalog[i].Endpoints[j].RegionId == region &&
  277. catalog[i].Endpoints[j].Interface == infType &&
  278. len(catalog[i].Endpoints[j].Name) > 0 {
  279. srv := ExternalService{
  280. Name: catalog[i].Endpoints[j].Name,
  281. Url: catalog[i].Endpoints[j].Url,
  282. Service: catalog[i].Type,
  283. }
  284. services = append(services, srv)
  285. }
  286. }
  287. }
  288. return services
  289. }
  290. func (catalog KeystoneServiceCatalogV3) getRegions() []string {
  291. regions := make([]string, 0)
  292. for i := 0; i < len(catalog); i++ {
  293. for j := 0; j < len(catalog[i].Endpoints); j++ {
  294. if len(catalog[i].Endpoints[j].RegionId) > 0 && !stringArrayContains(regions, catalog[i].Endpoints[j].RegionId) {
  295. regions = append(regions, catalog[i].Endpoints[j].RegionId)
  296. }
  297. }
  298. }
  299. return regions
  300. }
  301. func (catalog KeystoneServiceCatalogV3) getEndpoints(region string, endpointType string) []Endpoint {
  302. endpoints := make([]Endpoint, 0)
  303. for i := 0; i < len(catalog); i++ {
  304. for j := 0; j < len(catalog[i].Endpoints); j++ {
  305. endpoint := catalog[i].Endpoints[j]
  306. if (endpoint.RegionId == region || strings.HasPrefix(endpoint.RegionId, region+"-")) && endpoint.Interface == endpointType {
  307. endpoints = append(endpoints, Endpoint{
  308. Id: endpoint.Id,
  309. RegionId: endpoint.RegionId,
  310. ServiceId: catalog[i].Id,
  311. ServiceName: catalog[i].Name,
  312. Url: endpoint.Url,
  313. Interface: endpoint.Interface,
  314. })
  315. }
  316. }
  317. }
  318. return endpoints
  319. }
  320. func RegionID(region, zone string) string {
  321. if len(region) > 0 && len(zone) > 0 {
  322. return fmt.Sprintf("%s%c%s", region, REGION_ZONE_SEP, zone)
  323. } else {
  324. return region
  325. }
  326. }
  327. func Id2RegionZone(id string) (string, string) {
  328. pos := strings.IndexByte(id, REGION_ZONE_SEP)
  329. if pos > 0 {
  330. return id[:pos], id[pos+1:]
  331. } else {
  332. return id, ""
  333. }
  334. }
  335. func (catalog KeystoneServiceCatalogV3) Len() int {
  336. return len(catalog)
  337. }
  338. func (catalog KeystoneServiceCatalogV3) getServiceURL(service, region, zone, endpointType string) (string, error) {
  339. urls, err := catalog.getServiceURLs(service, region, zone, endpointType)
  340. if err != nil {
  341. return "", err
  342. }
  343. return urls[rand.Intn(len(urls))], nil
  344. }
  345. func (catalog KeystoneServiceCatalogV3) getServiceURLs(service, region, zone, endpointType string) ([]string, error) {
  346. if endpointType == "" {
  347. endpointType = "internal"
  348. }
  349. const MAX_ENDPOINTS = 4
  350. for i := 0; i < len(catalog); i++ {
  351. if service == catalog[i].Type {
  352. if len(catalog[i].Endpoints) == 0 {
  353. continue
  354. }
  355. regeps := make(map[string][]string)
  356. regionzone := ""
  357. if len(zone) > 0 {
  358. regionzone = RegionID(region, zone)
  359. }
  360. for j := 0; j < len(catalog[i].Endpoints); j++ {
  361. ep := catalog[i].Endpoints[j]
  362. if strings.HasPrefix(endpointType, ep.Interface) &&
  363. (ep.RegionId == region ||
  364. ep.RegionId == regionzone ||
  365. len(region) == 0) {
  366. _, ok := regeps[ep.RegionId]
  367. if !ok {
  368. regeps[ep.RegionId] = make([]string, 0, MAX_ENDPOINTS)
  369. }
  370. regeps[ep.RegionId] = append(regeps[ep.RegionId], ep.Url)
  371. }
  372. }
  373. if len(region) == 0 {
  374. if len(regeps) >= 1 {
  375. for k := range regeps {
  376. return regeps[k], nil
  377. }
  378. } else {
  379. return nil, fmt.Errorf("No default region for region(%s) zone(%s)", region, zone)
  380. }
  381. } else {
  382. var selected []string
  383. _, ok := regeps[regionzone]
  384. if ok {
  385. selected = regeps[regionzone]
  386. } else if _, ok := regeps[region]; ok {
  387. selected = regeps[region]
  388. }
  389. if len(selected) == 0 {
  390. return nil, fmt.Errorf("No valid %s endpoints for %s in region %s", endpointType, service, RegionID(region, zone))
  391. } else {
  392. return selected, nil
  393. }
  394. }
  395. }
  396. }
  397. return nil, errors.Wrapf(httperrors.ErrNotFound, "No such service %s", service)
  398. }
  399. func (self *TokenCredentialV3) GetCatalogData(serviceTypes []string, region string) jsonutils.JSONObject {
  400. catalog := self.Token.Catalog
  401. ret := make([]map[string]interface{}, 0)
  402. for i := 0; i < len(catalog); i++ {
  403. if !utils.IsInStringArray(catalog[i].Type, serviceTypes) {
  404. continue
  405. }
  406. neps := make([]KeystoneEndpointV3, 0)
  407. for j := 0; j < len(catalog[i].Endpoints); j++ {
  408. if catalog[i].Endpoints[j].RegionId != region && catalog[i].Endpoints[j].Region != region {
  409. continue
  410. }
  411. neps = append(neps, catalog[i].Endpoints[j])
  412. }
  413. if len(neps) > 0 {
  414. data := map[string]interface{}{
  415. "type": catalog[i].Type,
  416. "endpoints": neps,
  417. }
  418. ret = append(ret, data)
  419. }
  420. }
  421. return jsonutils.Marshal(ret)
  422. }
  423. func (self *TokenCredentialV3) String() string {
  424. token := SimplifyToken(self)
  425. return token.String()
  426. }
  427. func (self *TokenCredentialV3) IsZero() bool {
  428. return len(self.GetUserId()) == 0 && len(self.GetProjectId()) == 0
  429. }
  430. func (self *TokenCredentialV3) ToJson() jsonutils.JSONObject {
  431. return SimplifyToken(self).ToJson()
  432. }