client_auth.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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(http.StatusBadRequest, "Role JSON name does not match the name in the URL"))
  197. return
  198. }
  199. var out auth.Role
  200. // create
  201. if in.Grant.IsEmpty() && in.Revoke.IsEmpty() {
  202. err = sh.sec.CreateRole(in)
  203. if err != nil {
  204. writeError(w, err)
  205. return
  206. }
  207. w.WriteHeader(http.StatusCreated)
  208. out = in
  209. } else {
  210. if !in.Permissions.IsEmpty() {
  211. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON contains both permissions and grant/revoke"))
  212. return
  213. }
  214. out, err = sh.sec.UpdateRole(in)
  215. if err != nil {
  216. writeError(w, err)
  217. return
  218. }
  219. w.WriteHeader(http.StatusOK)
  220. }
  221. err = json.NewEncoder(w).Encode(out)
  222. if err != nil {
  223. plog.Warningf("forRole error encoding on %s", r.URL)
  224. return
  225. }
  226. return
  227. case "DELETE":
  228. err := sh.sec.DeleteRole(role)
  229. if err != nil {
  230. writeError(w, err)
  231. return
  232. }
  233. }
  234. }
  235. func (sh *authHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  236. if !allowMethod(w, r.Method, "GET") {
  237. return
  238. }
  239. if !hasRootAccess(sh.sec, r) {
  240. writeNoAuth(w)
  241. return
  242. }
  243. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  244. w.Header().Set("Content-Type", "application/json")
  245. var usersCollections struct {
  246. Users []string `json:"users"`
  247. }
  248. users, err := sh.sec.AllUsers()
  249. if err != nil {
  250. writeError(w, err)
  251. return
  252. }
  253. if users == nil {
  254. users = make([]string, 0)
  255. }
  256. usersCollections.Users = users
  257. err = json.NewEncoder(w).Encode(usersCollections)
  258. if err != nil {
  259. plog.Warningf("baseUsers error encoding on %s", r.URL)
  260. }
  261. }
  262. func (sh *authHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  263. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  264. // Split "/users/username".
  265. // First item is an empty string, second is "users"
  266. pieces := strings.Split(subpath, "/")
  267. if len(pieces) == 2 {
  268. sh.baseUsers(w, r)
  269. return
  270. }
  271. if len(pieces) != 3 {
  272. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  273. return
  274. }
  275. sh.forUser(w, r, pieces[2])
  276. }
  277. func (sh *authHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  278. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  279. return
  280. }
  281. if !hasRootAccess(sh.sec, r) {
  282. writeNoAuth(w)
  283. return
  284. }
  285. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  286. w.Header().Set("Content-Type", "application/json")
  287. switch r.Method {
  288. case "GET":
  289. u, err := sh.sec.GetUser(user)
  290. if err != nil {
  291. writeError(w, err)
  292. return
  293. }
  294. u.Password = ""
  295. err = json.NewEncoder(w).Encode(u)
  296. if err != nil {
  297. plog.Warningf("forUser error encoding on %s", r.URL)
  298. return
  299. }
  300. return
  301. case "PUT":
  302. var u auth.User
  303. err := json.NewDecoder(r.Body).Decode(&u)
  304. if err != nil {
  305. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  306. return
  307. }
  308. if u.User != user {
  309. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON name does not match the name in the URL"))
  310. return
  311. }
  312. var (
  313. out auth.User
  314. created bool
  315. )
  316. if len(u.Grant) == 0 && len(u.Revoke) == 0 {
  317. // create or update
  318. if len(u.Roles) != 0 {
  319. out, err = sh.sec.CreateUser(u)
  320. } else {
  321. // if user passes in both password and roles, we are unsure about his/her
  322. // intention.
  323. out, created, err = sh.sec.CreateOrUpdateUser(u)
  324. }
  325. if err != nil {
  326. writeError(w, err)
  327. return
  328. }
  329. } else {
  330. // update case
  331. if len(u.Roles) != 0 {
  332. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON contains both roles and grant/revoke"))
  333. return
  334. }
  335. out, err = sh.sec.UpdateUser(u)
  336. if err != nil {
  337. writeError(w, err)
  338. return
  339. }
  340. }
  341. if created {
  342. w.WriteHeader(http.StatusCreated)
  343. } else {
  344. w.WriteHeader(http.StatusOK)
  345. }
  346. out.Password = ""
  347. err = json.NewEncoder(w).Encode(out)
  348. if err != nil {
  349. plog.Warningf("forUser error encoding on %s", r.URL)
  350. return
  351. }
  352. return
  353. case "DELETE":
  354. err := sh.sec.DeleteUser(user)
  355. if err != nil {
  356. writeError(w, err)
  357. return
  358. }
  359. }
  360. }
  361. type enabled struct {
  362. Enabled bool `json:"enabled"`
  363. }
  364. func (sh *authHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  365. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  366. return
  367. }
  368. if !hasWriteRootAccess(sh.sec, r) {
  369. writeNoAuth(w)
  370. return
  371. }
  372. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  373. w.Header().Set("Content-Type", "application/json")
  374. isEnabled := sh.sec.AuthEnabled()
  375. switch r.Method {
  376. case "GET":
  377. jsonDict := enabled{isEnabled}
  378. err := json.NewEncoder(w).Encode(jsonDict)
  379. if err != nil {
  380. plog.Warningf("error encoding auth state on %s", r.URL)
  381. }
  382. case "PUT":
  383. err := sh.sec.EnableAuth()
  384. if err != nil {
  385. writeError(w, err)
  386. return
  387. }
  388. case "DELETE":
  389. err := sh.sec.DisableAuth()
  390. if err != nil {
  391. writeError(w, err)
  392. return
  393. }
  394. }
  395. }