Example #1
0
func (s *S) TestAddDefaultRole(c *check.C) {
	_, err := permission.NewRole("r1", "team")
	c.Assert(err, check.IsNil)
	_, err = permission.NewRole("r2", "team")
	c.Assert(err, check.IsNil)
	_, err = permission.NewRole("r3", "global")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	body := bytes.NewBufferString("team-create=r1&team-create=r2&user-create=r3")
	req, err := http.NewRequest("POST", "/role/default", body)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleDefaultCreate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r1, err := permission.FindRole("r1")
	c.Assert(err, check.IsNil)
	c.Assert(r1.Events, check.DeepEquals, []string{permission.RoleEventTeamCreate.String()})
	r2, err := permission.FindRole("r2")
	c.Assert(err, check.IsNil)
	c.Assert(r2.Events, check.DeepEquals, []string{permission.RoleEventTeamCreate.String()})
	r3, err := permission.FindRole("r3")
	c.Assert(err, check.IsNil)
	c.Assert(r3.Events, check.DeepEquals, []string{permission.RoleEventUserCreate.String()})
}
Example #2
0
func (s *S) TestAddDefaultRole(c *check.C) {
	_, err := permission.NewRole("r1", "team", "")
	c.Assert(err, check.IsNil)
	_, err = permission.NewRole("r2", "team", "")
	c.Assert(err, check.IsNil)
	_, err = permission.NewRole("r3", "global", "")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	body := bytes.NewBufferString("team-create=r1&team-create=r2&user-create=r3")
	req, err := http.NewRequest("POST", "/role/default", body)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleDefaultCreate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r1, err := permission.FindRole("r1")
	c.Assert(err, check.IsNil)
	c.Assert(r1.Events, check.DeepEquals, []string{permission.RoleEventTeamCreate.String()})
	r2, err := permission.FindRole("r2")
	c.Assert(err, check.IsNil)
	c.Assert(r2.Events, check.DeepEquals, []string{permission.RoleEventTeamCreate.String()})
	r3, err := permission.FindRole("r3")
	c.Assert(err, check.IsNil)
	c.Assert(r3.Events, check.DeepEquals, []string{permission.RoleEventUserCreate.String()})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "r1"},
		Owner:  token.GetUserName(),
		Kind:   "role.default.create",
		StartCustomData: []map[string]interface{}{
			{"name": "team-create", "value": []string{"r1", "r2"}},
			{"name": "user-create", "value": "r3"},
		},
	}, eventtest.HasEvent)
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "r2"},
		Owner:  token.GetUserName(),
		Kind:   "role.default.create",
		StartCustomData: []map[string]interface{}{
			{"name": "team-create", "value": []string{"r1", "r2"}},
			{"name": "user-create", "value": "r3"},
		},
	}, eventtest.HasEvent)
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "r3"},
		Owner:  token.GetUserName(),
		Kind:   "role.default.create",
		StartCustomData: []map[string]interface{}{
			{"name": "team-create", "value": []string{"r1", "r2"}},
			{"name": "user-create", "value": "r3"},
		},
	}, eventtest.HasEvent)
}
Example #3
0
func addDefaultRole(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleDefaultCreate) {
		return permission.ErrUnauthorized
	}
	err := r.ParseForm()
	if err != nil {
		return err
	}
	for evtName := range permission.RoleEventMap {
		roles := r.Form[evtName]
		for _, roleName := range roles {
			role, err := permission.FindRole(roleName)
			if err != nil {
				if err == permission.ErrRoleNotFound {
					return &errors.HTTP{
						Code:    http.StatusBadRequest,
						Message: err.Error(),
					}
				}
				return err
			}
			err = role.AddEvent(evtName)
			if err != nil {
				if _, ok := err.(permission.ErrRoleEventWrongContext); ok {
					return &errors.HTTP{
						Code:    http.StatusBadRequest,
						Message: err.Error(),
					}
				}
				return err
			}
		}
	}
	return nil
}
Example #4
0
func addPermissions(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleUpdate) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	role, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	err = r.ParseForm()
	if err != nil {
		return err
	}
	users, err := auth.ListUsersWithRole(roleName)
	if err != nil {
		return err
	}
	err = runWithPermSync(users, func() error {
		return role.AddPermissions(r.Form["permission"]...)
	})
	if err == nil {
		w.WriteHeader(http.StatusOK)
	}
	return err
}
Example #5
0
func deployableApps(u *auth.User, rolesCache map[string]*permission.Role) ([]string, error) {
	var perms []permission.Permission
	for _, roleData := range u.Roles {
		role := rolesCache[roleData.Name]
		if role == nil {
			foundRole, err := permission.FindRole(roleData.Name)
			if err != nil {
				return nil, err
			}
			role = &foundRole
			rolesCache[roleData.Name] = role
		}
		perms = append(perms, role.PermissionsFor(roleData.ContextValue)...)
	}
	contexts := permission.ContextsFromListForPermission(perms, permission.PermAppDeploy)
	if len(contexts) == 0 {
		return nil, nil
	}
	filter := appFilterByContext(contexts, nil)
	apps, err := app.List(filter)
	if err != nil {
		return nil, err
	}
	appNames := make([]string, len(apps))
	for i := range apps {
		appNames[i] = apps[i].GetName()
	}
	return appNames, nil
}
Example #6
0
func createRole(name, contextType string) (permission.Role, error) {
	role, err := permission.NewRole(name, contextType, "")
	if err == permission.ErrRoleAlreadyExists {
		role, err = permission.FindRole(name)
	}
	return role, err
}
Example #7
0
// title: role info
// path: /roles/{name}
// method: GET
// produce: application/json
// responses:
//   200: OK
//   401: Unauthorized
//   404: Role not found
func roleInfo(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !(permission.Check(t, permission.PermRoleUpdate) ||
		permission.Check(t, permission.PermRoleUpdateAssign) ||
		permission.Check(t, permission.PermRoleUpdateDissociate) ||
		permission.Check(t, permission.PermRoleCreate) ||
		permission.Check(t, permission.PermRoleDelete)) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	role, err := permission.FindRole(roleName)
	if err == permission.ErrRoleNotFound {
		return &errors.HTTP{
			Code:    http.StatusNotFound,
			Message: err.Error(),
		}
	}
	if err != nil {
		return err
	}
	b, err := json.Marshal(role)
	if err != nil {
		return err
	}
	w.Header().Set("Content-Type", "application/json")
	_, err = w.Write(b)
	return err
}
Example #8
0
func (u *User) AddRole(roleName string, contextValue string) error {
	_, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	err = conn.Users().Update(bson.M{"email": u.Email}, bson.M{
		"$addToSet": bson.M{
			// Order matters in $addToSet, that's why bson.D is used instead
			// of bson.M.
			"roles": bson.D([]bson.DocElem{
				{Name: "name", Value: roleName},
				{Name: "contextvalue", Value: contextValue},
			}),
		},
	})
	if err != nil {
		return err
	}
	return u.Reload()
}
Example #9
0
func canUseRole(t auth.Token, roleName, contextValue string) error {
	role, err := permission.FindRole(roleName)
	if err != nil {
		if err == permission.ErrRoleNotFound {
			return &errors.HTTP{
				Code:    http.StatusNotFound,
				Message: err.Error(),
			}
		}
		return err
	}
	userPerms, err := t.Permissions()
	if err != nil {
		return err
	}
	perms := role.PermissionsFor(contextValue)
	for _, p := range perms {
		if !permission.CheckFromPermList(userPerms, p.Scheme, p.Context) {
			return &errors.HTTP{
				Code:    http.StatusForbidden,
				Message: fmt.Sprintf("User not authorized to use permission %s", p.String()),
			}
		}
	}
	return nil
}
Example #10
0
func (s *S) TestRemoveDefaultRole(c *check.C) {
	r1, err := permission.NewRole("r1", "team", "")
	c.Assert(err, check.IsNil)
	err = r1.AddEvent(permission.RoleEventTeamCreate.String())
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	req, err := http.NewRequest("DELETE", "/role/default?team-create=r1", nil)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleDefaultDelete,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r1, err = permission.FindRole("r1")
	c.Assert(err, check.IsNil)
	c.Assert(r1.Events, check.DeepEquals, []string{})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "r1"},
		Owner:  token.GetUserName(),
		Kind:   "role.default.delete",
		StartCustomData: []map[string]interface{}{
			{"name": "team-create", "value": "r1"},
		},
	}, eventtest.HasEvent)
}
Example #11
0
func (s *S) TestAddPermissionsToARole(c *check.C) {
	_, err := permission.NewRole("test", "team", "")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	b := bytes.NewBufferString(`permission=app.update&permission=app.deploy`)
	req, err := http.NewRequest("POST", "/roles/test/permissions", b)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r, err := permission.FindRole("test")
	c.Assert(err, check.IsNil)
	sort.Strings(r.SchemeNames)
	c.Assert(r.SchemeNames, check.DeepEquals, []string{"app.deploy", "app.update"})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "test"},
		Owner:  token.GetUserName(),
		Kind:   "role.update.permission.add",
		StartCustomData: []map[string]interface{}{
			{"name": "permission", "value": []string{"app.update", "app.deploy"}},
		},
	}, eventtest.HasEvent)
}
Example #12
0
func (s *S) TestRemovePermissionsFromRole(c *check.C) {
	r, err := permission.NewRole("test", "team", "")
	c.Assert(err, check.IsNil)
	defer permission.DestroyRole(r.Name)
	err = r.AddPermissions("app.update")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	req, err := http.NewRequest("DELETE", "/roles/test/permissions/app.update", nil)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r, err = permission.FindRole("test")
	c.Assert(err, check.IsNil)
	c.Assert(r.SchemeNames, check.DeepEquals, []string{})
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypeRole, Value: "test"},
		Owner:  token.GetUserName(),
		Kind:   "role.update.permission.remove",
		StartCustomData: []map[string]interface{}{
			{"name": ":name", "value": "test"},
			{"name": ":permission", "value": "app.update"},
		},
	}, eventtest.HasEvent)
}
Example #13
0
func removeDefaultRole(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleDefaultDelete) {
		return permission.ErrUnauthorized
	}
	err := r.ParseForm()
	if err != nil {
		return err
	}
	for evtName := range permission.RoleEventMap {
		roles := r.Form[evtName]
		for _, roleName := range roles {
			role, err := permission.FindRole(roleName)
			if err != nil {
				if err == permission.ErrRoleNotFound {
					return &errors.HTTP{
						Code:    http.StatusBadRequest,
						Message: err.Error(),
					}
				}
				return err
			}
			err = role.RemoveEvent(evtName)
			if err != nil {
				return err
			}
		}
	}
	w.WriteHeader(http.StatusOK)
	return nil
}
Example #14
0
func (s *S) TestRemovePermissionsFromRoleSyncGitRepository(c *check.C) {
	r, err := permission.NewRole("test", "team")
	c.Assert(err, check.IsNil)
	defer permission.DestroyRole(r.Name)
	err = r.AddPermissions("app.deploy")
	c.Assert(err, check.IsNil)
	user := &auth.User{Email: "*****@*****.**", Password: "******"}
	_, err = nativeScheme.Create(user)
	c.Assert(err, check.IsNil)
	err = user.AddRole("test", s.team.Name)
	c.Assert(err, check.IsNil)
	a := app.App{Name: "myapp", TeamOwner: s.team.Name}
	err = app.CreateApp(&a, s.user)
	err = repository.Manager().GrantAccess(a.Name, user.Email)
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	req, err := http.NewRequest("DELETE", "/roles/test/permissions/app.deploy", nil)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r, err = permission.FindRole("test")
	c.Assert(err, check.IsNil)
	c.Assert(r.SchemeNames, check.DeepEquals, []string{})
	users, err := repositorytest.Granted(a.Name)
	c.Assert(err, check.IsNil)
	c.Assert(users, check.DeepEquals, []string{s.user.Email})
}
Example #15
0
func createApiUser(t auth.Token, user *auth.User) (*apiUser, error) {
	permissions, err := user.Permissions()
	if err != nil {
		return nil, err
	}
	permData := make([]rolePermissionData, len(permissions))
	for i, p := range permissions {
		if !permission.Check(t, p.Scheme, p.Context) {
			return nil, nil
		}
		permData[i] = rolePermissionData{
			Name:         p.Scheme.FullName(),
			ContextType:  string(p.Context.CtxType),
			ContextValue: p.Context.Value,
		}
	}
	roleData := make([]rolePermissionData, len(user.Roles))
	for i, userRole := range user.Roles {
		r, err := permission.FindRole(userRole.Name)
		if err != nil {
			return nil, err
		}
		roleData[i] = rolePermissionData{
			Name:         userRole.Name,
			ContextType:  string(r.ContextType),
			ContextValue: userRole.ContextValue,
		}
	}
	return &apiUser{
		Email:       user.Email,
		Roles:       roleData,
		Permissions: permData,
	}, nil
}
Example #16
0
File: auth.go Project: delkyd/tsuru
func createApiUser(perms []permission.Permission, user *auth.User, roleMap map[string]*permission.Role, includeAll bool) (*apiUser, error) {
	var permData []rolePermissionData
	roleData := make([]rolePermissionData, 0, len(user.Roles))
	if roleMap == nil {
		roleMap = make(map[string]*permission.Role)
	}
	allGlobal := true
	for _, userRole := range user.Roles {
		role := roleMap[userRole.Name]
		if role == nil {
			r, err := permission.FindRole(userRole.Name)
			if err != nil {
				return nil, err
			}
			role = &r
			roleMap[userRole.Name] = role
		}
		allPermsMatch := true
		permissions := role.PermissionsFor(userRole.ContextValue)
		if len(permissions) == 0 && !includeAll {
			continue
		}
		rolePerms := make([]rolePermissionData, len(permissions))
		for i, p := range permissions {
			if perms != nil && allPermsMatch && !permission.CheckFromPermList(perms, p.Scheme, p.Context) {
				allPermsMatch = false
				break
			}
			rolePerms[i] = rolePermissionData{
				Name:         p.Scheme.FullName(),
				ContextType:  string(p.Context.CtxType),
				ContextValue: p.Context.Value,
			}
		}
		if !allPermsMatch {
			continue
		}
		roleData = append(roleData, rolePermissionData{
			Name:         userRole.Name,
			ContextType:  string(role.ContextType),
			ContextValue: userRole.ContextValue,
		})
		permData = append(permData, rolePerms...)
		if role.ContextType != permission.CtxGlobal {
			allGlobal = false
		}
	}
	if len(roleData) == 0 || (!includeAll && allGlobal) {
		return nil, nil
	}
	return &apiUser{
		Email:       user.Email,
		Roles:       roleData,
		Permissions: permData,
	}, nil
}
Example #17
0
func (u *User) Permissions() ([]permission.Permission, error) {
	var permissions []permission.Permission
	for _, roleData := range u.Roles {
		role, err := permission.FindRole(roleData.Name)
		if err != nil {
			return nil, err
		}
		permissions = append(permissions, role.PermisionsFor(roleData.ContextValue)...)
	}
	return permissions, nil
}
Example #18
0
// title: add permissions
// path: /roles/{name}/permissions
// method: POST
// consume: application/x-www-form-urlencoded
// responses:
//   200: Ok
//   400: Invalid data
//   401: Unauthorized
//   409: Permission not allowed
func addPermissions(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	r.ParseForm()
	if !permission.Check(t, permission.PermRoleUpdatePermissionAdd) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	evt, err := event.New(&event.Opts{
		Target:     event.Target{Type: event.TargetTypeRole, Value: roleName},
		Kind:       permission.PermRoleUpdatePermissionAdd,
		Owner:      t,
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermRoleReadEvents),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	role, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	err = r.ParseForm()
	if err != nil {
		return err
	}
	users, err := auth.ListUsersWithRole(roleName)
	if err != nil {
		return err
	}
	err = runWithPermSync(users, func() error {
		return role.AddPermissions(r.Form["permission"]...)
	})
	if err == permission.ErrInvalidPermissionName {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: err.Error(),
		}
	}
	if perr, ok := err.(*permission.ErrPermissionNotFound); ok {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: perr.Error(),
		}
	}
	if perr, ok := err.(*permission.ErrPermissionNotAllowed); ok {
		return &errors.HTTP{
			Code:    http.StatusConflict,
			Message: perr.Error(),
		}
	}
	return err
}
Example #19
0
// title: add default role
// path: /role/default
// method: POST
// consme: application/x-www-form-urlencoded
// responses:
//   200: Ok
//   400: Invalid data
//   401: Unauthorized
func addDefaultRole(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	if !permission.Check(t, permission.PermRoleDefaultCreate) {
		return permission.ErrUnauthorized
	}
	err = r.ParseForm()
	if err != nil {
		return err
	}
	rolesMap := map[string][]string{}
	for evtName := range permission.RoleEventMap {
		roles := r.Form[evtName]
		for _, roleName := range roles {
			rolesMap[roleName] = append(rolesMap[roleName], evtName)
		}
	}
	for roleName, evts := range rolesMap {
		evt, err := event.New(&event.Opts{
			Target:     event.Target{Type: event.TargetTypeRole, Value: roleName},
			Kind:       permission.PermRoleDefaultCreate,
			Owner:      t,
			CustomData: event.FormToCustomData(r.Form),
			Allowed:    event.Allowed(permission.PermRoleReadEvents),
		})
		if err != nil {
			return err
		}
		defer func() { evt.Done(err) }()
		role, err := permission.FindRole(roleName)
		if err != nil {
			if err == permission.ErrRoleNotFound {
				return &errors.HTTP{
					Code:    http.StatusBadRequest,
					Message: err.Error(),
				}
			}
			return err
		}
		for _, evtName := range evts {
			err = role.AddEvent(evtName)
			if err != nil {
				if _, ok := err.(permission.ErrRoleEventWrongContext); ok {
					return &errors.HTTP{
						Code:    http.StatusBadRequest,
						Message: err.Error(),
					}
				}
				return err
			}
		}
	}
	return nil
}
Example #20
0
func addSuperRole(u *auth.User) error {
	defaultRoleName := "AllowAll"
	r, err := permission.FindRole(defaultRoleName)
	if err != nil {
		r, err = permission.NewRole(defaultRoleName, string(permission.CtxGlobal), "")
		if err != nil {
			return err
		}
	}
	err = r.AddPermissions("*")
	if err != nil {
		return err
	}
	return u.AddRole(defaultRoleName, "")
}
Example #21
0
func (u *User) Permissions() ([]permission.Permission, error) {
	var permissions []permission.Permission
	roles := make(map[string]*permission.Role)
	for _, roleData := range u.Roles {
		role := roles[roleData.Name]
		if role == nil {
			foundRole, err := permission.FindRole(roleData.Name)
			if err != nil && err != permission.ErrRoleNotFound {
				return nil, err
			}
			role = &foundRole
			roles[roleData.Name] = role
		}
		permissions = append(permissions, role.PermissionsFor(roleData.ContextValue)...)
	}
	return permissions, nil
}
Example #22
0
func removePermissions(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	roleName := r.URL.Query().Get(":name")
	role, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	defer r.Body.Close()
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	var params map[string][]string
	err = json.Unmarshal(b, &params)
	if err != nil {
		return err
	}
	return role.RemovePermissions(params["permissions"]...)
}
Example #23
0
func removePermissions(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleUpdate) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	permName := r.URL.Query().Get(":permission")
	role, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	users, err := auth.ListUsersWithRole(roleName)
	if err != nil {
		return err
	}
	err = runWithPermSync(users, func() error {
		return role.RemovePermissions(permName)
	})
	return err
}
Example #24
0
func (s *S) TestRemoveDefaultRole(c *check.C) {
	r1, err := permission.NewRole("r1", "team")
	c.Assert(err, check.IsNil)
	err = r1.AddEvent(permission.RoleEventTeamCreate.String())
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	req, err := http.NewRequest("DELETE", "/role/default?team-create=r1", nil)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleDefaultDelete,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r1, err = permission.FindRole("r1")
	c.Assert(err, check.IsNil)
	c.Assert(r1.Events, check.DeepEquals, []string{})
}
Example #25
0
func (s *S) TestAddPermissionsToARole(c *check.C) {
	_, err := permission.NewRole("test", "team")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	b := bytes.NewBufferString(`permission=app.update&permission=app.deploy`)
	req, err := http.NewRequest("POST", "/roles/test/permissions", b)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r, err := permission.FindRole("test")
	c.Assert(err, check.IsNil)
	sort.Strings(r.SchemeNames)
	c.Assert(r.SchemeNames, check.DeepEquals, []string{"app.deploy", "app.update"})
}
Example #26
0
func addPermissions(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	if !permission.Check(t, permission.PermRoleUpdate) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	role, err := permission.FindRole(roleName)
	if err != nil {
		return err
	}
	err = r.ParseForm()
	if err != nil {
		return err
	}
	users, err := auth.ListUsersWithRole(roleName)
	if err != nil {
		return err
	}
	err = runWithPermSync(users, func() error {
		return role.AddPermissions(r.Form["permission"]...)
	})
	if err == permission.ErrInvalidPermissionName {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: err.Error(),
		}
	}
	if perr, ok := err.(*permission.ErrPermissionNotFound); ok {
		return &errors.HTTP{
			Code:    http.StatusBadRequest,
			Message: perr.Error(),
		}
	}
	if perr, ok := err.(*permission.ErrPermissionNotAllowed); ok {
		return &errors.HTTP{
			Code:    http.StatusConflict,
			Message: perr.Error(),
		}
	}
	return err
}
Example #27
0
func createApiUser(perms []permission.Permission, user *auth.User, roleMap map[string]*permission.Role) (*apiUser, error) {
	permData := make([]rolePermissionData, 0, len(user.Roles))
	roleData := make([]rolePermissionData, len(user.Roles))
	if roleMap == nil {
		roleMap = make(map[string]*permission.Role)
	}
	for i, userRole := range user.Roles {
		role := roleMap[userRole.Name]
		if role == nil {
			r, err := permission.FindRole(userRole.Name)
			if err != nil {
				return nil, err
			}
			role = &r
			roleMap[userRole.Name] = role
		}
		roleData[i] = rolePermissionData{
			Name:         userRole.Name,
			ContextType:  string(role.ContextType),
			ContextValue: userRole.ContextValue,
		}
		permissions := role.PermissionsFor(userRole.ContextValue)
		for _, p := range permissions {
			if !permission.CheckFromPermList(perms, p.Scheme, p.Context) {
				return nil, nil
			}
			permData = append(permData, rolePermissionData{
				Name:         p.Scheme.FullName(),
				ContextType:  string(p.Context.CtxType),
				ContextValue: p.Context.Value,
			})
		}
	}
	return &apiUser{
		Email:       user.Email,
		Roles:       roleData,
		Permissions: permData,
	}, nil
}
Example #28
0
func (s *S) TestRemovePermissionsFromRole(c *check.C) {
	r, err := permission.NewRole("test", "team")
	c.Assert(err, check.IsNil)
	defer permission.DestroyRole(r.Name)
	err = r.AddPermissions("app.update")
	c.Assert(err, check.IsNil)
	rec := httptest.NewRecorder()
	req, err := http.NewRequest("DELETE", "/roles/test/permissions/app.update", nil)
	c.Assert(err, check.IsNil)
	token := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermRoleUpdate,
		Context: permission.Context(permission.CtxGlobal, ""),
	})
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "bearer "+token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusOK)
	r, err = permission.FindRole("test")
	c.Assert(err, check.IsNil)
	c.Assert(r.SchemeNames, check.DeepEquals, []string{})
}
Example #29
0
// title: remove permission
// path: /roles/{name}/permissions/{permission}
// method: DELETE
// responses:
//   200: Permission removed
//   401: Unauthorized
//   404: Not found
func removePermissions(w http.ResponseWriter, r *http.Request, t auth.Token) (err error) {
	r.ParseForm()
	if !permission.Check(t, permission.PermRoleUpdatePermissionRemove) {
		return permission.ErrUnauthorized
	}
	roleName := r.URL.Query().Get(":name")
	evt, err := event.New(&event.Opts{
		Target:     event.Target{Type: event.TargetTypeRole, Value: roleName},
		Kind:       permission.PermRoleUpdatePermissionRemove,
		Owner:      t,
		CustomData: event.FormToCustomData(r.Form),
		Allowed:    event.Allowed(permission.PermRoleReadEvents),
	})
	if err != nil {
		return err
	}
	defer func() { evt.Done(err) }()
	permName := r.URL.Query().Get(":permission")
	role, err := permission.FindRole(roleName)
	if err != nil {
		if err == permission.ErrRoleNotFound {
			return &errors.HTTP{
				Code:    http.StatusNotFound,
				Message: err.Error(),
			}
		}
		return err
	}
	users, err := auth.ListUsersWithRole(roleName)
	if err != nil {
		return err
	}
	err = runWithPermSync(users, func() error {
		return role.RemovePermissions(permName)
	})
	return err
}