client_auth.go 12 KB

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