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-5068 feat: Add PATCH endpoint to update sso providers #975

Merged
merged 5 commits into from
Nov 26, 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 @@ -59,6 +59,7 @@ func registerV2Auth(resources v2.Resources, routerInst *router.Router, permissio
routerInst.GET("/api/v2/sso-providers", managementResource.ListAuthProviders),
routerInst.POST("/api/v2/sso-providers/oidc", managementResource.CreateOIDCProvider).CheckFeatureFlag(resources.DB, appcfg.FeatureOIDCSupport).RequirePermissions(permissions.AuthManageProviders),
routerInst.DELETE(fmt.Sprintf("/api/v2/sso-providers/{%s}", api.URIPathVariableSSOProviderID), managementResource.DeleteSSOProvider).RequirePermissions(permissions.AuthManageProviders),
routerInst.PATCH(fmt.Sprintf("/api/v2/sso-providers/{%s}", api.URIPathVariableSSOProviderID), managementResource.UpdateSSOProvider).RequirePermissions(permissions.AuthManageProviders),
routerInst.GET(fmt.Sprintf("/api/v2/sso/{%s}/login", api.URIPathVariableSSOProviderSlug), managementResource.SSOLoginHandler),
routerInst.GET(fmt.Sprintf("/api/v2/sso/{%s}/metadata", api.URIPathVariableSSOProviderSlug), managementResource.ServeMetadata),
routerInst.PathPrefix(fmt.Sprintf("/api/v2/sso/{%s}/callback", api.URIPathVariableSSOProviderSlug), http.HandlerFunc(managementResource.SSOCallbackHandler)),
Expand Down
48 changes: 40 additions & 8 deletions cmd/api/src/api/v2/auth/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,57 @@ import (
"golang.org/x/oauth2"
)

// CreateOIDCProviderRequest represents the body of the CreateOIDCProvider endpoint
type CreateOIDCProviderRequest struct {
// UpsertOIDCProviderRequest represents the body of create & update provider endpoints
type UpsertOIDCProviderRequest struct {
Name string `json:"name" validate:"required"`
Issuer string `json:"issuer" validate:"url"`
ClientID string `json:"client_id" validate:"required"`
}

// UpdateOIDCProviderRequest updates an OIDC provider, support for only partial payloads
func (s ManagementResource) UpdateOIDCProviderRequest(response http.ResponseWriter, request *http.Request, ssoProvider model.SSOProvider) {
var upsertReq UpsertOIDCProviderRequest

if ssoProvider.OIDCProvider == nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusNotFound, api.ErrorResponseDetailsResourceNotFound, request), response)
} else if err := api.ReadJSONRequestPayloadLimited(&upsertReq, request); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else {
if upsertReq.Name != "" {
ssoProvider.Name = upsertReq.Name
}

if upsertReq.ClientID != "" {
ssoProvider.OIDCProvider.ClientID = upsertReq.ClientID
}

if upsertReq.Issuer != "" {
if err := validation.ValidUrl(upsertReq.Issuer); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "issuer url is invalid", request), response)
return
}

ssoProvider.OIDCProvider.Issuer = upsertReq.Issuer
}

if oidcProvider, err := s.db.UpdateOIDCProvider(request.Context(), ssoProvider); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
api.WriteBasicResponse(request.Context(), oidcProvider, http.StatusOK, response)
}
}
}

