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

Implementing Galadriel Server Management Handlers API #150

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
bfdfcc4
feat: Implementing Admin Handlers
Victorblsilveira May 5, 2023
cbdaf26
feat: Adding unit testes helpers and implemenenting get relationships…
Victorblsilveira May 8, 2023
c55c71b
Merge branch 'main' into victor/admin-handlers
Victorblsilveira May 8, 2023
664cb58
feat: Creating unit tests for relationshio request creation and impro…
Victorblsilveira May 9, 2023
d02e836
Merge remote-tracking branch 'origin/main' into victor/admin-handlers
Victorblsilveira May 9, 2023
a55e8fa
fix: Unmashaling assertion
Victorblsilveira May 9, 2023
a7edd5d
fix: Removin code duplication
Victorblsilveira May 9, 2023
c621801
fix: Organization
Victorblsilveira May 9, 2023
4b49fcc
feat: Adding more unit tests
Victorblsilveira May 10, 2023
5f3dcbd
feat: Changin return code for relationship request creation
Victorblsilveira May 10, 2023
9bc7b3a
feat: Finishing unit tests
Victorblsilveira May 11, 2023
46ca412
Update pkg/server/endpoints/management.go
Victorblsilveira May 11, 2023
02de6e6
Update pkg/server/endpoints/management.go
Victorblsilveira May 11, 2023
990cd61
Merge remote-tracking branch 'origin/main' into victor/admin-handlers
Victorblsilveira May 15, 2023
85ce235
fix: Function names
Victorblsilveira May 15, 2023
63306ec
fix: Centralizing common stuff
Victorblsilveira May 15, 2023
2b5d958
fix: Removing const_test file and unit test changes
Victorblsilveira May 15, 2023
38449f0
fix: Misstypes and const places
Victorblsilveira May 15, 2023
21b679b
fix: Refactoring trust domain lookup functions
Victorblsilveira May 15, 2023
d9b7d39
Merge branch 'HewlettPackard:main' into victor/admin-handlers
Victorblsilveira May 15, 2023
7eafbe5
fix: Unit tests failing
Victorblsilveira May 15, 2023
f085b5d
Merge remote-tracking branch 'origin/main' into victor/admin-handlers
Victorblsilveira May 16, 2023
b60cec3
fix: Removing unused values
Victorblsilveira May 16, 2023
4da954f
fix: Unit test failing
Victorblsilveira May 16, 2023
b92ffcb
fix: Unit test checking
Victorblsilveira May 16, 2023
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
22 changes: 22 additions & 0 deletions pkg/server/datastore/fakedatabase.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,28 @@ func (db *FakeDatabase) DeleteRelationship(ctx context.Context, relationshipID u
return nil
}

// WithRelationships overrides all relationships
func (db *FakeDatabase) WithRelationships(relationships []*entity.Relationship) {
Victorblsilveira marked this conversation as resolved.
Show resolved Hide resolved
db.mutex.Lock()
defer db.mutex.Unlock()

db.relationships = make(map[uuid.UUID]*entity.Relationship)
for _, r := range relationships {
db.relationships[r.ID.UUID] = r
}
}

// WithRelationships overrides all trust domains
func (db *FakeDatabase) WithTrustDomains(trustDomains []*entity.TrustDomain) {
Victorblsilveira marked this conversation as resolved.
Show resolved Hide resolved
db.mutex.Lock()
defer db.mutex.Unlock()

db.trustDomains = make(map[uuid.UUID]*entity.TrustDomain)
for _, td := range trustDomains {
db.trustDomains[td.ID.UUID] = td
}
}

func (db *FakeDatabase) SetNextError(err error) {
db.mutex.Lock()
defer db.mutex.Unlock()
Expand Down
6 changes: 3 additions & 3 deletions pkg/server/endpoints/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ func SetupMiddleware() *AuthNTestSetup {
}
}

