client_auth.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. // Copyright 2015 CoreOS, Inc.
  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 etcdhttp
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "path"
  19. "strings"
  20. "github.com/coreos/etcd/etcdserver"
  21. "github.com/coreos/etcd/etcdserver/auth"
  22. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  23. "github.com/coreos/etcd/pkg/netutil"
  24. )
  25. type authHandler struct {
  26. sec *auth.Store
  27. cluster etcdserver.Cluster
  28. }
  29. func hasWriteRootAccess(sec *auth.Store, r *http.Request) bool {
  30. if r.Method == "GET" || r.Method == "HEAD" {
  31. return true
  32. }
  33. return hasRootAccess(sec, r)
  34. }
  35. func hasRootAccess(sec *auth.Store, r *http.Request) bool {
  36. if sec == nil {
  37. // No store means no auth available, eg, tests.
  38. return true
  39. }
  40. if !sec.AuthEnabled() {
  41. return true
  42. }
  43. username, password, ok := netutil.BasicAuth(r)
  44. if !ok {
  45. return false
  46. }
  47. rootUser, err := sec.GetUser(username)
  48. if err != nil {
  49. return false
  50. }
  51. ok = rootUser.CheckPassword(password)
  52. if !ok {
  53. plog.Warningf("auth: wrong password for user %s", username)
  54. return false
  55. }
  56. for _, role := range rootUser.Roles {
  57. if role == auth.RootRoleName {
  58. return true
  59. }
  60. }
  61. plog.Warningf("auth: user %s does not have the %s role for resource %s.", username, auth.RootRoleName, r.URL.Path)
  62. return false
  63. }
  64. func hasKeyPrefixAccess(sec *auth.Store, r *http.Request, key string, recursive bool) bool {
  65. if sec == nil {
  66. // No store means no auth available, eg, tests.
  67. return true
  68. }
  69. if !sec.AuthEnabled() {
  70. return true
  71. }
  72. username, password, ok := netutil.BasicAuth(r)
  73. if !ok {
  74. return hasGuestAccess(sec, r, key)
  75. }
  76. user, err := sec.GetUser(username)
  77. if err != nil {
  78. plog.Warningf("auth: no such user: %s.", username)
  79. return false
  80. }
  81. authAsUser := user.CheckPassword(password)
  82. if !authAsUser {
  83. plog.Warningf("auth: incorrect password for user: %s.", username)
  84. return false
  85. }
  86. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  87. for _, roleName := range user.Roles {
  88. role, err := sec.GetRole(roleName)
  89. if err != nil {
  90. continue
  91. }
  92. if recursive {
  93. return role.HasRecursiveAccess(key, writeAccess)
  94. }
  95. return role.HasKeyAccess(key, writeAccess)
  96. }
  97. plog.Warningf("auth: invalid access for user %s on key %s.", username, key)
  98. return false
  99. }
  100. func hasGuestAccess(sec *auth.Store, r *http.Request, key string) bool {
  101. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  102. role, err := sec.GetRole(auth.GuestRoleName)
  103. if err != nil {
  104. return false
  105. }
  106. if role.HasKeyAccess(key, writeAccess) {
  107. return true
  108. }
  109. plog.Warningf("auth: invalid access for unauthenticated user on resource %s.", key)
  110. return false
  111. }
  112. func writeNoAuth(w http.ResponseWriter) {
  113. herr := httptypes.NewHTTPError(http.StatusUnauthorized, "Insufficient credentials")
  114. herr.WriteTo(w)
  115. }
  116. func handleAuth(mux *http.ServeMux, sh *authHandler) {
  117. mux.HandleFunc(authPrefix+"/roles", capabilityHandler(authCapability, sh.baseRoles))
  118. mux.HandleFunc(authPrefix+"/roles/", capabilityHandler(authCapability, sh.handleRoles))
  119. mux.HandleFunc(authPrefix+"/users", capabilityHandler(authCapability, sh.baseUsers))
  120. mux.HandleFunc(authPrefix+"/users/", capabilityHandler(authCapability, sh.handleUsers))
  121. mux.HandleFunc(authPrefix+"/enable", capabilityHandler(authCapability, sh.enableDisable))
  122. }
  123. func (sh *authHandler) baseRoles(w http.ResponseWriter, r *http.Request) {
  124. if !allowMethod(w, r.Method, "GET") {
  125. return
  126. }
  127. if !hasRootAccess(sh.sec, r) {
  128. writeNoAuth(w)
  129. return
  130. }
  131. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  132. w.Header().Set("Content-Type", "application/json")
  133. var rolesCollections struct {
  134. Roles []string `json:"roles"`
  135. }
  136. roles, err := sh.sec.AllRoles()
  137. if err != nil {
  138. writeError(w, err)
  139. return
  140. }
  141. if roles == nil {
  142. roles = make([]string, 0)
  143. }
  144. rolesCollections.Roles = roles
  145. err = json.NewEncoder(w).Encode(rolesCollections)
  146. if err != nil {
  147. plog.Warningf("baseRoles error encoding on %s", r.URL)
  148. }
  149. }
  150. func (sh *authHandler) handleRoles(w http.ResponseWriter, r *http.Request) {
  151. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  152. // Split "/roles/rolename/command".
  153. // First item is an empty string, second is "roles"
  154. pieces := strings.Split(subpath, "/")
  155. if len(pieces) == 2 {
  156. sh.baseRoles(w, r)
  157. return
  158. }
  159. if len(pieces) != 3 {
  160. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  161. return
  162. }
  163. sh.forRole(w, r, pieces[2])
  164. }
  165. func (sh *authHandler) forRole(w http.ResponseWriter, r *http.Request, role string) {
  166. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  167. return
  168. }
  169. if !hasRootAccess(sh.sec, r) {
  170. writeNoAuth(w)
  171. return
  172. }
  173. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  174. w.Header().Set("Content-Type", "application/json")
  175. switch r.Method {
  176. case "GET":
  177. data, err := sh.sec.GetRole(role)
  178. if err != nil {
  179. writeError(w, err)
  180. return
  181. }
  182. err = json.NewEncoder(w).Encode(data)
  183. if err != nil {
  184. plog.Warningf("forRole error encoding on %s", r.URL)
  185. return
  186. }
  187. return
  188. case "PUT":
  189. var in auth.Role
  190. err := json.NewDecoder(r.Body).Decode(&in)
  191. if err != nil {
  192. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  193. return
  194. }
  195. if in.Role != role {
  196. writeError(w, httptypes.NewHTTPError(401, "Role JSON name does not match the name in the URL"))
  197. return
  198. }
  199. newrole, created, err := sh.sec.CreateOrUpdateRole(in)
  200. if err != nil {
  201. writeError(w, err)
  202. return
  203. }
  204. if created {
  205. w.WriteHeader(http.StatusCreated)
  206. } else {
  207. w.WriteHeader(http.StatusOK)
  208. }
  209. err = json.NewEncoder(w).Encode(newrole)
  210. if err != nil {
  211. plog.Warningf("forRole error encoding on %s", r.URL)
  212. return
  213. }
  214. return
  215. case "DELETE":
  216. err := sh.sec.DeleteRole(role)
  217. if err != nil {
  218. writeError(w, err)
  219. return
  220. }
  221. }
  222. }
  223. func (sh *authHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  224. if !allowMethod(w, r.Method, "GET") {
  225. return
  226. }
  227. if !hasRootAccess(sh.sec, r) {
  228. writeNoAuth(w)
  229. return
  230. }
  231. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  232. w.Header().Set("Content-Type", "application/json")
  233. var usersCollections struct {
  234. Users []string `json:"users"`
  235. }
  236. users, err := sh.sec.AllUsers()
  237. if err != nil {
  238. writeError(w, err)
  239. return
  240. }
  241. if users == nil {
  242. users = make([]string, 0)
  243. }
  244. usersCollections.Users = users
  245. err = json.NewEncoder(w).Encode(usersCollections)
  246. if err != nil {
  247. plog.Warningf("baseUsers error encoding on %s", r.URL)
  248. }
  249. }
  250. func (sh *authHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  251. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  252. // Split "/users/username".
  253. // First item is an empty string, second is "users"
  254. pieces := strings.Split(subpath, "/")
  255. if len(pieces) == 2 {
  256. sh.baseUsers(w, r)
  257. return
  258. }
  259. if len(pieces) != 3 {
  260. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  261. return
  262. }
  263. sh.forUser(w, r, pieces[2])
  264. }
  265. func (sh *authHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  266. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  267. return
  268. }
  269. if !hasRootAccess(sh.sec, r) {
  270. writeNoAuth(w)
  271. return
  272. }
  273. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  274. w.Header().Set("Content-Type", "application/json")
  275. switch r.Method {
  276. case "GET":
  277. u, err := sh.sec.GetUser(user)
  278. if err != nil {
  279. writeError(w, err)
  280. return
  281. }
  282. u.Password = ""
  283. err = json.NewEncoder(w).Encode(u)
  284. if err != nil {
  285. plog.Warningf("forUser error encoding on %s", r.URL)
  286. return
  287. }
  288. return
  289. case "PUT":
  290. var u auth.User
  291. err := json.NewDecoder(r.Body).Decode(&u)
  292. if err != nil {
  293. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  294. return
  295. }
  296. if u.User != user {
  297. writeError(w, httptypes.NewHTTPError(400, "User JSON name does not match the name in the URL"))
  298. return
  299. }
  300. newuser, created, err := sh.sec.CreateOrUpdateUser(u)
  301. if err != nil {
  302. writeError(w, err)
  303. return
  304. }
  305. if u.Password == "" {
  306. newuser.Password = ""
  307. }
  308. if created {
  309. w.WriteHeader(http.StatusCreated)
  310. } else {
  311. w.WriteHeader(http.StatusOK)
  312. }
  313. err = json.NewEncoder(w).Encode(newuser)
  314. if err != nil {
  315. plog.Warningf("forUser error encoding on %s", r.URL)
  316. return
  317. }
  318. return
  319. case "DELETE":
  320. err := sh.sec.DeleteUser(user)
  321. if err != nil {
  322. writeError(w, err)
  323. return
  324. }
  325. }
  326. }
  327. type enabled struct {
  328. Enabled bool `json:"enabled"`
  329. }
  330. func (sh *authHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  331. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  332. return
  333. }
  334. if !hasWriteRootAccess(sh.sec, r) {
  335. writeNoAuth(w)
  336. return
  337. }
  338. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  339. w.Header().Set("Content-Type", "application/json")
  340. isEnabled := sh.sec.AuthEnabled()
  341. switch r.Method {
  342. case "GET":
  343. jsonDict := enabled{isEnabled}
  344. err := json.NewEncoder(w).Encode(jsonDict)
  345. if err != nil {
  346. plog.Warningf("error encoding auth state on %s", r.URL)
  347. }
  348. case "PUT":
  349. err := sh.sec.EnableAuth()
  350. if err != nil {
  351. writeError(w, err)
  352. return
  353. }
  354. case "DELETE":
  355. err := sh.sec.DisableAuth()
  356. if err != nil {
  357. writeError(w, err)
  358. return
  359. }
  360. }
  361. }