Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BED-4537: Create Share endpoint #775

Merged
merged 6 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading