client_auth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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, r *http.Request) {
  121. herr := httptypes.NewHTTPError(http.StatusUnauthorized, "Insufficient credentials")
  122. if err := herr.WriteTo(w); err != nil {
  123. plog.Debugf("error writing HTTPError (%v) to %s", err, r.RemoteAddr)
  124. }
  125. }
  126. func handleAuth(mux *http.ServeMux, sh *authHandler) {
  127. mux.HandleFunc(authPrefix+"/roles", capabilityHandler(authCapability, sh.baseRoles))
  128. mux.HandleFunc(authPrefix+"/roles/", capabilityHandler(authCapability, sh.handleRoles))
  129. mux.HandleFunc(authPrefix+"/users", capabilityHandler(authCapability, sh.baseUsers))
  130. mux.HandleFunc(authPrefix+"/users/", capabilityHandler(authCapability, sh.handleUsers))
  131. mux.HandleFunc(authPrefix+"/enable", capabilityHandler(authCapability, sh.enableDisable))
  132. }
  133. func (sh *authHandler) baseRoles(w http.ResponseWriter, r *http.Request) {
  134. if !allowMethod(w, r.Method, "GET") {
  135. return
  136. }
  137. if !hasRootAccess(sh.sec, r) {
  138. writeNoAuth(w, r)
  139. return
  140. }
  141. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  142. w.Header().Set("Content-Type", "application/json")
  143. roles, err := sh.sec.AllRoles()
  144. if err != nil {
  145. writeError(w, r, err)
  146. return
  147. }
  148. if roles == nil {
  149. roles = make([]string, 0)
  150. }
  151. err = r.ParseForm()
  152. if err != nil {
  153. writeError(w, r, err)
  154. return
  155. }
  156. var rolesCollections struct {
  157. Roles []auth.Role `json:"roles"`
  158. }
  159. for _, roleName := range roles {
  160. var role auth.Role
  161. role, err = sh.sec.GetRole(roleName)
  162. if err != nil {
  163. writeError(w, r, err)
  164. return
  165. }
  166. rolesCollections.Roles = append(rolesCollections.Roles, role)
  167. }
  168. err = json.NewEncoder(w).Encode(rolesCollections)
  169. if err != nil {
  170. plog.Warningf("baseRoles error encoding on %s", r.URL)
  171. writeError(w, r, err)
  172. return
  173. }
  174. }
  175. func (sh *authHandler) handleRoles(w http.ResponseWriter, r *http.Request) {
  176. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  177. // Split "/roles/rolename/command".
  178. // First item is an empty string, second is "roles"
  179. pieces := strings.Split(subpath, "/")
  180. if len(pieces) == 2 {
  181. sh.baseRoles(w, r)
  182. return
  183. }
  184. if len(pieces) != 3 {
  185. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  186. return
  187. }
  188. sh.forRole(w, r, pieces[2])
  189. }
  190. func (sh *authHandler) forRole(w http.ResponseWriter, r *http.Request, role string) {
  191. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  192. return
  193. }
  194. if !hasRootAccess(sh.sec, r) {
  195. writeNoAuth(w, r)
  196. return
  197. }
  198. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  199. w.Header().Set("Content-Type", "application/json")
  200. switch r.Method {
  201. case "GET":
  202. data, err := sh.sec.GetRole(role)
  203. if err != nil {
  204. writeError(w, r, err)
  205. return
  206. }
  207. err = json.NewEncoder(w).Encode(data)
  208. if err != nil {
  209. plog.Warningf("forRole error encoding on %s", r.URL)
  210. return
  211. }
  212. return
  213. case "PUT":
  214. var in auth.Role
  215. err := json.NewDecoder(r.Body).Decode(&in)
  216. if err != nil {
  217. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  218. return
  219. }
  220. if in.Role != role {
  221. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON name does not match the name in the URL"))
  222. return
  223. }
  224. var out auth.Role
  225. // create
  226. if in.Grant.IsEmpty() && in.Revoke.IsEmpty() {
  227. err = sh.sec.CreateRole(in)
  228. if err != nil {
  229. writeError(w, r, err)
  230. return
  231. }
  232. w.WriteHeader(http.StatusCreated)
  233. out = in
  234. } else {
  235. if !in.Permissions.IsEmpty() {
  236. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON contains both permissions and grant/revoke"))
  237. return
  238. }
  239. out, err = sh.sec.UpdateRole(in)
  240. if err != nil {
  241. writeError(w, r, err)
  242. return
  243. }
  244. w.WriteHeader(http.StatusOK)
  245. }
  246. err = json.NewEncoder(w).Encode(out)
  247. if err != nil {
  248. plog.Warningf("forRole error encoding on %s", r.URL)
  249. return
  250. }
  251. return
  252. case "DELETE":
  253. err := sh.sec.DeleteRole(role)
  254. if err != nil {
  255. writeError(w, r, err)
  256. return
  257. }
  258. }
  259. }
  260. type userWithRoles struct {
  261. User string `json:"user"`
  262. Roles []auth.Role `json:"roles,omitempty"`
  263. }
  264. func (sh *authHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  265. if !allowMethod(w, r.Method, "GET") {
  266. return
  267. }
  268. if !hasRootAccess(sh.sec, r) {
  269. writeNoAuth(w, r)
  270. return
  271. }
  272. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  273. w.Header().Set("Content-Type", "application/json")
  274. users, err := sh.sec.AllUsers()
  275. if err != nil {
  276. writeError(w, r, err)
  277. return
  278. }
  279. if users == nil {
  280. users = make([]string, 0)
  281. }
  282. err = r.ParseForm()
  283. if err != nil {
  284. writeError(w, r, err)
  285. return
  286. }
  287. var usersCollections struct {
  288. Users []userWithRoles `json:"users"`
  289. }
  290. for _, userName := range users {
  291. var user auth.User
  292. user, err = sh.sec.GetUser(userName)
  293. if err != nil {
  294. writeError(w, r, err)
  295. return
  296. }
  297. uwr := userWithRoles{User: user.User}
  298. for _, roleName := range user.Roles {
  299. var role auth.Role
  300. role, err = sh.sec.GetRole(roleName)
  301. if err != nil {
  302. writeError(w, r, err)
  303. return
  304. }
  305. uwr.Roles = append(uwr.Roles, role)
  306. }
  307. usersCollections.Users = append(usersCollections.Users, uwr)
  308. }
  309. err = json.NewEncoder(w).Encode(usersCollections)
  310. if err != nil {
  311. plog.Warningf("baseUsers error encoding on %s", r.URL)
  312. writeError(w, r, err)
  313. return
  314. }
  315. }
  316. func (sh *authHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  317. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  318. // Split "/users/username".
  319. // First item is an empty string, second is "users"
  320. pieces := strings.Split(subpath, "/")
  321. if len(pieces) == 2 {
  322. sh.baseUsers(w, r)
  323. return
  324. }
  325. if len(pieces) != 3 {
  326. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  327. return
  328. }
  329. sh.forUser(w, r, pieces[2])
  330. }
  331. func (sh *authHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  332. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  333. return
  334. }
  335. if !hasRootAccess(sh.sec, r) {
  336. writeNoAuth(w, r)
  337. return
  338. }
  339. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  340. w.Header().Set("Content-Type", "application/json")
  341. switch r.Method {
  342. case "GET":
  343. u, err := sh.sec.GetUser(user)
  344. if err != nil {
  345. writeError(w, r, err)
  346. return
  347. }
  348. err = r.ParseForm()
  349. if err != nil {
  350. writeError(w, r, err)
  351. return
  352. }
  353. uwr := userWithRoles{User: u.User}
  354. for _, roleName := range u.Roles {
  355. var role auth.Role
  356. role, err = sh.sec.GetRole(roleName)
  357. if err != nil {
  358. writeError(w, r, err)
  359. return
  360. }
  361. uwr.Roles = append(uwr.Roles, role)
  362. }
  363. err = json.NewEncoder(w).Encode(uwr)
  364. if err != nil {
  365. plog.Warningf("forUser error encoding on %s", r.URL)
  366. return
  367. }
  368. return
  369. case "PUT":
  370. var u auth.User
  371. err := json.NewDecoder(r.Body).Decode(&u)
  372. if err != nil {
  373. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  374. return
  375. }
  376. if u.User != user {
  377. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON name does not match the name in the URL"))
  378. return
  379. }
  380. var (
  381. out auth.User
  382. created bool
  383. )
  384. if len(u.Grant) == 0 && len(u.Revoke) == 0 {
  385. // create or update
  386. if len(u.Roles) != 0 {
  387. out, err = sh.sec.CreateUser(u)
  388. } else {
  389. // if user passes in both password and roles, we are unsure about his/her
  390. // intention.
  391. out, created, err = sh.sec.CreateOrUpdateUser(u)
  392. }
  393. if err != nil {
  394. writeError(w, r, err)
  395. return
  396. }
  397. } else {
  398. // update case
  399. if len(u.Roles) != 0 {
  400. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON contains both roles and grant/revoke"))
  401. return
  402. }
  403. out, err = sh.sec.UpdateUser(u)
  404. if err != nil {
  405. writeError(w, r, err)
  406. return
  407. }
  408. }
  409. if created {
  410. w.WriteHeader(http.StatusCreated)
  411. } else {
  412. w.WriteHeader(http.StatusOK)
  413. }
  414. out.Password = ""
  415. err = json.NewEncoder(w).Encode(out)
  416. if err != nil {
  417. plog.Warningf("forUser error encoding on %s", r.URL)
  418. return
  419. }
  420. return
  421. case "DELETE":
  422. err := sh.sec.DeleteUser(user)
  423. if err != nil {
  424. writeError(w, r, err)
  425. return
  426. }
  427. }
  428. }
  429. type enabled struct {
  430. Enabled bool `json:"enabled"`
  431. }
  432. func (sh *authHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  433. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  434. return
  435. }
  436. if !hasWriteRootAccess(sh.sec, r) {
  437. writeNoAuth(w, r)
  438. return
  439. }
  440. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  441. w.Header().Set("Content-Type", "application/json")
  442. isEnabled := sh.sec.AuthEnabled()
  443. switch r.Method {
  444. case "GET":
  445. jsonDict := enabled{isEnabled}
  446. err := json.NewEncoder(w).Encode(jsonDict)
  447. if err != nil {
  448. plog.Warningf("error encoding auth state on %s", r.URL)
  449. }
  450. case "PUT":
  451. err := sh.sec.EnableAuth()
  452. if err != nil {
  453. writeError(w, r, err)
  454. return
  455. }
  456. case "DELETE":
  457. err := sh.sec.DisableAuth()
  458. if err != nil {
  459. writeError(w, r, err)
  460. return
  461. }
  462. }
  463. }