client_auth.go 11 KB

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