Skip to content

Commit

Permalink
BED-4537: Create Share endpoint (#775)
Browse files Browse the repository at this point in the history
* created ShareSavedQueries endpoint and updated openapi docs

BED-4537 db methods by Mike

BED-4537 added database functionality to query for all scopes, integration tests for that

BED-4537 linter fix for error

BED-4537 added ability to delete saved query permissions and integration tests for it

BED-4537 added ability to delete saved query permissions, bulk create saved query permissions, and integration tests

BED-4537 forgot to push batch changes, whoops!

BED-4537 fix linting error

Addressed PR feedback, corrected yaml files and unit tests

Address PR feedback and optimization changes

Refactored control flow logic, added TONS of unit tests, added some integration tests, and altered some database functions

Refactored logic, added unit/integration tests, handled merge conflicts

Addressed previous PR feedback and adjusted unit tests

Corrected openapi stuff

Changed the endpoint url

More openapi corrections and file name change

Addressed PR feedback and fixed unit/integration tests

* chore: cleanup

* Corrected unit/integrations tests

* Renamed files back to former names and moved an integration test

* Addressed unit test feedback

* Corrected database functions and integration tests feedback

---------

Co-authored-by: Mistah J <26472282+mistahj67@users.noreply.github.com>
  • Loading branch information
ALCooper12 and mistahj67 authored Aug 27, 2024
1 parent e88dad4 commit af12ed0
Show file tree
Hide file tree
Showing 14 changed files with 2,026 additions and 242 deletions.
1 change: 1 addition & 0 deletions cmd/api/src/api/registration/v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ func NewV2API(cfg config.Configuration, resources v2.Resources, routerInst *rout
routerInst.PUT(fmt.Sprintf("/api/v2/saved-queries/{%s}", api.URIPathVariableSavedQueryID), resources.UpdateSavedQuery).RequirePermissions(permissions.SavedQueriesWrite),
routerInst.DELETE(fmt.Sprintf("/api/v2/saved-queries/{%s}", api.URIPathVariableSavedQueryID), resources.DeleteSavedQuery).RequirePermissions(permissions.SavedQueriesWrite),
routerInst.DELETE(fmt.Sprintf("/api/v2/saved-queries/{%s}/permissions", api.URIPathVariableSavedQueryID), resources.DeleteSavedQueryPermissions).RequirePermissions(permissions.SavedQueriesWrite),
routerInst.PUT(fmt.Sprintf("/api/v2/saved-queries/{%s}/permissions", api.URIPathVariableSavedQueryID), resources.ShareSavedQueries).RequirePermissions(permissions.SavedQueriesWrite),

// Azure Entity API
routerInst.GET("/api/v2/azure/{entity_type}", resources.GetAZEntity).RequirePermissions(permissions.GraphDBRead),
Expand Down
2 changes: 1 addition & 1 deletion cmd/api/src/api/v2/saved_queries.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func (s Resources) DeleteSavedQuery(response http.ResponseWriter, request *http.
if _, isAdmin := user.Roles.FindByName(auth.RoleAdministrator); !isAdmin {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusForbidden, "User does not have permission to delete this query", request), response)
return
} else if isPublicQuery, err := s.DB.IsSavedQueryPublic(request.Context(), int64(savedQueryID)); err != nil {
} else if isPublicQuery, err := s.DB.IsSavedQueryPublic(request.Context(), savedQueryID); err != nil {
api.HandleDatabaseError(request, response, err)
return
} else if !isPublicQuery {
Expand Down
154 changes: 131 additions & 23 deletions cmd/api/src/api/v2/saved_queries_permissions.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,145 @@
/*
* Copyright 2024 Specter Ops, Inc.
*
* Licensed under the Apache License, Version 2.0
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
// Copyright 2024 Specter Ops, Inc.
//
// Licensed under the Apache License, Version 2.0
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

package v2

import (
"encoding/json"
"errors"
"net/http"
"slices"
"strconv"

"github.com/gofrs/uuid"
"github.com/gorilla/mux"
"github.com/specterops/bloodhound/src/api"
"github.com/specterops/bloodhound/src/auth"
ctx2 "github.com/specterops/bloodhound/src/ctx"
"github.com/specterops/bloodhound/src/database"
"github.com/specterops/bloodhound/src/model"
"net/http"
"slices"
"strconv"
)

type ShareSavedQueriesResponse []model.SavedQueriesPermissions

type SavedQueryPermissionRequest struct {
UserIDs []uuid.UUID `json:"user_ids"`
Public bool `json:"public"`
}

var (
ErrInvalidSelfShare = errors.New("invalidSelfShare")
ErrForbidden = errors.New("forbidden")
ErrInvalidPublicShare = errors.New("invalidPublicShare")
)

func CanUpdateSavedQueriesPermission(user model.User, savedQueryBelongsToUser bool, createRequest SavedQueryPermissionRequest, dbSavedQueryScope database.SavedQueryScopeMap) error {
if user.Roles.Has(model.Role{Name: auth.RoleAdministrator}) {
if createRequest.Public && savedQueryBelongsToUser {
return nil
} else if len(createRequest.UserIDs) == 0 && (savedQueryBelongsToUser || dbSavedQueryScope[model.SavedQueryScopePublic]) {
return nil
} else if len(createRequest.UserIDs) > 0 && !createRequest.Public {
if dbSavedQueryScope[model.SavedQueryScopePublic] {
return ErrInvalidPublicShare
}
if savedQueryBelongsToUser {
for _, sharedUserID := range createRequest.UserIDs {
if sharedUserID == user.ID {
return ErrInvalidSelfShare
}
}
return nil
}
}
} else if savedQueryBelongsToUser && !dbSavedQueryScope[model.SavedQueryScopePublic] {
if len(createRequest.UserIDs) > 0 && !createRequest.Public {
for _, sharedUserID := range createRequest.UserIDs {
if sharedUserID == user.ID {
return ErrInvalidSelfShare
}
}
}
return nil
}
return ErrForbidden
}

// ShareSavedQueries allows a user to share queries between users, as well as share them publicly
func (s Resources) ShareSavedQueries(response http.ResponseWriter, request *http.Request) {
var (
rawSavedQueryID = mux.Vars(request)[api.URIPathVariableSavedQueryID]
createRequest SavedQueryPermissionRequest
)

if user, isUser := auth.GetUserFromAuthCtx(ctx2.FromRequest(request).AuthCtx); !isUser {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "No associated user found", request), response)
} else if savedQueryID, err := strconv.ParseInt(rawSavedQueryID, 10, 64); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, api.ErrorResponseDetailsIDMalformed, request), response)
} else if err := api.ReadJSONRequestPayloadLimited(&createRequest, request); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if createRequest.Public && len(createRequest.UserIDs) > 0 {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "Public cannot be true while user_ids is populated", request), response)
} else if savedQueryBelongsToUser, err := s.DB.SavedQueryBelongsToUser(request.Context(), user.ID, savedQueryID); errors.Is(err, database.ErrNotFound) {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusNotFound, "Query does not exist", request), response)
} else if err != nil {
api.HandleDatabaseError(request, response, err)
} else if dbSavedQueryScope, err := s.DB.GetScopeForSavedQuery(request.Context(), savedQueryID, user.ID); err != nil {
api.HandleDatabaseError(request, response, err)
} else if err := CanUpdateSavedQueriesPermission(user, savedQueryBelongsToUser, createRequest, dbSavedQueryScope); err != nil {
if errors.Is(err, ErrInvalidSelfShare) {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "Cannot share query to self", request), response)
} else if errors.Is(err, ErrInvalidPublicShare) {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "Public query cannot be shared to users. You must set your query to private first", request), response)
} else {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusForbidden, api.ErrorResponseDetailsForbidden, request), response)
}
} else {
// Query set to public
if createRequest.Public {
if dbSavedQueryScope[model.SavedQueryScopePublic] {
response.WriteHeader(http.StatusNoContent)
} else {
if savedPermission, err := s.DB.CreateSavedQueryPermissionToPublic(request.Context(), savedQueryID); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
api.WriteBasicResponse(request.Context(), ShareSavedQueriesResponse{savedPermission}, http.StatusCreated, response)
}
}
// Query set to private
} else if len(createRequest.UserIDs) == 0 {
if err := s.DB.DeleteSavedQueryPermissionsForUsers(request.Context(), savedQueryID); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
response.WriteHeader(http.StatusNoContent)
}
// Sharing a query
} else if len(createRequest.UserIDs) > 0 && !createRequest.Public {
if dbSavedQueryScope[model.SavedQueryScopePublic] {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "Public query cannot be shared to users. You must set your query to private first", request), response)
} else {
if savedPermissions, err := s.DB.CreateSavedQueryPermissionsToUsers(request.Context(), savedQueryID, createRequest.UserIDs...); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
api.WriteBasicResponse(request.Context(), savedPermissions, http.StatusCreated, response)
}
}
}
}
}

// DeleteSavedQueryPermissionsRequest represents the payload sent to the unshare endpoint
type DeleteSavedQueryPermissionsRequest struct {
UserIds []uuid.UUID `json:"user_ids"`
Expand Down Expand Up @@ -59,7 +168,6 @@ func (s Resources) DeleteSavedQueryPermissions(response http.ResponseWriter, req
api.HandleDatabaseError(request, response, err)
return
} else if !isShared {

// The user cannot unshare a saved query if a saved query permission does not exist for them. This means a user cannot unshare a query that they don't own, or hasn't been shared with them
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "User cannot unshare a query from themselves that is not shared to them", request), response)
return
Expand All @@ -73,15 +181,15 @@ func (s Resources) DeleteSavedQueryPermissions(response http.ResponseWriter, req
api.HandleDatabaseError(request, response, err)
return
} else if !savedQueryBelongsToUser {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusUnauthorized, "Query does not belong to the user", request), response)
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusForbidden, "Query does not belong to the user", request), response)
return
}
}

}

// Unshare the queries
if err = s.DB.DeleteSavedQueryPermissionsForUsers(request.Context(), savedQueryID, deleteRequest.UserIds); err != nil {
if err = s.DB.DeleteSavedQueryPermissionsForUsers(request.Context(), savedQueryID, deleteRequest.UserIds...); err != nil {
api.HandleDatabaseError(request, response, err)
return
}
Expand Down
Loading

0 comments on commit af12ed0

Please sign in to comment.