token2.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. api "yunion.io/x/onecloud/pkg/apis/identity"
  22. )
  23. type KeystoneEndpointV2 struct {
  24. // 接口ID
  25. Id string `json:"id"`
  26. // 内部URL
  27. InternalURL string `json:"internal_url"`
  28. // 外部URL
  29. PublicURL string `json:"public_url"`
  30. // 管理URL
  31. AdminURL string `json:"admin_url"`
  32. // 区域ID
  33. Region string `json:"region"`
  34. }
  35. type KeystoneServiceV2 struct {
  36. // 服务名称
  37. Name string `json:"name"`
  38. // 服务类型
  39. Type string `json:"type"`
  40. // 服务接口地址列表
  41. Endpoints []KeystoneEndpointV2 `json:"endpoints"`
  42. }
  43. type KeystoneRoleV2 struct {
  44. // 角色名称
  45. Name string `json:"name"`
  46. // 角色ID
  47. Id string `json:"id"`
  48. }
  49. type KeystoneUserV2 struct {
  50. // 用户ID
  51. Id string `json:"id"`
  52. // 用户名
  53. Name string `json:"name"`
  54. // 用户username
  55. Username string `json:"username"`
  56. IsSystemAccount bool `json:"is_system_account"`
  57. // 用户角色列表
  58. Roles []KeystoneRoleV2 `json:"roles"`
  59. }
  60. type KeystoneTenantV2 struct {
  61. // 项目ID
  62. Id string `json:"id"`
  63. // 项目名称
  64. Name string `json:"name"`
  65. // 是否启用
  66. Enabled bool `json:"enabled"`
  67. // 描述
  68. Description string `json:"description"`
  69. // 项目归属域信息
  70. Domain struct {
  71. // 域ID
  72. Id string `json:"id"`
  73. // 域名称
  74. Name string `json:"name"`
  75. } `json:"domain"`
  76. }
  77. type KeystoneTokenV2 struct {
  78. // token
  79. Id string `json:"id"`
  80. // 过期时间(UTC)
  81. Expires time.Time `json:"expires"`
  82. // token有效的项目信息
  83. Tenant KeystoneTenantV2 `json:"tenant"`
  84. }
  85. type KeystoneMetadataV2 struct {
  86. // 是否为管理员
  87. IsAdmin int `json:"is_admin"`
  88. // 角色
  89. Roles []string `json:"roles"`
  90. }
  91. type KeystoneServiceCatalogV2 []KeystoneServiceV2
  92. // Keystone token信息V2
  93. type TokenCredentialV2 struct {
  94. // token信息
  95. Token KeystoneTokenV2 `json:"token"`
  96. // 服务目录
  97. ServiceCatalog KeystoneServiceCatalogV2 `json:"service_catalog"`
  98. // 认证用户信息
  99. User KeystoneUserV2 `json:"user"`
  100. // 用户所属项目列表
  101. Tenants []KeystoneTenantV2 `json:"tenants"`
  102. // 认证元数据
  103. Metadata KeystoneMetadataV2 `json:"metadata"`
  104. // 认证上下文
  105. Context SAuthContext `json:"context"`
  106. }
  107. func (token *TokenCredentialV2) GetTokenString() string {
  108. return token.Token.Id
  109. }
  110. func (token *TokenCredentialV2) GetDomainId() string {
  111. return api.DEFAULT_DOMAIN_ID
  112. }
  113. func (token *TokenCredentialV2) GetDomainName() string {
  114. return api.DEFAULT_DOMAIN_NAME
  115. }
  116. func (token *TokenCredentialV2) GetTenantId() string {
  117. return token.Token.Tenant.Id
  118. }
  119. func (token *TokenCredentialV2) GetTenantName() string {
  120. return token.Token.Tenant.Name
  121. }
  122. func (token *TokenCredentialV2) GetProjectId() string {
  123. return token.GetTenantId()
  124. }
  125. func (token *TokenCredentialV2) GetProjectName() string {
  126. return token.GetTenantName()
  127. }
  128. func (token *TokenCredentialV2) GetProjectDomainId() string {
  129. return api.DEFAULT_DOMAIN_ID
  130. }
  131. func (token *TokenCredentialV2) GetProjectDomain() string {
  132. return api.DEFAULT_DOMAIN_NAME
  133. }
  134. func (token *TokenCredentialV2) GetUserName() string {
  135. return token.User.Username
  136. }
  137. func (token *TokenCredentialV2) GetUserId() string {
  138. return token.User.Id
  139. }
  140. func (token *TokenCredentialV2) IsSystemAccount() bool {
  141. return token.User.IsSystemAccount
  142. }
  143. func (token *TokenCredentialV2) GetRoles() []string {
  144. roles := make([]string, 0)
  145. for i := 0; i < len(token.User.Roles); i++ {
  146. roles = append(roles, token.User.Roles[i].Name)
  147. }
  148. return roles
  149. }
  150. func (token *TokenCredentialV2) GetRoleIds() []string {
  151. roles := make([]string, 0)
  152. for i := 0; i < len(token.User.Roles); i++ {
  153. roles = append(roles, token.User.Roles[i].Id)
  154. }
  155. return roles
  156. }
  157. func (this *TokenCredentialV2) GetExpires() time.Time {
  158. return this.Token.Expires
  159. }
  160. func (this *TokenCredentialV2) IsValid() bool {
  161. return this.ValidDuration() > 0
  162. }
  163. func (this *TokenCredentialV2) ValidDuration() time.Duration {
  164. return time.Until(this.Token.Expires)
  165. }
  166. func (this *TokenCredentialV2) IsAdmin() bool {
  167. for i := 0; i < len(this.User.Roles); i++ {
  168. if this.User.Roles[i].Name == "admin" {
  169. return true
  170. }
  171. }
  172. return false
  173. }
  174. func (this *TokenCredentialV2) GetRegions() []string {
  175. return this.ServiceCatalog.getRegions()
  176. }
  177. func (this *TokenCredentialV2) HasSystemAdminPrivilege() bool {
  178. return this.IsAdmin() && this.GetTenantName() == "system"
  179. }
  180. /*func (this *TokenCredentialV2) IsAllow(scope rbacscope.TRbacScope, service string, resource string, action string, extra ...string) rbacutils.SPolicyResult {
  181. if this.isAllow(scope, service, resource, action, extra...) {
  182. return rbacutils.PolicyAllow
  183. } else {
  184. return rbacutils.PolicyDeny
  185. }
  186. }
  187. func (this *TokenCredentialV2) isAllow(scope rbacscope.TRbacScope, service string, resource string, action string, extra ...string) bool {
  188. if scope == rbacscope.ScopeSystem || scope == rbacscope.ScopeDomain {
  189. return this.HasSystemAdminPrivilege()
  190. } else {
  191. return true
  192. }
  193. }*/
  194. func (this *TokenCredentialV2) Len() int {
  195. return this.ServiceCatalog.Len()
  196. }
  197. func (this *TokenCredentialV2) getServiceURL(service, region, zone, endpointType string) (string, error) {
  198. return this.ServiceCatalog.getServiceURL(service, region, zone, endpointType)
  199. }
  200. func (this *TokenCredentialV2) getServiceURLs(service, region, zone, endpointType string) ([]string, error) {
  201. return this.ServiceCatalog.getServiceURLs(service, region, zone, endpointType)
  202. }
  203. func (this *TokenCredentialV2) GetInternalServices(region string) []string {
  204. return nil
  205. }
  206. func (this *TokenCredentialV2) GetExternalServices(region string) []ExternalService {
  207. return nil
  208. }
  209. func (this *TokenCredentialV2) GetServicesByInterface(region string, infType string) []ExternalService {
  210. return nil
  211. }
  212. func (this *TokenCredentialV2) GetEndpoints(region string, endpointType string) []Endpoint {
  213. return nil
  214. }
  215. func (this *TokenCredentialV2) GetServiceCatalog() IServiceCatalog {
  216. return this.ServiceCatalog
  217. }
  218. func (this *TokenCredentialV2) GetLoginSource() string {
  219. return this.Context.Source
  220. }
  221. func (this *TokenCredentialV2) GetLoginIp() string {
  222. return this.Context.Ip
  223. }
  224. func stringArrayContains(arr []string, needle string) bool {
  225. for i := 0; i < len(arr); i++ {
  226. if arr[i] == needle {
  227. return true
  228. }
  229. }
  230. return false
  231. }
  232. func (catalog KeystoneServiceCatalogV2) getRegions() []string {
  233. regions := make([]string, 0)
  234. for i := 0; i < len(catalog); i++ {
  235. for j := 0; j < len(catalog[i].Endpoints); j++ {
  236. r := catalog[i].Endpoints[j].Region
  237. slash := strings.IndexByte(r, '/')
  238. if slash > 0 {
  239. r = r[:slash]
  240. }
  241. if !stringArrayContains(regions, r) {
  242. regions = append(regions, r)
  243. }
  244. }
  245. }
  246. return regions
  247. }
  248. func (catalog KeystoneServiceCatalogV2) getServiceEndpoint(service, region, zone string) (KeystoneEndpointV2, error) {
  249. var selected KeystoneEndpointV2
  250. var findService bool
  251. for i := 0; i < len(catalog); i++ {
  252. if service == catalog[i].Type {
  253. findService = true
  254. if len(catalog[i].Endpoints) == 0 {
  255. continue
  256. }
  257. if len(region) == 0 {
  258. selected = catalog[i].Endpoints[0]
  259. } else {
  260. regionEps := make([]KeystoneEndpointV2, 0)
  261. zoneEps := make([]KeystoneEndpointV2, 0)
  262. if len(zone) > 0 {
  263. zone = fmt.Sprintf("%s/%s", region, zone)
  264. }
  265. for j := 0; j < len(catalog[i].Endpoints); j++ {
  266. if catalog[i].Endpoints[j].Region == region {
  267. regionEps = append(regionEps, catalog[i].Endpoints[j])
  268. } else if len(zone) > 0 && catalog[i].Endpoints[j].Region == zone {
  269. zoneEps = append(zoneEps, catalog[i].Endpoints[j])
  270. }
  271. }
  272. if len(zone) > 0 && len(zoneEps) > 0 {
  273. selected = zoneEps[rand.Intn(len(zoneEps))]
  274. } else if len(regionEps) > 0 {
  275. selected = regionEps[rand.Intn(len(regionEps))]
  276. } else {
  277. return selected, fmt.Errorf("No such region %s", region)
  278. }
  279. }
  280. return selected, nil
  281. }
  282. }
  283. if findService {
  284. return selected, fmt.Errorf("No default region")
  285. } else {
  286. return selected, fmt.Errorf("No such service %s", service)
  287. }
  288. }
  289. func (catalog KeystoneServiceCatalogV2) Len() int {
  290. return len(catalog)
  291. }
  292. func (catalog KeystoneServiceCatalogV2) getServiceURL(service, region, zone, endpointType string) (string, error) {
  293. ep, err := catalog.getServiceEndpoint(service, region, zone)
  294. if err != nil {
  295. return "", err
  296. }
  297. return ep.getURL(endpointType), nil
  298. }
  299. func (catalog KeystoneServiceCatalogV2) getServiceURLs(service, region, zone, endpointType string) ([]string, error) {
  300. url, err := catalog.getServiceURL(service, region, zone, endpointType)
  301. if err != nil {
  302. return nil, err
  303. }
  304. return []string{url}, nil
  305. }
  306. func (catalog KeystoneServiceCatalogV2) GetInternalServices(region string) []string {
  307. return nil
  308. }
  309. func (catalog KeystoneServiceCatalogV2) GetExternalServices(region string) []ExternalService {
  310. return nil
  311. }
  312. func (catalog KeystoneServiceCatalogV2) GetServicesByInterface(region string, infType string) []ExternalService {
  313. return nil
  314. }
  315. func (ep KeystoneEndpointV2) getURL(epType string) string {
  316. switch epType {
  317. case "publicURL":
  318. return ep.PublicURL
  319. case "adminURL":
  320. return ep.AdminURL
  321. default:
  322. return ep.InternalURL
  323. }
  324. }
  325. func (self *TokenCredentialV2) GetCatalogData(serviceTypes []string, region string) jsonutils.JSONObject {
  326. return jsonutils.Marshal(self.GetServiceCatalog())
  327. }
  328. func (self *TokenCredentialV2) String() string {
  329. token := SimplifyToken(self)
  330. return token.String()
  331. }
  332. func (self *TokenCredentialV2) IsZero() bool {
  333. return len(self.GetUserId()) == 0 && len(self.GetProjectId()) == 0
  334. }
  335. func (self *TokenCredentialV2) ToJson() jsonutils.JSONObject {
  336. return SimplifyToken(self).ToJson()
  337. }