auth_user.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 2015 The etcd Authors
  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 client
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "net/http"
  20. "net/url"
  21. "path"
  22. )
  23. var (
  24. defaultV2AuthPrefix = "/v2/auth"
  25. )
  26. type User struct {
  27. User string `json:"user"`
  28. Password string `json:"password,omitempty"`
  29. Roles []string `json:"roles"`
  30. Grant []string `json:"grant,omitempty"`
  31. Revoke []string `json:"revoke,omitempty"`
  32. }
  33. // userListEntry is the user representation given by the server for ListUsers
  34. type userListEntry struct {
  35. User string `json:"user"`
  36. Roles []Role `json:"roles"`
  37. }
  38. type UserRoles struct {
  39. User string `json:"user"`
  40. Roles []Role `json:"roles"`
  41. }
  42. func v2AuthURL(ep url.URL, action string, name string) *url.URL {
  43. if name != "" {
  44. ep.Path = path.Join(ep.Path, defaultV2AuthPrefix, action, name)
  45. return &ep
  46. }
  47. ep.Path = path.Join(ep.Path, defaultV2AuthPrefix, action)
  48. return &ep
  49. }
  50. // NewAuthAPI constructs a new AuthAPI that uses HTTP to
  51. // interact with etcd's general auth features.
  52. func NewAuthAPI(c Client) AuthAPI {
  53. return &httpAuthAPI{
  54. client: c,
  55. }
  56. }
  57. type AuthAPI interface {
  58. // Enable auth.
  59. Enable(ctx context.Context) error
  60. // Disable auth.
  61. Disable(ctx context.Context) error
  62. }
  63. type httpAuthAPI struct {
  64. client httpClient
  65. }
  66. func (s *httpAuthAPI) Enable(ctx context.Context) error {
  67. return s.enableDisable(ctx, &authAPIAction{"PUT"})
  68. }
  69. func (s *httpAuthAPI) Disable(ctx context.Context) error {
  70. return s.enableDisable(ctx, &authAPIAction{"DELETE"})
  71. }
  72. func (s *httpAuthAPI) enableDisable(ctx context.Context, req httpAction) error {
  73. resp, body, err := s.client.Do(ctx, req)
  74. if err != nil {
  75. return err
  76. }
  77. if err = assertStatusCode(resp.StatusCode, http.StatusOK, http.StatusCreated); err != nil {
  78. var sec authError
  79. err = json.Unmarshal(body, &sec)
  80. if err != nil {
  81. return err
  82. }
  83. return sec
  84. }
  85. return nil
  86. }
  87. type authAPIAction struct {
  88. verb string
  89. }
  90. func (l *authAPIAction) HTTPRequest(ep url.URL) *http.Request {
  91. u := v2AuthURL(ep, "enable", "")
  92. req, _ := http.NewRequest(l.verb, u.String(), nil)
  93. return req
  94. }
  95. type authError struct {
  96. Message string `json:"message"`
  97. Code int `json:"-"`
  98. }
  99. func (e authError) Error() string {
  100. return e.Message
  101. }
  102. // NewAuthUserAPI constructs a new AuthUserAPI that uses HTTP to
  103. // interact with etcd's user creation and modification features.
  104. func NewAuthUserAPI(c Client) AuthUserAPI {
  105. return &httpAuthUserAPI{
  106. client: c,
  107. }
  108. }
  109. type AuthUserAPI interface {
  110. // AddUser adds a user.
  111. AddUser(ctx context.Context, username string, password string) error
  112. // RemoveUser removes a user.
  113. RemoveUser(ctx context.Context, username string) error
  114. // GetUser retrieves user details.
  115. GetUser(ctx context.Context, username string) (*User, error)
  116. // GrantUser grants a user some permission roles.
  117. GrantUser(ctx context.Context, username string, roles []string) (*User, error)
  118. // RevokeUser revokes some permission roles from a user.
  119. RevokeUser(ctx context.Context, username string, roles []string) (*User, error)
  120. // ChangePassword changes the user's password.
  121. ChangePassword(ctx context.Context, username string, password string) (*User, error)
  122. // ListUsers lists the users.
  123. ListUsers(ctx context.Context) ([]string, error)
  124. }
  125. type httpAuthUserAPI struct {
  126. client httpClient
  127. }
  128. type authUserAPIAction struct {
  129. verb string
  130. username string
  131. user *User
  132. }
  133. type authUserAPIList struct{}
  134. func (list *authUserAPIList) HTTPRequest(ep url.URL) *http.Request {
  135. u := v2AuthURL(ep, "users", "")
  136. req, _ := http.NewRequest("GET", u.String(), nil)
  137. req.Header.Set("Content-Type", "application/json")
  138. return req
  139. }
  140. func (l *authUserAPIAction) HTTPRequest(ep url.URL) *http.Request {
  141. u := v2AuthURL(ep, "users", l.username)
  142. if l.user == nil {
  143. req, _ := http.NewRequest(l.verb, u.String(), nil)
  144. return req
  145. }
  146. b, err := json.Marshal(l.user)
  147. if err != nil {
  148. panic(err)
  149. }
  150. body := bytes.NewReader(b)
  151. req, _ := http.NewRequest(l.verb, u.String(), body)
  152. req.Header.Set("Content-Type", "application/json")
  153. return req
  154. }
  155. func (u *httpAuthUserAPI) ListUsers(ctx context.Context) ([]string, error) {
  156. resp, body, err := u.client.Do(ctx, &authUserAPIList{})
  157. if err != nil {
  158. return nil, err
  159. }
  160. if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
  161. var sec authError
  162. err = json.Unmarshal(body, &sec)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return nil, sec
  167. }
  168. var userList struct {
  169. Users []userListEntry `json:"users"`
  170. }
  171. if err = json.Unmarshal(body, &userList); err != nil {
  172. return nil, err
  173. }
  174. ret := make([]string, 0, len(userList.Users))
  175. for _, u := range userList.Users {
  176. ret = append(ret, u.User)
  177. }
  178. return ret, nil
  179. }
  180. func (u *httpAuthUserAPI) AddUser(ctx context.Context, username string, password string) error {
  181. user := &User{
  182. User: username,
  183. Password: password,
  184. }
  185. return u.addRemoveUser(ctx, &authUserAPIAction{
  186. verb: "PUT",
  187. username: username,
  188. user: user,
  189. })
  190. }
  191. func (u *httpAuthUserAPI) RemoveUser(ctx context.Context, username string) error {
  192. return u.addRemoveUser(ctx, &authUserAPIAction{
  193. verb: "DELETE",
  194. username: username,
  195. })
  196. }
  197. func (u *httpAuthUserAPI) addRemoveUser(ctx context.Context, req *authUserAPIAction) error {
  198. resp, body, err := u.client.Do(ctx, req)
  199. if err != nil {
  200. return err
  201. }
  202. if err = assertStatusCode(resp.StatusCode, http.StatusOK, http.StatusCreated); err != nil {
  203. var sec authError
  204. err = json.Unmarshal(body, &sec)
  205. if err != nil {
  206. return err
  207. }
  208. return sec
  209. }
  210. return nil
  211. }
  212. func (u *httpAuthUserAPI) GetUser(ctx context.Context, username string) (*User, error) {
  213. return u.modUser(ctx, &authUserAPIAction{
  214. verb: "GET",
  215. username: username,
  216. })
  217. }
  218. func (u *httpAuthUserAPI) GrantUser(ctx context.Context, username string, roles []string) (*User, error) {
  219. user := &User{
  220. User: username,
  221. Grant: roles,
  222. }
  223. return u.modUser(ctx, &authUserAPIAction{
  224. verb: "PUT",
  225. username: username,
  226. user: user,
  227. })
  228. }
  229. func (u *httpAuthUserAPI) RevokeUser(ctx context.Context, username string, roles []string) (*User, error) {
  230. user := &User{
  231. User: username,
  232. Revoke: roles,
  233. }
  234. return u.modUser(ctx, &authUserAPIAction{
  235. verb: "PUT",
  236. username: username,
  237. user: user,
  238. })
  239. }
  240. func (u *httpAuthUserAPI) ChangePassword(ctx context.Context, username string, password string) (*User, error) {
  241. user := &User{
  242. User: username,
  243. Password: password,
  244. }
  245. return u.modUser(ctx, &authUserAPIAction{
  246. verb: "PUT",
  247. username: username,
  248. user: user,
  249. })
  250. }
  251. func (u *httpAuthUserAPI) modUser(ctx context.Context, req *authUserAPIAction) (*User, error) {
  252. resp, body, err := u.client.Do(ctx, req)
  253. if err != nil {
  254. return nil, err
  255. }
  256. if err = assertStatusCode(resp.StatusCode, http.StatusOK); err != nil {
  257. var sec authError
  258. err = json.Unmarshal(body, &sec)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return nil, sec
  263. }
  264. var user User
  265. if err = json.Unmarshal(body, &user); err != nil {
  266. var userR UserRoles
  267. if urerr := json.Unmarshal(body, &userR); urerr != nil {
  268. return nil, err
  269. }
  270. user.User = userR.User
  271. for _, r := range userR.Roles {
  272. user.Roles = append(user.Roles, r.Role)
  273. }
  274. }
  275. return &user, nil
  276. }