client_auth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. if role.HasRecursiveAccess(key, writeAccess) {
  94. return true
  95. }
  96. } else if role.HasKeyAccess(key, writeAccess) {
  97. return true
  98. }
  99. }
  100. plog.Warningf("auth: invalid access for user %s on key %s.", username, key)
  101. return false
  102. }
  103. func hasGuestAccess(sec auth.Store, r *http.Request, key string) bool {
  104. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  105. role, err := sec.GetRole(auth.GuestRoleName)
  106. if err != nil {
  107. return false
  108. }
  109. if role.HasKeyAccess(key, writeAccess) {
  110. return true
  111. }
  112. plog.Warningf("auth: invalid access for unauthenticated user on resource %s.", key)
  113. return false
  114. }
  115. func writeNoAuth(w http.ResponseWriter) {
  116. herr := httptypes.NewHTTPError(http.StatusUnauthorized, "Insufficient credentials")
  117. herr.WriteTo(w)
  118. }
  119. func handleAuth(mux *http.ServeMux, sh *authHandler) {
  120. mux.HandleFunc(authPrefix+"/roles", capabilityHandler(authCapability, sh.baseRoles))
  121. mux.HandleFunc(authPrefix+"/roles/", capabilityHandler(authCapability, sh.handleRoles))
  122. mux.HandleFunc(authPrefix+"/users", capabilityHandler(authCapability, sh.baseUsers))
  123. mux.HandleFunc(authPrefix+"/users/", capabilityHandler(authCapability, sh.handleUsers))
  124. mux.HandleFunc(authPrefix+"/enable", capabilityHandler(authCapability, sh.enableDisable))
  125. }
  126. func (sh *authHandler) baseRoles(w http.ResponseWriter, r *http.Request) {
  127. if !allowMethod(w, r.Method, "GET") {
  128. return
  129. }
  130. if !hasRootAccess(sh.sec, r) {
  131. writeNoAuth(w)
  132. return
  133. }
  134. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  135. w.Header().Set("Content-Type", "application/json")
  136. var rolesCollections struct {
  137. Roles []string `json:"roles"`
  138. }
  139. roles, err := sh.sec.AllRoles()
  140. if err != nil {
  141. writeError(w, err)
  142. return
  143. }
  144. if roles == nil {
  145. roles = make([]string, 0)
  146. }
  147. rolesCollections.Roles = roles
  148. err = json.NewEncoder(w).Encode(rolesCollections)
  149. if err != nil {
  150. plog.Warningf("baseRoles error encoding on %s", r.URL)
  151. }
  152. }
  153. func (sh *authHandler) handleRoles(w http.ResponseWriter, r *http.Request) {
  154. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  155. // Split "/roles/rolename/command".
  156. // First item is an empty string, second is "roles"
  157. pieces := strings.Split(subpath, "/")
  158. if len(pieces) == 2 {
  159. sh.baseRoles(w, r)
  160. return
  161. }
  162. if len(pieces) != 3 {
  163. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  164. return
  165. }
  166. sh.forRole(w, r, pieces[2])
  167. }
  168. func (sh *authHandler) forRole(w http.ResponseWriter, r *http.Request, role string) {
  169. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  170. return
  171. }
  172. if !hasRootAccess(sh.sec, r) {
  173. writeNoAuth(w)
  174. return
  175. }
  176. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  177. w.Header().Set("Content-Type", "application/json")
  178. switch r.Method {
  179. case "GET":
  180. data, err := sh.sec.GetRole(role)
  181. if err != nil {
  182. writeError(w, err)
  183. return
  184. }
  185. err = json.NewEncoder(w).Encode(data)
  186. if err != nil {
  187. plog.Warningf("forRole error encoding on %s", r.URL)
  188. return
  189. }
  190. return
  191. case "PUT":
  192. var in auth.Role
  193. err := json.NewDecoder(r.Body).Decode(&in)
  194. if err != nil {
  195. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  196. return
  197. }
  198. if in.Role != role {
  199. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON name does not match the name in the URL"))
  200. return
  201. }
  202. var out auth.Role
  203. // create
  204. if in.Grant.IsEmpty() && in.Revoke.IsEmpty() {
  205. err = sh.sec.CreateRole(in)
  206. if err != nil {
  207. writeError(w, err)
  208. return
  209. }
  210. w.WriteHeader(http.StatusCreated)
  211. out = in
  212. } else {
  213. if !in.Permissions.IsEmpty() {
  214. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON contains both permissions and grant/revoke"))
  215. return
  216. }
  217. out, err = sh.sec.UpdateRole(in)
  218. if err != nil {
  219. writeError(w, err)
  220. return
  221. }
  222. w.WriteHeader(http.StatusOK)
  223. }
  224. err = json.NewEncoder(w).Encode(out)
  225. if err != nil {
  226. plog.Warningf("forRole error encoding on %s", r.URL)
  227. return
  228. }
  229. return
  230. case "DELETE":
  231. err := sh.sec.DeleteRole(role)
  232. if err != nil {
  233. writeError(w, err)
  234. return
  235. }
  236. }
  237. }
  238. func (sh *authHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  239. if !allowMethod(w, r.Method, "GET") {
  240. return
  241. }
  242. if !hasRootAccess(sh.sec, r) {
  243. writeNoAuth(w)
  244. return
  245. }
  246. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  247. w.Header().Set("Content-Type", "application/json")
  248. var usersCollections struct {
  249. Users []string `json:"users"`
  250. }
  251. users, err := sh.sec.AllUsers()
  252. if err != nil {
  253. writeError(w, err)
  254. return
  255. }
  256. if users == nil {
  257. users = make([]string, 0)
  258. }
  259. usersCollections.Users = users
  260. err = json.NewEncoder(w).Encode(usersCollections)
  261. if err != nil {
  262. plog.Warningf("baseUsers error encoding on %s", r.URL)
  263. }
  264. }
  265. func (sh *authHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  266. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  267. // Split "/users/username".
  268. // First item is an empty string, second is "users"
  269. pieces := strings.Split(subpath, "/")
  270. if len(pieces) == 2 {
  271. sh.baseUsers(w, r)
  272. return
  273. }
  274. if len(pieces) != 3 {
  275. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  276. return
  277. }
  278. sh.forUser(w, r, pieces[2])
  279. }
  280. func (sh *authHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  281. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  282. return
  283. }
  284. if !hasRootAccess(sh.sec, r) {
  285. writeNoAuth(w)
  286. return
  287. }
  288. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  289. w.Header().Set("Content-Type", "application/json")
  290. switch r.Method {
  291. case "GET":
  292. u, err := sh.sec.GetUser(user)
  293. if err != nil {
  294. writeError(w, err)
  295. return
  296. }
  297. u.Password = ""
  298. err = json.NewEncoder(w).Encode(u)
  299. if err != nil {
  300. plog.Warningf("forUser error encoding on %s", r.URL)
  301. return
  302. }
  303. return
  304. case "PUT":
  305. var u auth.User
  306. err := json.NewDecoder(r.Body).Decode(&u)
  307. if err != nil {
  308. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  309. return
  310. }
  311. if u.User != user {
  312. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON name does not match the name in the URL"))
  313. return
  314. }
  315. var (
  316. out auth.User
  317. created bool
  318. )
  319. if len(u.Grant) == 0 && len(u.Revoke) == 0 {
  320. // create or update
  321. if len(u.Roles) != 0 {
  322. out, err = sh.sec.CreateUser(u)
  323. } else {
  324. // if user passes in both password and roles, we are unsure about his/her
  325. // intention.
  326. out, created, err = sh.sec.CreateOrUpdateUser(u)
  327. }
  328. if err != nil {
  329. writeError(w, err)
  330. return
  331. }
  332. } else {
  333. // update case
  334. if len(u.Roles) != 0 {
  335. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON contains both roles and grant/revoke"))
  336. return
  337. }
  338. out, err = sh.sec.UpdateUser(u)
  339. if err != nil {
  340. writeError(w, err)
  341. return
  342. }
  343. }
  344. if created {
  345. w.WriteHeader(http.StatusCreated)
  346. } else {
  347. w.WriteHeader(http.StatusOK)
  348. }
  349. out.Password = ""
  350. err = json.NewEncoder(w).Encode(out)
  351. if err != nil {
  352. plog.Warningf("forUser error encoding on %s", r.URL)
  353. return
  354. }
  355. return
  356. case "DELETE":
  357. err := sh.sec.DeleteUser(user)
  358. if err != nil {
  359. writeError(w, err)
  360. return
  361. }
  362. }
  363. }
  364. type enabled struct {
  365. Enabled bool `json:"enabled"`
  366. }
  367. func (sh *authHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  368. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  369. return
  370. }
  371. if !hasWriteRootAccess(sh.sec, r) {
  372. writeNoAuth(w)
  373. return
  374. }
  375. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  376. w.Header().Set("Content-Type", "application/json")
  377. isEnabled := sh.sec.AuthEnabled()
  378. switch r.Method {
  379. case "GET":
  380. jsonDict := enabled{isEnabled}
  381. err := json.NewEncoder(w).Encode(jsonDict)
  382. if err != nil {
  383. plog.Warningf("error encoding auth state on %s", r.URL)
  384. }
  385. case "PUT":
  386. err := sh.sec.EnableAuth()
  387. if err != nil {
  388. writeError(w, err)
  389. return
  390. }
  391. case "DELETE":
  392. err := sh.sec.DisableAuth()
  393. if err != nil {
  394. writeError(w, err)
  395. return
  396. }
  397. }
  398. }