func SetupToken(t *testing.T, ds datastore.Datastore, token string, tdID uuid.UUID) *entity.JoinToken {
td, err := spiffeid.TrustDomainFromString(testTrustDomain)
func SetupToken(t *testing.T, ds datastore.Datastore, tdID uuid.UUID, token, tdName string) *entity.JoinToken {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function doesn't exist anymore.

td, err := spiffeid.TrustDomainFromString(tdName)
assert.NoError(t, err)

jt := &entity.JoinToken{
Expand All @@ -67,7 +67,7 @@ func TestAuthenticate(t *testing.T) {
t.Run("Authorized tokens must be able to pass authn verification", func(t *testing.T) {
authnSetup := SetupMiddleware()
token := GenerateSecureToken(10)
SetupToken(t, authnSetup.FakeDatabase, token, uuid.New())
SetupToken(t, authnSetup.FakeDatabase, uuid.New(), token, testTrustDomain)

authorized, err := authnSetup.Middleware.Authenticate(token, authnSetup.EchoCtx)
assert.NoError(t, err)
Expand Down
21 changes: 13 additions & 8 deletions pkg/server/endpoints/harvester_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package endpoints
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
Expand All @@ -23,9 +24,16 @@ type HarvesterTestSetup struct {
Recorder *httptest.ResponseRecorder
}

func NewHarvesterTestSetup(method, url, body string) *HarvesterTestSetup {
func NewHarvesterTestSetup(t *testing.T, method, url string, body interface{}) *HarvesterTestSetup {
var bodyReader io.Reader
if body != nil {
bodyStr, err := json.Marshal(body)
assert.NoError(t, err)
bodyReader = strings.NewReader(string(bodyStr))
}

e := echo.New()
req := httptest.NewRequest(method, url, strings.NewReader(body))
req := httptest.NewRequest(method, url, bodyReader)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
rec := httptest.NewRecorder()
fakeDB := datastore.NewFakeDB()
Expand Down Expand Up @@ -67,18 +75,15 @@ func TestTCPBundleSync(t *testing.T) {
}

func TestTCPBundlePut(t *testing.T) {
t.Run("Succesfully register bundles for a trust domain", func(t *testing.T) {
t.Run("Successfully register bundles for a trust domain", func(t *testing.T) {
bundlePut := harvester.BundlePut{
Signature: "",
SigningCertificate: "",
TrustBundle: "a new bundle",
TrustDomain: testTrustDomain,
}

body, err := json.Marshal(bundlePut)
assert.NoError(t, err)

harvesterTestSetup := NewHarvesterTestSetup(http.MethodPut, "/trust-domain/:trustDomainName/bundles", string(body))
harvesterTestSetup := NewHarvesterTestSetup(t, http.MethodPut, "/trust-domain/:trustDomainName/bundles", bundlePut)
echoCtx := harvesterTestSetup.EchoCtx

// Creating Trust Domain
Expand All @@ -87,7 +92,7 @@ func TestTCPBundlePut(t *testing.T) {

// Creating Auth token to bypass AuthN layer
token := GenerateSecureToken(10)
jt := SetupToken(t, harvesterTestSetup.Handler.Datastore, token, td.ID.UUID)
jt := SetupToken(t, harvesterTestSetup.Handler.Datastore, td.ID.UUID, token, td.Name.String())
assert.NoError(t, err)
echoCtx.Set(tokenKey, jt)

Expand Down
204 changes: 201 additions & 3 deletions pkg/server/endpoints/management.go
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we rename this to admin.go?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm modifying the same file, can we postpone the renaming for now?

Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import (
"context"
"fmt"
"net/http"
"time"

"github.com/HewlettPackard/galadriel/pkg/common/api"
"github.com/HewlettPackard/galadriel/pkg/common/entity"
chttp "github.com/HewlettPackard/galadriel/pkg/common/http"
"github.com/HewlettPackard/galadriel/pkg/server/api/admin"
"github.com/HewlettPackard/galadriel/pkg/server/datastore"
"github.com/google/uuid"
"github.com/spiffe/go-spiffe/v2/spiffeid"

"github.com/sirupsen/logrus"

Expand All @@ -35,10 +38,32 @@ func NewAdminAPIHandlers(l logrus.FieldLogger, ds datastore.Datastore) *AdminAPI
func (h AdminAPIHandlers) GetRelationships(ctx echo.Context, params admin.GetRelationshipsParams) error {
gctx := ctx.Request().Context()

rels, err := h.Datastore.ListRelationships(gctx)
var err error
var rels []*entity.Relationship

if params.TrustDomainName != nil {
td, err := h.findTrustDomainByName(gctx, *params.TrustDomainName)
if err != nil {
err = fmt.Errorf("failed parsing trust domain name: %v", err)
Victorblsilveira marked this conversation as resolved.
Show resolved Hide resolved
return h.HandleAndLog(err, http.StatusBadRequest)
}

rels, err = h.Datastore.FindRelationshipsByTrustDomainID(gctx, td.ID.UUID)
if err != nil {
err = fmt.Errorf("failed listing relationships: %v", err)
Victorblsilveira marked this conversation as resolved.
Show resolved Hide resolved
return h.HandleAndLog(err, http.StatusInternalServerError)
}
} else {
rels, err = h.Datastore.ListRelationships(gctx)
if err != nil {
err = fmt.Errorf("failed listing relationships: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}
}

rels, err = h.filterRelationshipsByStatus(gctx, rels, params.Status)
if err != nil {
err = fmt.Errorf("failed listing relationships: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
return err
}

rels, err = h.populateTrustDomainNames(gctx, rels)
Expand Down Expand Up @@ -89,6 +114,21 @@ func (h AdminAPIHandlers) PutRelationships(ctx echo.Context) error {

// GetRelationshipsRelationshipID retrieve a specific relationship based on its id - (GET /relationships/{relationshipID})
func (h AdminAPIHandlers) GetRelationshipsRelationshipID(ctx echo.Context, relationshipID api.UUID) error {
gctx := ctx.Request().Context()

r, err := h.Datastore.FindRelationshipByID(gctx, relationshipID)
if err != nil {
err = fmt.Errorf("failed getting relationships: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}

response := api.RelationshipFromEntity(r)
err = chttp.WriteResponse(ctx, response)
if err != nil {
err = fmt.Errorf("relationship entity - %v", err.Error())
return h.HandleAndLog(err, http.StatusInternalServerError)
}

return nil
}

Expand Down Expand Up @@ -138,19 +178,154 @@ func (h AdminAPIHandlers) PutTrustDomain(ctx echo.Context) error {

// GetTrustDomainTrustDomainName retrieve a specific trust domain by its name - (GET /trust-domain/{trustDomainName})
func (h AdminAPIHandlers) GetTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.TrustDomainName) error {
gctx := ctx.Request().Context()

tdName, err := spiffeid.TrustDomainFromString(trustDomainName)
if err != nil {
err = fmt.Errorf("failed parsing trust domain name: %v", err)
return h.HandleAndLog(err, http.StatusBadRequest)
}

td, err := h.Datastore.FindTrustDomainByName(gctx, tdName)
if err != nil {
err = fmt.Errorf("failed getting trust domain: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}

response := api.TrustDomainFromEntity(td)
err = chttp.WriteResponse(ctx, response)
if err != nil {
err = fmt.Errorf("trust domain entity - %v", err.Error())
return h.HandleAndLog(err, http.StatusInternalServerError)
}

return nil
}

// PutTrustDomainTrustDomainName updates the trust domain - (PUT /trust-domain/{trustDomainName})
func (h AdminAPIHandlers) PutTrustDomainTrustDomainName(ctx echo.Context, trustDomainName api.UUID) error {
gctx := ctx.Request().Context()

reqBody := &admin.PutTrustDomainTrustDomainNameJSONRequestBody{}
err := chttp.FromBody(ctx, reqBody)
if err != nil {
err := fmt.Errorf("failed to read trust domain put body: %v", err)
return h.HandleAndLog(err, http.StatusBadRequest)
}

etd, err := reqBody.ToEntity()
if err != nil {
err := fmt.Errorf("failed to read trust domain put body: %v", err)
return h.HandleAndLog(err, http.StatusBadRequest)
}

td, err := h.Datastore.CreateOrUpdateTrustDomain(gctx, etd)
if err != nil {
err = fmt.Errorf("failed creating/updating trust domain: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}

h.Logger.Printf("Trust Bundle %v created/updated", td.Name)

response := api.TrustDomainFromEntity(td)
err = chttp.WriteResponse(ctx, response)
if err != nil {
err = fmt.Errorf("relationships - %v", err.Error())
return h.HandleAndLog(err, http.StatusInternalServerError)
}

return nil
}

// PostTrustDomainTrustDomainNameJoinToken generate a join token for the trust domain - (POST /trust-domain/{trustDomainName}/join-token)
func (h AdminAPIHandlers) PostTrustDomainTrustDomainNameJoinToken(ctx echo.Context, trustDomainName api.TrustDomainName) error {
gctx := ctx.Request().Context()

td, err := h.findTrustDomainByName(gctx, trustDomainName)
if err != nil {
return err
}

if td == nil {
err = fmt.Errorf("trust domain does not exists %v", trustDomainName)
return h.HandleAndLog(err, http.StatusBadRequest)
}

token, err := util.GenerateToken()
if err != nil {
err = fmt.Errorf("failed generating a new join token %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}

jt := &entity.JoinToken{
TrustDomainID: td.ID.UUID,
Token: token,
ExpiresAt: time.Now().Add(1 * time.Hour),
}

jt, err = h.Datastore.CreateJoinToken(gctx, jt)
if err != nil {
err = fmt.Errorf("failed creating the join token: %v", err)
return h.HandleAndLog(err, http.StatusInternalServerError)
}

h.Logger.Printf("join token successfully created for %v", td.Name)

response := admin.JoinTokenResult{
Token: uuid.MustParse(jt.Token),
}

err = chttp.WriteResponse(ctx, response)
if err != nil {
err = fmt.Errorf("relationships - %v", err.Error())
return h.HandleAndLog(err, http.StatusInternalServerError)
}

return nil
}

func (h AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomain string) (*entity.TrustDomain, error) {
tdName, err := spiffeid.TrustDomainFromString(trustDomain)
if err != nil {
err = fmt.Errorf("failed parsing trust domain name: %v", err)
return nil, h.HandleAndLog(err, http.StatusBadRequest)
}

td, err := h.Datastore.FindTrustDomainByName(ctx, tdName)
if err != nil {
err = fmt.Errorf("failed getting trust domain: %v", err)
return nil, h.HandleAndLog(err, http.StatusInternalServerError)
}

return td, nil
}

func (h AdminAPIHandlers) filterRelationshipsByStatus(
ctx context.Context,
relationships []*entity.Relationship,
status *admin.GetRelationshipsParamsStatus,
) ([]*entity.Relationship, error) {

if status != nil {
switch *status {
case admin.Denied:
return filterBy(relationships, deniedRelationFilter), nil
case admin.Approved:
return filterBy(relationships, approvedRelationFilter), nil
case admin.Pending:
return filterBy(relationships, pendingRelationFilter), nil
}

err := fmt.Errorf(
"unrecognized status filter %v, accepted values [%v, %v, %v]",
*status, admin.Denied, admin.Approved, admin.Pending,
)
return nil, h.HandleAndLog(err, http.StatusBadRequest)
} else {
return filterBy(relationships, pendingRelationFilter), nil
}
}

func (h AdminAPIHandlers) populateTrustDomainNames(ctx context.Context, relationships []*entity.Relationship) ([]*entity.Relationship, error) {
for _, r := range relationships {
tda, err := h.Datastore.FindTrustDomainByID(ctx, r.TrustDomainAID)
Expand Down Expand Up @@ -184,3 +359,26 @@ func (h AdminAPIHandlers) HandleAndLog(err error, code int) error {
h.Logger.Errorf(errMsg)
return echo.NewHTTPError(code, err.Error())
}

func deniedRelationFilter(e *entity.Relationship) bool {
return !e.TrustDomainAConsent || !e.TrustDomainBConsent
}

func approvedRelationFilter(e *entity.Relationship) bool {
return e.TrustDomainAConsent && e.TrustDomainBConsent
}

func pendingRelationFilter(e *entity.Relationship) bool {
return !e.TrustDomainAConsent || !e.TrustDomainBConsent
}

// filterBy will generate a new slice with the elements that matched
func filterBy[E any](s []E, match func(E) bool) []E {
filtered := []E{}
for _, e := range s {
if match(e) {
filtered = append(filtered, e)
}
}
return filtered
}
Loading