// CreateOIDCProvider creates an OIDC provider entry given a valid request
func (s ManagementResource) CreateOIDCProvider(response http.ResponseWriter, request *http.Request) {
var (
createRequest = CreateOIDCProviderRequest{}
)
var upsertReq UpsertOIDCProviderRequest

if err := api.ReadJSONRequestPayloadLimited(&createRequest, request); err != nil {
if err := api.ReadJSONRequestPayloadLimited(&upsertReq, request); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if validated := validation.Validate(createRequest); validated != nil {
} else if validated := validation.Validate(upsertReq); validated != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, validated.Error(), request), response)
} else {
if oidcProvider, err := s.db.CreateOIDCProvider(request.Context(), createRequest.Name, createRequest.Issuer, createRequest.ClientID); err != nil {
if oidcProvider, err := s.db.CreateOIDCProvider(request.Context(), upsertReq.Name, upsertReq.Issuer, upsertReq.ClientID); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
api.WriteBasicResponse(request.Context(), oidcProvider, http.StatusCreated, response)
Expand Down
107 changes: 89 additions & 18 deletions cmd/api/src/api/v2/auth/oidc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@ import (

"github.com/specterops/bloodhound/src/api/v2/apitest"
"github.com/specterops/bloodhound/src/api/v2/auth"
"github.com/specterops/bloodhound/src/database"
"github.com/specterops/bloodhound/src/model"
"github.com/specterops/bloodhound/src/utils/test"
"go.uber.org/mock/gomock"
)

func TestManagementResource_CreateOIDCProvider(t *testing.T) {
const (
url = "/api/v2/sso/providers/oidc"
)
var (
mockCtrl = gomock.NewController(t)
resources, mockDB = apitest.NewAuthManagementResource(mockCtrl)
Expand All @@ -45,9 +43,7 @@ func TestManagementResource_CreateOIDCProvider(t *testing.T) {
}, nil)

test.Request(t).
WithMethod(http.MethodPost).
WithURL(url).
WithBody(auth.CreateOIDCProviderRequest{
WithBody(auth.UpsertOIDCProviderRequest{
Name: "Bloodhound gang",
Issuer: "https://localhost/auth",
ClientID: "bloodhound",
Expand All @@ -59,19 +55,14 @@ func TestManagementResource_CreateOIDCProvider(t *testing.T) {

t.Run("error parsing body request", func(t *testing.T) {
test.Request(t).
WithMethod(http.MethodPost).
WithURL(url).
WithBody("").
OnHandlerFunc(resources.CreateOIDCProvider).
Require().
ResponseStatusCode(http.StatusBadRequest)
})

t.Run("error validating request field", func(t *testing.T) {
test.Request(t).
WithMethod(http.MethodPost).
WithURL(url).
WithBody(auth.CreateOIDCProviderRequest{
WithBody(auth.UpsertOIDCProviderRequest{
Name: "test",
Issuer: "1234:not:a:url",
ClientID: "bloodhound",
Expand All @@ -82,12 +73,10 @@ func TestManagementResource_CreateOIDCProvider(t *testing.T) {
})

t.Run("error invalid Issuer", func(t *testing.T) {
request := auth.CreateOIDCProviderRequest{
request := auth.UpsertOIDCProviderRequest{
Issuer: "12345:bloodhound",
}
test.Request(t).
WithMethod(http.MethodPost).
WithURL(url).
WithBody(request).
OnHandlerFunc(resources.CreateOIDCProvider).
Require().
Expand All @@ -98,9 +87,7 @@ func TestManagementResource_CreateOIDCProvider(t *testing.T) {
mockDB.EXPECT().CreateOIDCProvider(gomock.Any(), "test", "https://localhost/auth", "bloodhound").Return(model.OIDCProvider{}, fmt.Errorf("error"))

test.Request(t).
WithMethod(http.MethodPost).
WithURL(url).
WithBody(auth.CreateOIDCProviderRequest{
WithBody(auth.UpsertOIDCProviderRequest{
Name: "test",
Issuer: "https://localhost/auth",
ClientID: "bloodhound",
Expand All @@ -110,3 +97,87 @@ func TestManagementResource_CreateOIDCProvider(t *testing.T) {
ResponseStatusCode(http.StatusInternalServerError)
})
}

func TestManagementResource_UpdateOIDCProvider(t *testing.T) {
var (
mockCtrl = gomock.NewController(t)
resources, mockDB = apitest.NewAuthManagementResource(mockCtrl)
baseProvider = model.SSOProvider{
Type: model.SessionAuthProviderOIDC,
Name: "Gotham Net",
OIDCProvider: &model.OIDCProvider{
ClientID: "gotham-net",
Issuer: "https://gotham.net",
},
}
urlParams = map[string]string{"sso_provider_id": "1"}
)
defer mockCtrl.Finish()

t.Run("successfully update an OIDCProvider", func(t *testing.T) {
mockDB.EXPECT().GetSSOProviderById(gomock.Any(), int32(1)).Return(baseProvider, nil)
mockDB.EXPECT().UpdateOIDCProvider(gomock.Any(), gomock.Any())

test.Request(t).
WithURLPathVars(urlParams).
WithBody(auth.UpsertOIDCProviderRequest{
Name: "Gotham Net 2",
Issuer: "https://gotham-2.net",
ClientID: "gotham-net-2",
}).
OnHandlerFunc(resources.UpdateSSOProvider).
Require().
ResponseStatusCode(http.StatusOK)
})

t.Run("error not found while updating an unknown OIDCProvider", func(t *testing.T) {
mockDB.EXPECT().GetSSOProviderById(gomock.Any(), int32(1)).Return(model.SSOProvider{}, database.ErrNotFound)

test.Request(t).
WithURLPathVars(urlParams).
OnHandlerFunc(resources.UpdateSSOProvider).
Require().
ResponseStatusCode(http.StatusNotFound)
})

t.Run("error parsing body request", func(t *testing.T) {
mockDB.EXPECT().GetSSOProviderById(gomock.Any(), int32(1)).Return(baseProvider, nil)

test.Request(t).
WithURLPathVars(urlParams).
OnHandlerFunc(resources.UpdateSSOProvider).
Require().
ResponseStatusCode(http.StatusBadRequest)
})

t.Run("error validating request field", func(t *testing.T) {
mockDB.EXPECT().GetSSOProviderById(gomock.Any(), int32(1)).Return(baseProvider, nil)

test.Request(t).
WithURLPathVars(urlParams).
WithBody(auth.UpsertOIDCProviderRequest{
Name: "test",
Issuer: "1234:not:a:url",
ClientID: "bloodhound",
}).
OnHandlerFunc(resources.UpdateSSOProvider).
Require().
ResponseStatusCode(http.StatusBadRequest)
})

t.Run("error creating oidc provider db entry", func(t *testing.T) {
mockDB.EXPECT().GetSSOProviderById(gomock.Any(), int32(1)).Return(baseProvider, nil)
mockDB.EXPECT().UpdateOIDCProvider(gomock.Any(), gomock.Any()).Return(model.OIDCProvider{}, fmt.Errorf("error"))

test.Request(t).
WithURLPathVars(urlParams).
WithBody(auth.UpsertOIDCProviderRequest{
Name: "test",
Issuer: "https://localhost/auth",
ClientID: "bloodhound",
}).
OnHandlerFunc(resources.UpdateSSOProvider).
Require().
ResponseStatusCode(http.StatusInternalServerError)
})
}
73 changes: 70 additions & 3 deletions cmd/api/src/api/v2/auth/saml.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"io"
"net/http"
"strconv"
"strings"

"github.com/crewjam/saml"
"github.com/crewjam/saml/samlsp"
Expand Down Expand Up @@ -144,9 +145,7 @@ func (s ManagementResource) CreateSAMLProviderMultipart(response http.ResponseWr
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if metadata, err := samlsp.ParseMetadata(metadataXML); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if ssoDescriptor, err := auth.GetIDPSingleSignOnDescriptor(metadata, saml.HTTPPostBinding); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if ssoURL, err := auth.GetIDPSingleSignOnServiceURL(ssoDescriptor, saml.HTTPPostBinding); err != nil {
} else if ssoURL, err := auth.GetIDPSingleSignOnServiceURL(metadata, saml.HTTPPostBinding); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "metadata does not have a SSO service that supports HTTP POST binding", request), response)
} else {
samlIdentityProvider.Name = providerNames[0]
Expand Down Expand Up @@ -188,6 +187,74 @@ func (s ManagementResource) DeleteSAMLProvider(response http.ResponseWriter, req
}
}

// UpdateSAMLProviderRequest updates an SAML provider entry, support for partial payloads
func (s ManagementResource) UpdateSAMLProviderRequest(response http.ResponseWriter, request *http.Request, ssoProvider model.SSOProvider) {
if ssoProvider.SAMLProvider == nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusNotFound, api.ErrorResponseDetailsResourceNotFound, request), response)
} else if err := request.ParseMultipartForm(api.DefaultAPIPayloadReadLimitBytes); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if providerNames, hasProviderName := request.MultipartForm.Value["name"]; len(providerNames) > 1 {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "expected only one \"name\" parameter", request), response)
} else if metadataXMLFileHandles, hasMetadataXML := request.MultipartForm.File["metadata"]; len(metadataXMLFileHandles) > 1 {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "expected only one \"metadata\" parameter", request), response)
} else {
if hasProviderName {
ssoProvider.Name = providerNames[0]

ssoProvider.SAMLProvider.Name = providerNames[0]
ssoProvider.SAMLProvider.DisplayName = providerNames[0]
}

if hasMetadataXML {
if metadataXMLReader, err := metadataXMLFileHandles[0].Open(); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
return
} else {
defer metadataXMLReader.Close()

if metadataXML, err := io.ReadAll(metadataXMLReader); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
return
} else if metadata, err := samlsp.ParseMetadata(metadataXML); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
return
} else if ssoURL, err := auth.GetIDPSingleSignOnServiceURL(metadata, saml.HTTPPostBinding); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "metadata does not have a SSO service that supports HTTP POST binding", request), response)
return
} else {
ssoProvider.SAMLProvider.MetadataXML = metadataXML
ssoProvider.SAMLProvider.IssuerURI = metadata.EntityID
ssoProvider.SAMLProvider.SingleSignOnURI = ssoURL

// It's possible to update the ACS url which will be reflected in the metadataXML, we need to guarantee it is set to only what we expect if it is present
if acsUrl, err := auth.GetAssertionConsumerServiceURL(metadata, saml.HTTPPostBinding); err == nil {
if !strings.Contains(acsUrl, model.SAMLRootURIVersionMap[ssoProvider.SAMLProvider.RootURIVersion]) {
var validUri bool
for rootUriVersion, path := range model.SAMLRootURIVersionMap {
if strings.Contains(acsUrl, path) {
ssoProvider.SAMLProvider.RootURIVersion = rootUriVersion
validUri = true
break
}
}
if !validUri {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, "metadata does not have a valid ACS location", request), response)
return
}
}
}
}
}
}

if newSAMLProvider, err := s.db.UpdateSAMLIdentityProvider(request.Context(), ssoProvider); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
api.WriteBasicResponse(request.Context(), newSAMLProvider, http.StatusOK, response)
}
}
}

// Preserve old metadata endpoint
func (s ManagementResource) ServeMetadata(response http.ResponseWriter, request *http.Request) {
ssoProviderSlug := mux.Vars(request)[api.URIPathVariableSSOProviderSlug]
Expand Down
21 changes: 21 additions & 0 deletions cmd/api/src/api/v2/auth/sso.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,27 @@ func (s ManagementResource) DeleteSSOProvider(response http.ResponseWriter, requ
}
}

// UpdateSSOProvider updates a sso_provider with the matching id
func (s ManagementResource) UpdateSSOProvider(response http.ResponseWriter, request *http.Request) {
rawSSOProviderID := mux.Vars(request)[api.URIPathVariableSSOProviderID]

// Convert the incoming string url param to an int
if ssoProviderID, err := strconv.Atoi(rawSSOProviderID); err != nil {
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusBadRequest, err.Error(), request), response)
} else if ssoProvider, err := s.db.GetSSOProviderById(request.Context(), int32(ssoProviderID)); err != nil {
api.HandleDatabaseError(request, response, err)
} else {
switch ssoProvider.Type {
case model.SessionAuthProviderSAML:
s.UpdateSAMLProviderRequest(response, request, ssoProvider)
case model.SessionAuthProviderOIDC:
s.UpdateOIDCProviderRequest(response, request, ssoProvider)
default:
api.WriteErrorResponse(request.Context(), api.BuildErrorResponse(http.StatusNotImplemented, api.ErrorResponseDetailsNotImplemented, request), response)
}
}
}

func (s ManagementResource) SSOLoginHandler(response http.ResponseWriter, request *http.Request) {
ssoProviderSlug := mux.Vars(request)[api.URIPathVariableSSOProviderSlug]

Expand Down
Loading
Loading