From 00f12a9e13f81ce66857aea54425e2d3a3622444 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Tue, 16 May 2023 17:29:09 -0300 Subject: [PATCH 01/12] Adding methods to the CLI --- cmd/server/util/client.go | 270 +++++++++++++++++++++++++++++--------- 1 file changed, 206 insertions(+), 64 deletions(-) diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 3586df62..9bd6669f 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -11,6 +11,7 @@ import ( "net/http" "github.com/HewlettPackard/galadriel/pkg/common/entity" + "github.com/google/uuid" "github.com/spiffe/go-spiffe/v2/spiffeid" ) @@ -23,20 +24,22 @@ const ( ) var ( - createTrustDomainURL = fmt.Sprintf(localURL, "createTrustDomain") - listTrustDomainsURL = fmt.Sprintf(localURL, "listTrustDomains") - createRelationshipURL = fmt.Sprintf(localURL, "createRelationship") - listRelationshipsURL = fmt.Sprintf(localURL, "listRelationships") - joinTokenURL = fmt.Sprintf(localURL, "trust-domain/%s/join-token") + trustDomainByNameURL = fmt.Sprintf(localURL, "trust-domain/%s") + getJoinTokenURL = fmt.Sprintf(localURL, "trust-domain/%s/join-token") + trustDomainURL = fmt.Sprintf(localURL, "trust-domain") + relationshipsURL = fmt.Sprintf(localURL, "relationships") + relationshipsByIDURL = fmt.Sprintf(localURL, "relationships/%s") ) // ServerLocalClient represents a local client of the Galadriel Server. type ServerLocalClient interface { - CreateTrustDomain(m *entity.TrustDomain) error - ListTrustDomains() ([]*entity.TrustDomain, error) - CreateRelationship(r *entity.Relationship) error - ListRelationships() ([]*entity.Relationship, error) - GenerateJoinToken(trustDomain spiffeid.TrustDomain) (string, error) + CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) + GetTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) + UpdateTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) + CreateRelationship(ctx context.Context, r *entity.Relationship) (*entity.Relationship, error) + GetRelationshipByID(ctx context.Context, id uuid.UUID) (*entity.Relationship, error) + GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) + GetJoinToken(ctx context.Context, trustDomain spiffeid.TrustDomain) (*entity.JoinToken, error) } // TODO: improve this adding options for the transport, dialcontext, and http.Client. @@ -50,122 +53,261 @@ func NewServerClient(socketPath string) ServerLocalClient { Transport: t, } - return serverClient{client: c} + return &serverClient{client: c} } type serverClient struct { client *http.Client } -func (c serverClient) CreateTrustDomain(m *entity.TrustDomain) error { - trustDomainBytes, err := json.Marshal(m) +func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) { + trustDomainNameBytes, err := trustDomainName.MarshalText() if err != nil { - return err + return nil, fmt.Errorf("failed to marshal trust domain: %v", err) } - r, err := c.client.Post(createTrustDomainURL, contentType, bytes.NewReader(trustDomainBytes)) + getTrustDomainByNameURL := fmt.Sprintf(trustDomainByNameURL, trustDomainName) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, getTrustDomainByNameURL, bytes.NewReader(trustDomainNameBytes)) if err != nil { - return err + return nil, fmt.Errorf("failed to create request: %v", err) } - defer r.Body.Close() - body, err := io.ReadAll(r.Body) + res, err := c.client.Do(req) if err != nil { - return err + return nil, fmt.Errorf("failed to send request: %v", err) + } + defer res.Body.Close() + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) + } + + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) } - if r.StatusCode != 200 { - return errors.New(string(body)) + var trustDomain *entity.TrustDomain + if err = json.Unmarshal(body, &trustDomain); err != nil { + return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) } - return nil + return trustDomain, nil } -func (c serverClient) ListTrustDomains() ([]*entity.TrustDomain, error) { - r, err := c.client.Get(listTrustDomainsURL) +func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) { + trustDomainNameBytes, err := trustDomainName.MarshalText() if err != nil { - return nil, err + return nil, fmt.Errorf("failed to marshal trust domain: %v", err) } - defer r.Body.Close() - b, err := io.ReadAll(r.Body) + updateTrustDomainByNameURL := fmt.Sprintf(trustDomainByNameURL, trustDomainName) + + req, err := http.NewRequestWithContext(ctx, http.MethodPut, updateTrustDomainByNameURL, bytes.NewReader(trustDomainNameBytes)) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to create request: %v", err) } - if r.StatusCode != 200 { - return nil, errors.New(string(b)) + res, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %v", err) } + defer res.Body.Close() - var trustDomains []*entity.TrustDomain - if err = json.Unmarshal(b, &trustDomains); err != nil { - return nil, err + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) } - return trustDomains, nil + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + } + + var trustDomain *entity.TrustDomain + if err = json.Unmarshal(body, &trustDomain); err != nil { + return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + } + + return trustDomain, nil } -func (c serverClient) CreateRelationship(rel *entity.Relationship) error { - relBytes, err := json.Marshal(rel) +func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) { + trustDomainBytes, err := json.Marshal(trustDomain) if err != nil { - return err + return nil, fmt.Errorf("failed to marshal trust domain: %v", err) } - r, err := c.client.Post(createRelationshipURL, contentType, bytes.NewReader(relBytes)) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, trustDomainURL, bytes.NewReader(trustDomainBytes)) if err != nil { - return fmt.Errorf("failed to create relationship: %v", err) + return nil, fmt.Errorf("failed to create request: %v", err) } - defer r.Body.Close() - b, err := io.ReadAll(r.Body) + res, err := c.client.Do(req) if err != nil { - return err + return nil, fmt.Errorf("failed to send request: %v", err) } + defer res.Body.Close() - if r.StatusCode != 200 { - return errors.New(string(b)) + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) } - return nil + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + } + + var trustDomainRes *entity.TrustDomain + if err = json.Unmarshal(body, &trustDomainRes); err != nil { + return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + } + + return trustDomain, nil } -func (c serverClient) ListRelationships() ([]*entity.Relationship, error) { - r, err := c.client.Get(listRelationshipsURL) +func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relationship) (*entity.Relationship, error) { + relBytes, err := json.Marshal(rel) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to marshal Relationship: %v", err) } - defer r.Body.Close() - b, err := io.ReadAll(r.Body) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, relationshipsURL, bytes.NewReader(relBytes)) + if err != nil { + return nil, fmt.Errorf("failed to create request: %v", err) + } + + res, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %v", err) + } + defer res.Body.Close() + body, err := io.ReadAll(req.Body) if err != nil { return nil, err } - if r.StatusCode != 200 { - return nil, errors.New(string(b)) + if res.StatusCode != http.StatusOK { + return nil, errors.New(string(body)) } - var rels []*entity.Relationship - if err = json.Unmarshal(b, &rels); err != nil { - return nil, err + var relationships *entity.Relationship + if err = json.Unmarshal(body, &relationships); err != nil { + return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) } - return rels, nil + return relationships, nil } +func (c *serverClient) GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) { + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, relationshipsURL, bytes.NewReader()) + if err != nil { + return nil, fmt.Errorf("failed to create request: %v", err) + } -func (c serverClient) GenerateJoinToken(td spiffeid.TrustDomain) (string, error) { - joinTokenURL := fmt.Sprintf(joinTokenURL, td) - r, err := c.client.Get(joinTokenURL) + res, err := c.client.Do(req) if err != nil { - return "", err + return nil, fmt.Errorf("failed to send request: %v", err) } - defer r.Body.Close() + defer res.Body.Close() - body, err := io.ReadAll(r.Body) + body, err := io.ReadAll(req.Body) if err != nil { - return "", err + return nil, fmt.Errorf("failed to read response body: %v", err) + } + + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + } + + var relationship *entity.Relationship + if err = json.Unmarshal(body, &relationship); err != nil { + return nil, fmt.Errorf("failed to unmarshal relationship: %v", err) } - return string(body), nil + return relationship, nil } + +func (c *serverClient) GetRelationshipByID(ctx context.Context, id uuid.UUID) (*entity.Relationship, error) { + relationshipsByIDURL = fmt.Sprintf(relationshipsByIDURL, id) + + req, err := http.NewRequestWithContext(ctx, http.MethodPut, relationshipsByIDURL, bytes.NewReader(id[:])) + if err != nil { + return nil, fmt.Errorf("failed to create request: %v", err) + } + + res, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %v", err) + } + defer res.Body.Close() + + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) + } + + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + } + + var relationship *entity.Relationship + if err = json.Unmarshal(body, &relationship); err != nil { + return nil, fmt.Errorf("failed to unmarshal relationship: %v", err) + } + + return relationship, nil +} + +func (c *serverClient) GetJoinToken(ctx context.Context, trustDomain spiffeid.TrustDomain) (*entity.JoinToken, error) { + trustDomainBytes, err := trustDomain.MarshalText() + if err != nil { + return nil, fmt.Errorf("failed to marshal trust domain: %v", err) + } + + getJoinTokenURL = fmt.Sprintf(getJoinTokenURL, trustDomain) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, getJoinTokenURL, bytes.NewReader(trustDomainBytes)) + if err != nil { + return nil, fmt.Errorf("failed to create request: %v", err) + } + + res, err := c.client.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send request: %v", err) + } + defer res.Body.Close() + + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %v", err) + } + + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + } + + var joinToken *entity.JoinToken + if err = json.Unmarshal(body, &joinToken); err != nil { + return nil, fmt.Errorf("failed to unmarshal join token: %v", err) + } + + return joinToken, nil +} + +// func (c clientServer) GenerateJoinToken(td spiffeid.TrustDomain) (string, error) { +// joinTokenURL := fmt.Sprintf(joinTokenURL, td) +// r, err := c.client.Get(joinTokenURL) +// if err != nil { +// return "", err +// } +// defer r.Body.Close() + +// body, err := io.ReadAll(r.Body) +// if err != nil { +// return "", err +// } + +// return string(body), nil +// } From c3997815438463c131294a17c8de0e8e9fd98921 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Wed, 17 May 2023 14:57:59 -0300 Subject: [PATCH 02/12] updating CLI to use the new generated API spec --- cmd/server/cli/create.go | 9 +- cmd/server/cli/generate.go | 13 +-- cmd/server/cli/list.go | 85 ++++++++--------- cmd/server/util/client.go | 153 ++++++------------------------ pkg/server/api/admin/admin.gen.go | 74 +++++++-------- pkg/server/api/admin/admin.yaml | 2 +- 6 files changed, 117 insertions(+), 219 deletions(-) diff --git a/cmd/server/cli/create.go b/cmd/server/cli/create.go index 65647296..fe556f50 100644 --- a/cmd/server/cli/create.go +++ b/cmd/server/cli/create.go @@ -1,6 +1,7 @@ package cli import ( + "context" "fmt" "github.com/HewlettPackard/galadriel/cmd/server/util" @@ -32,7 +33,8 @@ var createTrustDomainCmd = &cobra.Command{ c := util.NewServerClient(defaultSocketPath) - if err := c.CreateTrustDomain(&entity.TrustDomain{Name: trustDomain}); err != nil { + _, err = c.CreateTrustDomain(context.Background(), &entity.TrustDomain{Name: trustDomain}) + if err != nil { return err } @@ -69,10 +71,11 @@ var createRelationshipCmd = &cobra.Command{ return err } - if err := c.CreateRelationship(&entity.Relationship{ + _, err = c.CreateRelationship(context.Background(), &entity.Relationship{ TrustDomainAName: trustDomain1, TrustDomainBName: trustDomain2, - }); err != nil { + }) + if err != nil { return err } diff --git a/cmd/server/cli/generate.go b/cmd/server/cli/generate.go index 6124af6d..4c4182d1 100644 --- a/cmd/server/cli/generate.go +++ b/cmd/server/cli/generate.go @@ -1,12 +1,12 @@ package cli import ( + "context" "fmt" "strings" "github.com/HewlettPackard/galadriel/cmd/server/util" "github.com/spf13/cobra" - "github.com/spiffe/go-spiffe/v2/spiffeid" ) var generateCmd = &cobra.Command{ @@ -20,22 +20,17 @@ var tokenCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { c := util.NewServerClient(defaultSocketPath) - td, err := cmd.Flags().GetString("trustDomain") + trustDomain, err := cmd.Flags().GetString("trustDomain") if err != nil { return fmt.Errorf("cannot get trust domain flag: %v", err) } - trustDomain, err := spiffeid.TrustDomainFromString(td) + joinToken, err := c.GetJoinToken(context.Background(), trustDomain) if err != nil { return err } - joinToken, err := c.GenerateJoinToken(trustDomain) - if err != nil { - return err - } - - fmt.Printf("Token: %s", strings.ReplaceAll(joinToken, "\"", "")) + fmt.Printf("Token: %s", strings.ReplaceAll(joinToken.Token, "\"", "")) return nil }, } diff --git a/cmd/server/cli/list.go b/cmd/server/cli/list.go index 48e646b1..870a4dbf 100644 --- a/cmd/server/cli/list.go +++ b/cmd/server/cli/list.go @@ -1,9 +1,6 @@ package cli import ( - "fmt" - - "github.com/HewlettPackard/galadriel/cmd/server/util" "github.com/spf13/cobra" ) @@ -13,56 +10,56 @@ var listCmd = &cobra.Command{ } var listTrustDomainCmd = &cobra.Command{ - Use: "trustdomains", - Args: cobra.ExactArgs(0), - Short: "Lists all the Trust Domains.", - RunE: func(cmd *cobra.Command, args []string) error { - c := util.NewServerClient(defaultSocketPath) - trustDomains, err := c.ListTrustDomains() - if err != nil { - return err - } + // Use: "trustdomains", + // Args: cobra.ExactArgs(0), + // Short: "Lists all the Trust Domains.", + // RunE: func(cmd *cobra.Command, args []string) error { + // c := util.NewServerClient(defaultSocketPath) + // trustDomains, err := c.ListTrustDomains() + // if err != nil { + // return err + // } - if len(trustDomains) == 0 { - fmt.Println("No trust domains found") - return nil - } + // if len(trustDomains) == 0 { + // fmt.Println("No trust domains found") + // return nil + // } - for _, m := range trustDomains { - fmt.Printf("ID: %s\n", m.ID.UUID) - fmt.Printf("Trust Domain: %s\n", m.Name) - fmt.Println() - } + // for _, m := range trustDomains { + // fmt.Printf("ID: %s\n", m.ID.UUID) + // fmt.Printf("Trust Domain: %s\n", m.Name) + // fmt.Println() + // } - return nil - }, + // return nil + // }, } var listRelationshipsCmd = &cobra.Command{ - Use: "relationships", - Args: cobra.ExactArgs(0), - Short: "Lists all the relationships.", - RunE: func(cmd *cobra.Command, args []string) error { - c := util.NewServerClient(defaultSocketPath) - rels, err := c.ListRelationships() - if err != nil { - return err - } + // Use: "relationships", + // Args: cobra.ExactArgs(0), + // Short: "Lists all the relationships.", + // RunE: func(cmd *cobra.Command, args []string) error { + // c := util.NewServerClient(defaultSocketPath) + // rels, err := c.GetRelationships(context.Background(), "status", "tdName") + // if err != nil { + // return err + // } - if len(rels) == 0 { - fmt.Println("No relationships found") - return nil - } + // if len(rels) == 0 { + // fmt.Println("No relationships found") + // return nil + // } - for _, r := range rels { - fmt.Printf("ID: %s\n", r.ID.UUID) - fmt.Printf("Trust Domain A: %s\n", r.TrustDomainAName.String()) - fmt.Printf("Trust Domain B: %s\n", r.TrustDomainBName.String()) - fmt.Println() - } + // for _, r := range rels { + // fmt.Printf("ID: %s\n", r.ID.UUID) + // fmt.Printf("Trust Domain A: %s\n", r.TrustDomainAName.String()) + // fmt.Printf("Trust Domain B: %s\n", r.TrustDomainBName.String()) + // fmt.Println() + // } - return nil - }, + // return nil + // }, } func init() { diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 654b5037..4885a448 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -7,72 +7,39 @@ import ( "errors" "fmt" "io" - "net" "net/http" + "github.com/HewlettPackard/galadriel/pkg/common/api" "github.com/HewlettPackard/galadriel/pkg/common/entity" + "github.com/HewlettPackard/galadriel/pkg/server/api/admin" "github.com/google/uuid" - "github.com/spiffe/go-spiffe/v2/spiffeid" ) -// URL pattern to make http calls on local Unix domain socket, -// the Host is required for the URL, but it's not relevant - const ( - localURL = "http://local/%s" - contentType = "application/json" -) - -var ( - trustDomainByNameURL = fmt.Sprintf(localURL, "trust-domain/%s") - getJoinTokenURL = fmt.Sprintf(localURL, "trust-domain/%s/join-token") - trustDomainURL = fmt.Sprintf(localURL, "trust-domain") - relationshipsURL = fmt.Sprintf(localURL, "relationships") - relationshipsByIDURL = fmt.Sprintf(localURL, "relationships/%s") + jsonContentType = "application/json" ) // ServerLocalClient represents a local client of the Galadriel Server. type ServerLocalClient interface { CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) - GetTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) - UpdateTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) + GetTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) + UpdateTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) CreateRelationship(ctx context.Context, r *entity.Relationship) (*entity.Relationship, error) - GetRelationshipByID(ctx context.Context, id uuid.UUID) (*entity.Relationship, error) + GetRelationshipByID(ctx context.Context, relID uuid.UUID) (*entity.Relationship, error) GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) - GetJoinToken(ctx context.Context, trustDomain spiffeid.TrustDomain) (*entity.JoinToken, error) + GetJoinToken(ctx context.Context, trustDomain string) (*entity.JoinToken, error) } -// TODO: improve this adding options for the transport, dialcontext, and http.Client. func NewServerClient(socketPath string) ServerLocalClient { - t := &http.Transport{ - DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { - var d net.Dialer - return d.DialContext(ctx, "unix", socketPath) - }} - c := &http.Client{ - Transport: t, - } - - return &serverClient{client: c} + return &serverClient{client: &admin.Client{Server: socketPath}} } type serverClient struct { - client *http.Client + client *admin.Client } -func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) { - trustDomainBytes, err := trustDomainName.MarshalText() - if err != nil { - return nil, fmt.Errorf("failed to marshal trust domain: %v", err) - } - - req, err := http.NewRequest(http.MethodPut, trustDomainURL, bytes.NewReader(trustDomainBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - req.Header.Set("Content-Type", "application/json") - res, err := c.client.Do(req) +func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) { + res, err := c.client.GetTrustDomainByName(ctx, trustDomainName) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } @@ -95,26 +62,14 @@ func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName return trustDomain, nil } -func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainName spiffeid.TrustDomain) (*entity.TrustDomain, error) { - trustDomainNameBytes, err := trustDomainName.MarshalText() - if err != nil { - return nil, fmt.Errorf("failed to marshal trust domain: %v", err) - } - - updateTrustDomainByNameURL := fmt.Sprintf(trustDomainByNameURL, trustDomainName) - - req, err := http.NewRequestWithContext(ctx, http.MethodPut, updateTrustDomainByNameURL, bytes.NewReader(trustDomainNameBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - res, err := c.client.Do(req) +func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) { + res, err := c.client.PutTrustDomainByNameWithBody(ctx, trustDomainName, jsonContentType, bytes.NewReader([]byte(trustDomainName))) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } defer res.Body.Close() - body, err := io.ReadAll(req.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %v", err) } @@ -132,23 +87,15 @@ func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainN } func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) { - trustDomainBytes, err := json.Marshal(trustDomain) - if err != nil { - return nil, fmt.Errorf("failed to marshal trust domain: %v", err) - } - - req, err := http.NewRequestWithContext(ctx, http.MethodPut, trustDomainURL, bytes.NewReader(trustDomainBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } + payload := admin.PutTrustDomainJSONRequestBody{Name: trustDomain.Name.String()} - res, err := c.client.Do(req) + res, err := c.client.PutTrustDomain(ctx, payload) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } defer res.Body.Close() - body, err := io.ReadAll(req.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %v", err) } @@ -171,18 +118,13 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat return nil, fmt.Errorf("failed to marshal Relationship: %v", err) } - req, err := http.NewRequestWithContext(ctx, http.MethodPut, relationshipsURL, bytes.NewReader(relBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - res, err := c.client.Do(req) + res, err := c.client.PutRelationshipWithBody(ctx, jsonContentType, bytes.NewReader(relBytes)) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } defer res.Body.Close() - body, err := io.ReadAll(req.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, err } @@ -193,25 +135,21 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat var relationships *entity.Relationship if err = json.Unmarshal(body, &relationships); err != nil { - return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + return nil, fmt.Errorf("failed to unmarshal relationships: %v", err) } return relationships, nil } func (c *serverClient) GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) { + payload := &admin.GetRelationshipsParams{Status: (*api.ConsentStatus)(&consentStatus), TrustDomainName: &trustDomain} - req, err := http.NewRequestWithContext(ctx, http.MethodGet, relationshipsURL, bytes.NewReader([]byte(consentStatus))) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - res, err := c.client.Do(req) + res, err := c.client.GetRelationships(ctx, payload) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } defer res.Body.Close() - body, err := io.ReadAll(req.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %v", err) } @@ -228,21 +166,14 @@ func (c *serverClient) GetRelationships(ctx context.Context, consentStatus strin return relationship, nil } -func (c *serverClient) GetRelationshipByID(ctx context.Context, id uuid.UUID) (*entity.Relationship, error) { - relationshipsByIDURL = fmt.Sprintf(relationshipsByIDURL, id) - - req, err := http.NewRequestWithContext(ctx, http.MethodPut, relationshipsByIDURL, bytes.NewReader(id[:])) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - res, err := c.client.Do(req) +func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) (*entity.Relationship, error) { + res, err := c.client.GetRelationshipByID(ctx, relID) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } defer res.Body.Close() - body, err := io.ReadAll(req.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf("failed to read response body: %v", err) } @@ -259,20 +190,8 @@ func (c *serverClient) GetRelationshipByID(ctx context.Context, id uuid.UUID) (* return relationship, nil } -func (c *serverClient) GetJoinToken(ctx context.Context, trustDomain spiffeid.TrustDomain) (*entity.JoinToken, error) { - trustDomainBytes, err := trustDomain.MarshalText() - if err != nil { - return nil, fmt.Errorf("failed to marshal trust domain: %v", err) - } - - getJoinTokenURL = fmt.Sprintf(getJoinTokenURL, trustDomain) - - req, err := http.NewRequestWithContext(ctx, http.MethodGet, getJoinTokenURL, bytes.NewReader(trustDomainBytes)) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - res, err := c.client.Do(req) +func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName string) (*entity.JoinToken, error) { + res, err := c.client.GetJoinToken(ctx, trustDomainName) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } @@ -294,19 +213,3 @@ func (c *serverClient) GetJoinToken(ctx context.Context, trustDomain spiffeid.Tr return joinToken, nil } - -// func (c clientServer) GenerateJoinToken(td spiffeid.TrustDomain) (string, error) { -// joinTokenURL := fmt.Sprintf(joinTokenURL, td) -// r, err := c.client.Get(joinTokenURL) -// if err != nil { -// return "", err -// } -// defer r.Body.Close() - -// body, err := io.ReadAll(r.Body) -// if err != nil { -// return "", err -// } - -// return string(body), nil -// } diff --git a/pkg/server/api/admin/admin.gen.go b/pkg/server/api/admin/admin.gen.go index 36e960ea..db292bb8 100644 --- a/pkg/server/api/admin/admin.gen.go +++ b/pkg/server/api/admin/admin.gen.go @@ -153,9 +153,9 @@ type ClientInterface interface { GetTrustDomainByName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) // PutTrustDomainByName request with any body - PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.TrustDomainName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) // GetJoinToken request GetJoinToken(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -245,7 +245,7 @@ func (c *Client) GetTrustDomainByName(ctx context.Context, trustDomainName exter return c.Client.Do(req) } -func (c *Client) PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { +func (c *Client) PutTrustDomainByNameWithBody(ctx context.Context, trustDomainName externalRef0.TrustDomainName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewPutTrustDomainByNameRequestWithBody(c.Server, trustDomainName, contentType, body) if err != nil { return nil, err @@ -257,7 +257,7 @@ func (c *Client) PutTrustDomainByNameWithBody(ctx context.Context, trustDomainNa return c.Client.Do(req) } -func (c *Client) PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { +func (c *Client) PutTrustDomainByName(ctx context.Context, trustDomainName externalRef0.TrustDomainName, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewPutTrustDomainByNameRequest(c.Server, trustDomainName, body) if err != nil { return nil, err @@ -493,7 +493,7 @@ func NewGetTrustDomainByNameRequest(server string, trustDomainName externalRef0. } // NewPutTrustDomainByNameRequest calls the generic PutTrustDomainByName builder with application/json body -func NewPutTrustDomainByNameRequest(server string, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody) (*http.Request, error) { +func NewPutTrustDomainByNameRequest(server string, trustDomainName externalRef0.TrustDomainName, body PutTrustDomainByNameJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { @@ -504,7 +504,7 @@ func NewPutTrustDomainByNameRequest(server string, trustDomainName externalRef0. } // NewPutTrustDomainByNameRequestWithBody generates requests for PutTrustDomainByName with any type of body -func NewPutTrustDomainByNameRequestWithBody(server string, trustDomainName externalRef0.UUID, contentType string, body io.Reader) (*http.Request, error) { +func NewPutTrustDomainByNameRequestWithBody(server string, trustDomainName externalRef0.TrustDomainName, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -636,9 +636,9 @@ type ClientWithResponsesInterface interface { GetTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetTrustDomainByNameResponse, error) // PutTrustDomainByName request with any body - PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) + PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) - PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) + PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) // GetJoinToken request GetJoinTokenWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, reqEditors ...RequestEditorFn) (*GetJoinTokenResponse, error) @@ -867,7 +867,7 @@ func (c *ClientWithResponses) GetTrustDomainByNameWithResponse(ctx context.Conte } // PutTrustDomainByNameWithBodyWithResponse request with arbitrary body returning *PutTrustDomainByNameResponse -func (c *ClientWithResponses) PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { +func (c *ClientWithResponses) PutTrustDomainByNameWithBodyWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { rsp, err := c.PutTrustDomainByNameWithBody(ctx, trustDomainName, contentType, body, reqEditors...) if err != nil { return nil, err @@ -875,7 +875,7 @@ func (c *ClientWithResponses) PutTrustDomainByNameWithBodyWithResponse(ctx conte return ParsePutTrustDomainByNameResponse(rsp) } -func (c *ClientWithResponses) PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.UUID, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { +func (c *ClientWithResponses) PutTrustDomainByNameWithResponse(ctx context.Context, trustDomainName externalRef0.TrustDomainName, body PutTrustDomainByNameJSONRequestBody, reqEditors ...RequestEditorFn) (*PutTrustDomainByNameResponse, error) { rsp, err := c.PutTrustDomainByName(ctx, trustDomainName, body, reqEditors...) if err != nil { return nil, err @@ -1142,7 +1142,7 @@ type ServerInterface interface { GetTrustDomainByName(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error // Update a specific trust domain // (PUT /trust-domain/{trustDomainName}) - PutTrustDomainByName(ctx echo.Context, trustDomainName externalRef0.UUID) error + PutTrustDomainByName(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error // Get a join token for a specific Trust Domain // (GET /trust-domain/{trustDomainName}/join-token) GetJoinToken(ctx echo.Context, trustDomainName externalRef0.TrustDomainName) error @@ -1232,7 +1232,7 @@ func (w *ServerInterfaceWrapper) GetTrustDomainByName(ctx echo.Context) error { func (w *ServerInterfaceWrapper) PutTrustDomainByName(ctx echo.Context) error { var err error // ------------- Path parameter "trustDomainName" ------------- - var trustDomainName externalRef0.UUID + var trustDomainName externalRef0.TrustDomainName err = runtime.BindStyledParameterWithLocation("simple", false, "trustDomainName", runtime.ParamLocationPath, ctx.Param("trustDomainName"), &trustDomainName) if err != nil { @@ -1301,31 +1301,31 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerS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7j1Vzy", + "XXexWDjEPHW4mLnlq9J9N359dn51Zvcdz5mrxLilqDLQbDk0ChPKjC82+iMFpq8GxtYtCFlE0XM8p9cz", + "lSQFRlKqMXY8Z4ANSnNDbVdUjk1zZwYmrZr/5sE41A6Auqwt1FsIkoACIbF/3dAIru6KpGlsUCR4gggq", + "NFNQFqUgdDIVvQULa3ixj79kIJarSqLhN22R1XFqazRTudV0rXpYtltUDU11Nb2txYlVH1H7nrfXeEoV", + "JHKX2Vr3nq9lQ4Qgy7bZ9SoLApBSD4FrkAsNrOfnNnPrQNzVoG0G3ixJiFgWFEGiwRFFZpoduM6dSW7h", + "NGth2UVWYxkuShlIdcLD5aPN9W2NYl6vm0pkkH8ndt0hezaIXptDGZEaTqjMMZqCWgAwpBa8JtKHgMyt", + "RgVx76p/x6d515Jyshyf7qoq41PEI3OwNmhiVKxr2kbEdTdwE92umi479cnPRwatV7I+ymqU2AG4qY92", + "uJ437tNyvdI+hZQbXV1eyrgGVO8prLXhVKgrfARoRmFYhUZVuswKNFWNtiDj3jXOsQelWIntZFmeeg9q", + "sXaMl01/iwy3z9Jv0+Hjn63fgfTzKLIb7FYX+f1IkD5plWgvET86cT6Y+fopSob7iVNmrz8831c9Nh+d", + "96HY+U9WNZpf95+7cmiskMEKRVxU6VDDfUMH7TAqcJsYZ6WZLgvg6nN0zAMSz7lUjlyQ2QyEQ7lLUure", + "DrBOarllE+8RKj6ZNT0oca7d3R7VRvVGlUrT+60/sZgnuiMkKytvICyTWusQH2xtS1fqjc62L5ctVisJ", + "n/KMhUjxxoDrbAxUkp1P8n8CAAD//xYGDe3KHAAA", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/pkg/server/api/admin/admin.yaml b/pkg/server/api/admin/admin.yaml index 8a721479..e5368001 100644 --- a/pkg/server/api/admin/admin.yaml +++ b/pkg/server/api/admin/admin.yaml @@ -54,7 +54,7 @@ paths: description: Trust Domain name required: true schema: - $ref: '../../../common/api/schemas.yaml#/components/schemas/UUID' + $ref: '../../../common/api/schemas.yaml#/components/schemas/TrustDomainName' requestBody: content: application/json: From 7ba186e9c455c41d19398a5217834940114b30f1 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 16:20:28 -0300 Subject: [PATCH 03/12] adding create comand and generate jointoken --- cmd/server/cli/create.go | 31 ++++++++------ cmd/server/cli/generate.go | 10 +++-- cmd/server/cli/generate_test.go | 17 ++++++++ cmd/server/cli/list.go | 1 + cmd/server/cli/run_test.go | 44 ++++++++++++++++++++ cmd/server/util/client.go | 33 ++++++++++----- pkg/server/api/admin/admin.gen.go | 54 ++++++++++++------------- pkg/server/api/admin/admin.yaml | 12 +++--- pkg/server/api/admin/helper.go | 4 +- pkg/server/api/admin/helper_test.go | 14 ++++--- pkg/server/endpoints/management.go | 25 +++++++----- pkg/server/endpoints/management_test.go | 14 +++---- 12 files changed, 176 insertions(+), 83 deletions(-) create mode 100644 cmd/server/cli/generate_test.go diff --git a/cmd/server/cli/create.go b/cmd/server/cli/create.go index fe556f50..c50385c3 100644 --- a/cmd/server/cli/create.go +++ b/cmd/server/cli/create.go @@ -11,7 +11,7 @@ import ( ) var createCmd = &cobra.Command{ - Use: "create ", + Use: "create ", Short: "Allows creation of trust domains and relationships", } @@ -28,17 +28,20 @@ var createTrustDomainCmd = &cobra.Command{ trustDomain, err := spiffeid.TrustDomainFromString(td) if err != nil { - return err + return fmt.Errorf("failed parsing trust domain: %v", err) } - c := util.NewServerClient(defaultSocketPath) + client, err := util.NewServerClient(defaultSocketPath) + if err != nil { + return err + } - _, err = c.CreateTrustDomain(context.Background(), &entity.TrustDomain{Name: trustDomain}) + trustDomainRes, err := client.CreateTrustDomain(context.Background(), &entity.TrustDomain{Name: trustDomain}) if err != nil { return err } - fmt.Printf("Trust Domain created: %q\n", trustDomain.String()) + fmt.Printf("Trust Domain created: %s\n", trustDomainRes.Name.String()) return nil }, @@ -50,7 +53,10 @@ var createRelationshipCmd = &cobra.Command{ Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - c := util.NewServerClient(defaultSocketPath) + client, err := util.NewServerClient(defaultSocketPath) + if err != nil { + return err + } tdA, err := cmd.Flags().GetString("trustDomainA") if err != nil { @@ -59,19 +65,20 @@ var createRelationshipCmd = &cobra.Command{ trustDomain1, err := spiffeid.TrustDomainFromString(tdA) if err != nil { - return err + return fmt.Errorf("failed parsing trust domain: %v", err) } - tdb, err := cmd.Flags().GetString("trustDomainB") + tdB, err := cmd.Flags().GetString("trustDomainB") if err != nil { return fmt.Errorf("cannot get trust domain B flag: %v", err) } - trustDomain2, err := spiffeid.TrustDomainFromString(tdb) + + trustDomain2, err := spiffeid.TrustDomainFromString(tdB) if err != nil { - return err + return fmt.Errorf("failed parsing trust domain: %v", err) } - _, err = c.CreateRelationship(context.Background(), &entity.Relationship{ + _, err = client.CreateRelationship(context.Background(), &entity.Relationship{ TrustDomainAName: trustDomain1, TrustDomainBName: trustDomain2, }) @@ -79,7 +86,7 @@ var createRelationshipCmd = &cobra.Command{ return err } - fmt.Printf("Relationship created between trust domain %q and trust domain %q\n", trustDomain1.String(), trustDomain2.String()) + fmt.Printf("Relationship created between trust domains %s and %s\n", tdA, tdB) return nil }, } diff --git a/cmd/server/cli/generate.go b/cmd/server/cli/generate.go index 4c4182d1..9dcdbdf4 100644 --- a/cmd/server/cli/generate.go +++ b/cmd/server/cli/generate.go @@ -3,7 +3,6 @@ package cli import ( "context" "fmt" - "strings" "github.com/HewlettPackard/galadriel/cmd/server/util" "github.com/spf13/cobra" @@ -18,19 +17,22 @@ var tokenCmd = &cobra.Command{ Args: cobra.ExactArgs(0), Short: "Generates a join token for provided trust domain", RunE: func(cmd *cobra.Command, args []string) error { - c := util.NewServerClient(defaultSocketPath) + client, err := util.NewServerClient(defaultSocketPath) + if err != nil { + return err + } trustDomain, err := cmd.Flags().GetString("trustDomain") if err != nil { return fmt.Errorf("cannot get trust domain flag: %v", err) } - joinToken, err := c.GetJoinToken(context.Background(), trustDomain) + joinToken, err := client.GetJoinToken(context.Background(), trustDomain) if err != nil { return err } - fmt.Printf("Token: %s", strings.ReplaceAll(joinToken.Token, "\"", "")) + fmt.Printf("Token: %s\n", joinToken.Token) return nil }, } diff --git a/cmd/server/cli/generate_test.go b/cmd/server/cli/generate_test.go new file mode 100644 index 00000000..631e60c7 --- /dev/null +++ b/cmd/server/cli/generate_test.go @@ -0,0 +1,17 @@ +package cli + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +func TestTokenCmd(t *testing.T) { + cmd := &cobra.Command{} + cmd.Flags().String("trustDomain", "test.com", "") + + err := cmd.Execute() + + assert.Nil(t, err) +} diff --git a/cmd/server/cli/list.go b/cmd/server/cli/list.go index 870a4dbf..04a097f6 100644 --- a/cmd/server/cli/list.go +++ b/cmd/server/cli/list.go @@ -9,6 +9,7 @@ var listCmd = &cobra.Command{ Short: "Lists trust domains and relationships", } +// TODO: Implement Get Relationships and Trust Domains var listTrustDomainCmd = &cobra.Command{ // Use: "trustdomains", // Args: cobra.ExactArgs(0), diff --git a/cmd/server/cli/run_test.go b/cmd/server/cli/run_test.go index 7f1e458c..8272b068 100644 --- a/cmd/server/cli/run_test.go +++ b/cmd/server/cli/run_test.go @@ -1 +1,45 @@ package cli + +import ( + "os" + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +func TestLoadConfig(t *testing.T) { + tempFile, err := os.CreateTemp("", "server.conf") + assert.NoError(t, err) + defer os.Remove(tempFile.Name()) + + _, err = tempFile.WriteString(` + server { + listen_address = "localhost" + listen_port = "8085" + socket_path = "/tmp/galadriel-server/api.sock/" + log_level = "DEBUG" +} + providers { + Datastore "postgres" { + connection_string = "postgresql://postgres:postgres@localhost:5432/galadriel" + } + + X509CA "disk" { + key_file_path = "./conf/server/dummy_root_ca.key" + cert_file_path = "./conf/server/dummy_root_ca.crt" + } + + KeyManager "memory" {} +} + `) + assert.NoError(t, err) + + cmd := &cobra.Command{} + cmd.Flags().String("config", tempFile.Name(), "") + + config, err := LoadConfig(cmd) + + assert.NoError(t, err) + assert.NotNil(t, config) +} diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 4885a448..22ccb9c0 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "net" "net/http" "github.com/HewlettPackard/galadriel/pkg/common/api" @@ -17,6 +18,7 @@ import ( const ( jsonContentType = "application/json" + baseURL = "http://localhost/" ) // ServerLocalClient represents a local client of the Galadriel Server. @@ -30,8 +32,23 @@ type ServerLocalClient interface { GetJoinToken(ctx context.Context, trustDomain string) (*entity.JoinToken, error) } -func NewServerClient(socketPath string) ServerLocalClient { - return &serverClient{client: &admin.Client{Server: socketPath}} +func NewServerClient(socketPath string) (ServerLocalClient, error) { + clientOpt := admin.WithBaseURL(baseURL) + + client, err := admin.NewClient(socketPath, clientOpt) + if err != nil { + return nil, fmt.Errorf("failed to instantiate the Admin Client: %q", err) + } + + t := &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, "unix", socketPath) + }} + + client.Client = &http.Client{Transport: t} + + return &serverClient{client: client}, nil } type serverClient struct { @@ -100,7 +117,7 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entit return nil, fmt.Errorf("failed to read response body: %v", err) } - if res.StatusCode != http.StatusOK { + if res.StatusCode != http.StatusCreated { return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) } @@ -113,12 +130,8 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entit } func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relationship) (*entity.Relationship, error) { - relBytes, err := json.Marshal(rel) - if err != nil { - return nil, fmt.Errorf("failed to marshal Relationship: %v", err) - } - - res, err := c.client.PutRelationshipWithBody(ctx, jsonContentType, bytes.NewReader(relBytes)) + payload := admin.PutRelationshipJSONRequestBody{TrustDomainAName: rel.TrustDomainAName.String(), TrustDomainBName: rel.TrustDomainBName.String()} + res, err := c.client.PutRelationship(ctx, payload) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } @@ -129,7 +142,7 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat return nil, err } - if res.StatusCode != http.StatusOK { + if res.StatusCode != http.StatusCreated { return nil, errors.New(string(body)) } diff --git a/pkg/server/api/admin/admin.gen.go b/pkg/server/api/admin/admin.gen.go index db292bb8..eabefb48 100644 --- a/pkg/server/api/admin/admin.gen.go +++ b/pkg/server/api/admin/admin.gen.go @@ -29,8 +29,8 @@ type JoinTokenResult struct { // RelationshipRequest defines model for RelationshipRequest. type RelationshipRequest struct { - TrustDomainAId externalRef0.UUID `json:"trust_domain_a_id"` - TrustDomainBId externalRef0.UUID `json:"trust_domain_b_id"` + TrustDomainAName externalRef0.TrustDomainName `json:"trust_domain_a_name"` + TrustDomainBName externalRef0.TrustDomainName `json:"trust_domain_b_name"` } // TrustDomainPut defines model for TrustDomainPut. @@ -1301,31 +1301,31 @@ func RegisterHandlersWithBaseURL(router EchoRouter, si ServerInterface, baseURL // Base64 encoded, gzipped, json marshaled Swagger object var swaggerSpec = []string{ - "H4sIAAAAAAAC/9xYXXObOBf+Kxq9vXi3w5ftxE24c5q0651uNpO0MzvNeDMyHGy1IFFJxPVm+O87EtgG", - "TGLcJtltr4xB6Hw8z3N0Dnc44EnKGTAlsX+HBciUMwnmzylEJIuVvgw4U8DMJUnTmAZEUc7cT5IzfU8G", - "c0iIvnohIMI+/p+72dctnkp3lNIzIbjAeZ5bOAQZCJrqfbCPzQM0uhijjQt6Vfmu3nr9unYiDKl+k8QX", - "gqcgFNUuRySWYOG0cku7HoL+jbhIiMI+pkwND7CFE/KVJlmC/cPjYwsnlBX/ep5nYbVMoVgKMxA4t3AC", - "UpKZ2Qm+kiSN9fMRmgLJFI2yGI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7bipRQPmD2O0O2YtB9NY0ZUQsnFCdYzQFdQPA", + "kLrhlkjvA7J0WhXEv23+HB+Xu5aUo8X4eFtVGR8jnpjG2qKJUbGuaWsR227gNrq7aro6w/2wkH9CMmi9", + "klUrsyixBXBTH914NW/cpWW70j6HlFunurKWsQVU7zmsdeFUqSt+AmhGcdyERjVOmQ1omhrtQMa/bfWx", + "e6XYiO1oUXe9e7VotfH60N8hw81e+jgdPn1v/QGkX0aRu8Hu7CK/XwnSZ60S3SXiVyfOJzNfP0fJ8L9w", + "ytzVJ/K7qsf68/hDKHb6D6sa7f9DvHTl0FghgxVKuGjSwcJ9TQftMKpwmxhnpZkuK+DsOTrlEUnnXCpP", + "3pDZDIRHuU9y6l8PsE5qvWUb7xGqPpm1Pahxtu5ujmoj+6BKpTn7rT6xmCf6REiWVt5BXCfVOiHee7St", + "XbEPOpu+nHdYbSR8ygsWI8VbA663NtBIdjkp/woAAP//wY4RiHQdAAA=", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/pkg/server/api/admin/admin.yaml b/pkg/server/api/admin/admin.yaml index e5368001..bed52a39 100644 --- a/pkg/server/api/admin/admin.yaml +++ b/pkg/server/api/admin/admin.yaml @@ -199,13 +199,13 @@ components: type: object additionalProperties: false required: - - trust_domain_a_id - - trust_domain_b_id + - trust_domain_a_name + - trust_domain_b_name properties: - trust_domain_a_id: - $ref: '../../../common/api/schemas.yaml#/components/schemas/UUID' - trust_domain_b_id: - $ref: '../../../common/api/schemas.yaml#/components/schemas/UUID' + trust_domain_a_name: + $ref: '../../../common/api/schemas.yaml#/components/schemas/TrustDomainName' + trust_domain_b_name: + $ref: '../../../common/api/schemas.yaml#/components/schemas/TrustDomainName' TrustDomainPut: type: object additionalProperties: false diff --git a/pkg/server/api/admin/helper.go b/pkg/server/api/admin/helper.go index 2b996a96..ab0b341b 100644 --- a/pkg/server/api/admin/helper.go +++ b/pkg/server/api/admin/helper.go @@ -9,8 +9,8 @@ import ( func (r RelationshipRequest) ToEntity() *entity.Relationship { return &entity.Relationship{ - TrustDomainAID: r.TrustDomainAId, - TrustDomainBID: r.TrustDomainBId, + TrustDomainAName: spiffeid.RequireTrustDomainFromString(r.TrustDomainAName), + TrustDomainBName: spiffeid.RequireTrustDomainFromString(r.TrustDomainBName), } } diff --git a/pkg/server/api/admin/helper_test.go b/pkg/server/api/admin/helper_test.go index e775dfc3..5c649919 100644 --- a/pkg/server/api/admin/helper_test.go +++ b/pkg/server/api/admin/helper_test.go @@ -3,22 +3,26 @@ package admin import ( "testing" - "github.com/google/uuid" "github.com/stretchr/testify/assert" ) +const ( + td1 = "test.com" + td2 = "test2.com" +) + func TestRelationshipRequestToEntity(t *testing.T) { t.Run("Full fill correctly the relationship entity model", func(t *testing.T) { releationshipRequest := RelationshipRequest{ - TrustDomainAId: uuid.New(), - TrustDomainBId: uuid.New(), + TrustDomainAName: td1, + TrustDomainBName: td2, } r := releationshipRequest.ToEntity() assert.NotNil(t, r) - assert.Equal(t, releationshipRequest.TrustDomainAId, r.TrustDomainAID) - assert.Equal(t, releationshipRequest.TrustDomainBId, r.TrustDomainBID) + assert.Equal(t, releationshipRequest.TrustDomainAName, r.TrustDomainAName.String()) + assert.Equal(t, releationshipRequest.TrustDomainBName, r.TrustDomainBName.String()) }) } diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index fbf147a4..fcb6189a 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -104,23 +104,26 @@ func (h *AdminAPIHandlers) PutRelationship(echoCtx echo.Context) error { } eRelationship := reqBody.ToEntity() - _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainAID, http.StatusBadRequest) + dbTd1, err := h.lookupTrustDomain(ctx, eRelationship.TrustDomainAName.String(), http.StatusBadRequest) if err != nil { return err } - _, err = h.lookupTrustDomain(ctx, eRelationship.TrustDomainBID, http.StatusBadRequest) + dbTd2, err := h.lookupTrustDomain(ctx, eRelationship.TrustDomainBName.String(), http.StatusBadRequest) if err != nil { return err } + eRelationship.TrustDomainAID = dbTd1.ID.UUID + eRelationship.TrustDomainBID = dbTd2.ID.UUID + rel, err := h.Datastore.CreateOrUpdateRelationship(ctx, eRelationship) if err != nil { err = fmt.Errorf("failed creating relationship: %v", err) return h.handleAndLog(err, http.StatusInternalServerError) } - h.Logger.Printf("Created relationship between trust domains %s and %s", rel.TrustDomainAID, rel.TrustDomainBID) + h.Logger.Printf("Created relationship between trust domains %s and %s", dbTd1.Name.String(), dbTd2.Name.String()) response := api.RelationshipFromEntity(rel) err = chttp.WriteResponse(echoCtx, http.StatusCreated, response) @@ -179,7 +182,7 @@ func (h *AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { } if td != nil { - err = fmt.Errorf("trust domain already exists: %q", dbTD.Name) + err = fmt.Errorf("trust domain already exists: %s", dbTD.Name.String()) return h.handleAndLog(err, http.StatusBadRequest) } @@ -189,7 +192,7 @@ func (h *AdminAPIHandlers) PutTrustDomain(echoCtx echo.Context) error { return h.handleAndLog(err, http.StatusInternalServerError) } - h.Logger.Printf("Created trustDomain for trust domain: %s", dbTD.Name) + h.Logger.Printf("Created trustDomain: %s", dbTD.Name.String()) response := api.TrustDomainFromEntity(m) err = chttp.WriteResponse(echoCtx, http.StatusCreated, response) @@ -233,7 +236,7 @@ func (h *AdminAPIHandlers) GetTrustDomainByName(echoCtx echo.Context, trustDomai } // PutTrustDomainByName updates the trust domain - (PUT /trust-domain/{trustDomainName}) -func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomainID api.UUID) error { +func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomainName api.TrustDomainName) error { ctx := echoCtx.Request().Context() reqBody := &admin.PutTrustDomainByNameJSONRequestBody{} @@ -249,7 +252,7 @@ func (h *AdminAPIHandlers) PutTrustDomainByName(echoCtx echo.Context, trustDomai return h.handleAndLog(err, http.StatusBadRequest) } - _, err = h.lookupTrustDomain(ctx, trustDomainID, http.StatusNotFound) + _, err = h.lookupTrustDomain(ctx, trustDomainName, http.StatusNotFound) if err != nil { return err } @@ -337,8 +340,10 @@ func (h *AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomai return td, nil } -func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID uuid.UUID, code int) (*entity.TrustDomain, error) { - td, err := h.Datastore.FindTrustDomainByID(ctx, trustDomainID) +func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainName api.TrustDomainName, code int) (*entity.TrustDomain, error) { + tdName := spiffeid.RequireTrustDomainFromString(trustDomainName) + + td, err := h.Datastore.FindTrustDomainByName(ctx, tdName) if err != nil { msg := errors.New("error looking up trust domain") errMsg := fmt.Errorf("%s: %w", msg, err) @@ -346,7 +351,7 @@ func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainID } if td == nil { - errMsg := fmt.Errorf("trust domain exists: %q", trustDomainID) + errMsg := fmt.Errorf("trust domain does not exists") return nil, h.handleAndLog(errMsg, code) } diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/management_test.go index 4f45b2d2..8225026c 100644 --- a/pkg/server/endpoints/management_test.go +++ b/pkg/server/endpoints/management_test.go @@ -198,8 +198,8 @@ func TestUDSPutRelationships(t *testing.T) { } reqBody := &admin.PutRelationshipJSONRequestBody{ - TrustDomainAId: tdUUID1.UUID, - TrustDomainBId: tdUUID2.UUID, + TrustDomainAName: td1, + TrustDomainBName: td2, } // Setup @@ -227,8 +227,8 @@ func TestUDSPutRelationships(t *testing.T) { } reqBody := &admin.PutRelationshipJSONRequestBody{ - TrustDomainAId: tdUUID1.UUID, - TrustDomainBId: tdUUID2.UUID, + TrustDomainAName: td1, + TrustDomainBName: td2, } // Setup @@ -409,7 +409,7 @@ func TestUDSPutTrustDomainByName(t *testing.T) { setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) setup.FakeDatabase.WithTrustDomains(&fakeTrustDomains) - err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, tdUUID1.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1) assert.NoError(t, err) assert.Equal(t, http.StatusOK, setup.Recorder.Code) @@ -436,13 +436,13 @@ func TestUDSPutTrustDomainByName(t *testing.T) { // Setup setup := NewManagementTestSetup(t, http.MethodPut, completePath, reqBody) - err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, tdUUID1.UUID) + err := setup.Handler.PutTrustDomainByName(setup.EchoCtx, td1) assert.Error(t, err) assert.Empty(t, setup.Recorder.Body.Bytes()) echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain exists: %q", tdUUID1.UUID) + expectedErrorMsg := fmt.Sprintf("trust domain exists: %s", td1) assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) }) } From b243a6724e531eb684574b6dd57bd474ef576ce2 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 16:44:46 -0300 Subject: [PATCH 04/12] changing order of instantiation --- cmd/server/cli/generate.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/server/cli/generate.go b/cmd/server/cli/generate.go index 9dcdbdf4..7e52e34d 100644 --- a/cmd/server/cli/generate.go +++ b/cmd/server/cli/generate.go @@ -17,14 +17,14 @@ var tokenCmd = &cobra.Command{ Args: cobra.ExactArgs(0), Short: "Generates a join token for provided trust domain", RunE: func(cmd *cobra.Command, args []string) error { - client, err := util.NewServerClient(defaultSocketPath) + trustDomain, err := cmd.Flags().GetString("trustDomain") if err != nil { - return err + return fmt.Errorf("cannot get trust domain flag: %v", err) } - trustDomain, err := cmd.Flags().GetString("trustDomain") + client, err := util.NewServerClient(defaultSocketPath) if err != nil { - return fmt.Errorf("cannot get trust domain flag: %v", err) + return err } joinToken, err := client.GetJoinToken(context.Background(), trustDomain) From 36aeff088ed7e84430499b3c3d58316f4d6d76fd Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 17:10:50 -0300 Subject: [PATCH 05/12] using api models for type --- cmd/server/cli/create.go | 9 ++------- cmd/server/util/client.go | 30 +++++++++++++++--------------- pkg/server/endpoints/management.go | 2 +- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/cmd/server/cli/create.go b/cmd/server/cli/create.go index c50385c3..46a950f9 100644 --- a/cmd/server/cli/create.go +++ b/cmd/server/cli/create.go @@ -21,22 +21,17 @@ var createTrustDomainCmd = &cobra.Command{ Short: "Creates a new trust domain", RunE: func(cmd *cobra.Command, args []string) error { - td, err := cmd.Flags().GetString("trustDomain") + trustDomain, err := cmd.Flags().GetString("trustDomain") if err != nil { return fmt.Errorf("cannot get trust domain flag: %v", err) } - trustDomain, err := spiffeid.TrustDomainFromString(td) - if err != nil { - return fmt.Errorf("failed parsing trust domain: %v", err) - } - client, err := util.NewServerClient(defaultSocketPath) if err != nil { return err } - trustDomainRes, err := client.CreateTrustDomain(context.Background(), &entity.TrustDomain{Name: trustDomain}) + trustDomainRes, err := client.CreateTrustDomain(context.Background(), trustDomain) if err != nil { return err } diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 22ccb9c0..86555a3a 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -1,7 +1,6 @@ package util import ( - "bytes" "context" "encoding/json" "errors" @@ -23,13 +22,13 @@ const ( // ServerLocalClient represents a local client of the Galadriel Server. type ServerLocalClient interface { - CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) - GetTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) - UpdateTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) + CreateTrustDomain(ctx context.Context, trustDomain api.TrustDomainName) (*entity.TrustDomain, error) + GetTrustDomainByName(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) + UpdateTrustDomainByName(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) CreateRelationship(ctx context.Context, r *entity.Relationship) (*entity.Relationship, error) GetRelationshipByID(ctx context.Context, relID uuid.UUID) (*entity.Relationship, error) - GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) - GetJoinToken(ctx context.Context, trustDomain string) (*entity.JoinToken, error) + GetRelationships(ctx context.Context, consentStatus api.ConsentStatus, trustDomainName api.TrustDomainName) (*entity.Relationship, error) + GetJoinToken(ctx context.Context, trustDomain api.TrustDomainName) (*entity.JoinToken, error) } func NewServerClient(socketPath string) (ServerLocalClient, error) { @@ -55,7 +54,7 @@ type serverClient struct { client *admin.Client } -func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) { +func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) { res, err := c.client.GetTrustDomainByName(ctx, trustDomainName) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) @@ -79,8 +78,9 @@ func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName return trustDomain, nil } -func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainName string) (*entity.TrustDomain, error) { - res, err := c.client.PutTrustDomainByNameWithBody(ctx, trustDomainName, jsonContentType, bytes.NewReader([]byte(trustDomainName))) +func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) { + payload := api.TrustDomain{Name: trustDomainName} + res, err := c.client.PutTrustDomainByName(ctx, trustDomainName, payload) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) } @@ -103,8 +103,8 @@ func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainN return trustDomain, nil } -func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entity.TrustDomain) (*entity.TrustDomain, error) { - payload := admin.PutTrustDomainJSONRequestBody{Name: trustDomain.Name.String()} +func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) { + payload := admin.PutTrustDomainJSONRequestBody{Name: trustDomainName} res, err := c.client.PutTrustDomain(ctx, payload) if err != nil { @@ -126,7 +126,7 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomain *entit return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) } - return trustDomain, nil + return trustDomainRes, nil } func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relationship) (*entity.Relationship, error) { @@ -153,8 +153,8 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat return relationships, nil } -func (c *serverClient) GetRelationships(ctx context.Context, consentStatus string, trustDomain string) (*entity.Relationship, error) { - payload := &admin.GetRelationshipsParams{Status: (*api.ConsentStatus)(&consentStatus), TrustDomainName: &trustDomain} +func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.ConsentStatus, trustDomainName api.TrustDomainName) (*entity.Relationship, error) { + payload := &admin.GetRelationshipsParams{Status: (*api.ConsentStatus)(&consentStatus), TrustDomainName: &trustDomainName} res, err := c.client.GetRelationships(ctx, payload) if err != nil { @@ -203,7 +203,7 @@ func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) return relationship, nil } -func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName string) (*entity.JoinToken, error) { +func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.JoinToken, error) { res, err := c.client.GetJoinToken(ctx, trustDomainName) if err != nil { return nil, fmt.Errorf("failed to send request: %v", err) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/management.go index fcb6189a..fe1e05fe 100644 --- a/pkg/server/endpoints/management.go +++ b/pkg/server/endpoints/management.go @@ -291,7 +291,7 @@ func (h *AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName ap } if td == nil { - errMsg := fmt.Errorf("trust domain exists: %q", trustDomainName) + errMsg := fmt.Errorf("trust domain '%s' does not exists", trustDomainName) return h.handleAndLog(errMsg, http.StatusBadRequest) } From 0db62d9902d86bc33c6e5862f2045fc5b6eded3a Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 17:25:30 -0300 Subject: [PATCH 06/12] decapitalize trust domain flag --- cmd/server/cli/generate.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/server/cli/generate.go b/cmd/server/cli/generate.go index 7e52e34d..fda42b54 100644 --- a/cmd/server/cli/generate.go +++ b/cmd/server/cli/generate.go @@ -17,7 +17,7 @@ var tokenCmd = &cobra.Command{ Args: cobra.ExactArgs(0), Short: "Generates a join token for provided trust domain", RunE: func(cmd *cobra.Command, args []string) error { - trustDomain, err := cmd.Flags().GetString("trustDomain") + trustDomain, err := cmd.Flags().GetString("trustdomain") if err != nil { return fmt.Errorf("cannot get trust domain flag: %v", err) } @@ -39,6 +39,6 @@ var tokenCmd = &cobra.Command{ func init() { generateCmd.AddCommand(tokenCmd) - tokenCmd.PersistentFlags().StringP("trustDomain", "t", "", "A trust domain which the join token is bound to.") + tokenCmd.PersistentFlags().StringP("trustdomain", "t", "", "A trust domain which the join token is bound to.") RootCmd.AddCommand(generateCmd) } From bb82190c671f0ece7c2b7bf21a5f875a5b3eafb8 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 17:31:17 -0300 Subject: [PATCH 07/12] renaming management to admin --- pkg/server/endpoints/{management.go => admin.go} | 0 pkg/server/endpoints/{management_test.go => admin_test.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename pkg/server/endpoints/{management.go => admin.go} (100%) rename pkg/server/endpoints/{management_test.go => admin_test.go} (100%) diff --git a/pkg/server/endpoints/management.go b/pkg/server/endpoints/admin.go similarity index 100% rename from pkg/server/endpoints/management.go rename to pkg/server/endpoints/admin.go diff --git a/pkg/server/endpoints/management_test.go b/pkg/server/endpoints/admin_test.go similarity index 100% rename from pkg/server/endpoints/management_test.go rename to pkg/server/endpoints/admin_test.go From 5ca38bdffe6cd80f30bf52784bc50803ea1e5abc Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 17:45:48 -0300 Subject: [PATCH 08/12] fixing duplication messages --- cmd/server/util/client.go | 62 +++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 86555a3a..2b38cbdc 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -16,8 +16,14 @@ import ( ) const ( - jsonContentType = "application/json" - baseURL = "http://localhost/" + jsonContentType = "application/json" + baseURL = "http://localhost/" + errFailedRequest = "failed to send request: %v" + errReadResponseBody = "failed to read response body: %v" + errStatusCodeMsg = "request returned an error code %d: \n%s" + errUnmarshalRelationships = "failed to unmarshal relationships: %v" + errUnmarshalTrustDomains = "failed to unmarshal trust domain: %v" + errUnmarshalJoinToken = "failed to unmarshal join token: %v" ) // ServerLocalClient represents a local client of the Galadriel Server. @@ -57,22 +63,22 @@ type serverClient struct { func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.TrustDomain, error) { res, err := c.client.GetTrustDomainByName(ctx, trustDomainName) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var trustDomain *entity.TrustDomain if err = json.Unmarshal(body, &trustDomain); err != nil { - return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + return nil, fmt.Errorf(errUnmarshalTrustDomains, err) } return trustDomain, nil @@ -82,22 +88,22 @@ func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainN payload := api.TrustDomain{Name: trustDomainName} res, err := c.client.PutTrustDomainByName(ctx, trustDomainName, payload) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var trustDomain *entity.TrustDomain if err = json.Unmarshal(body, &trustDomain); err != nil { - return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + return nil, fmt.Errorf(errUnmarshalTrustDomains, err) } return trustDomain, nil @@ -108,22 +114,22 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomainName ap res, err := c.client.PutTrustDomain(ctx, payload) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusCreated { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var trustDomainRes *entity.TrustDomain if err = json.Unmarshal(body, &trustDomainRes); err != nil { - return nil, fmt.Errorf("failed to unmarshal trust domain: %v", err) + return nil, fmt.Errorf(errUnmarshalTrustDomains, err) } return trustDomainRes, nil @@ -133,7 +139,7 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat payload := admin.PutRelationshipJSONRequestBody{TrustDomainAName: rel.TrustDomainAName.String(), TrustDomainBName: rel.TrustDomainBName.String()} res, err := c.client.PutRelationship(ctx, payload) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() @@ -148,7 +154,7 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat var relationships *entity.Relationship if err = json.Unmarshal(body, &relationships); err != nil { - return nil, fmt.Errorf("failed to unmarshal relationships: %v", err) + return nil, fmt.Errorf(errUnmarshalRelationships, err) } return relationships, nil @@ -158,22 +164,22 @@ func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.C res, err := c.client.GetRelationships(ctx, payload) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var relationship *entity.Relationship if err = json.Unmarshal(body, &relationship); err != nil { - return nil, fmt.Errorf("failed to unmarshal relationship: %v", err) + return nil, fmt.Errorf(errUnmarshalRelationships, err) } return relationship, nil @@ -182,22 +188,22 @@ func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.C func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) (*entity.Relationship, error) { res, err := c.client.GetRelationshipByID(ctx, relID) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var relationship *entity.Relationship if err = json.Unmarshal(body, &relationship); err != nil { - return nil, fmt.Errorf("failed to unmarshal relationship: %v", err) + return nil, fmt.Errorf(errUnmarshalRelationships, err) } return relationship, nil @@ -206,22 +212,22 @@ func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName api.TrustDomainName) (*entity.JoinToken, error) { res, err := c.client.GetJoinToken(ctx, trustDomainName) if err != nil { - return nil, fmt.Errorf("failed to send request: %v", err) + return nil, fmt.Errorf(errFailedRequest, err) } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { - return nil, fmt.Errorf("failed to read response body: %v", err) + return nil, fmt.Errorf(errReadResponseBody, err) } if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf("request returned an error code %d: \n%s", res.StatusCode, body) + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) } var joinToken *entity.JoinToken if err = json.Unmarshal(body, &joinToken); err != nil { - return nil, fmt.Errorf("failed to unmarshal join token: %v", err) + return nil, fmt.Errorf(errUnmarshalJoinToken, err) } return joinToken, nil From 53b668d1bd486a1b7ab1237f987646865909d8a8 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 17:48:28 -0300 Subject: [PATCH 09/12] removing unused var --- cmd/server/util/client.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 2b38cbdc..a63f7620 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -16,7 +16,6 @@ import ( ) const ( - jsonContentType = "application/json" baseURL = "http://localhost/" errFailedRequest = "failed to send request: %v" errReadResponseBody = "failed to read response body: %v" From 2283c376e6c5de1a933677d3bcc5e60665d27950 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 18:01:19 -0300 Subject: [PATCH 10/12] fixing unit tests --- pkg/server/endpoints/admin_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pkg/server/endpoints/admin_test.go b/pkg/server/endpoints/admin_test.go index 8225026c..f2b4a144 100644 --- a/pkg/server/endpoints/admin_test.go +++ b/pkg/server/endpoints/admin_test.go @@ -242,8 +242,8 @@ func TestUDSPutRelationships(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain exists: %q", tdUUID2.UUID) - assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) + expectedErrorMsg := fmt.Errorf("trust domain does not exists") + assert.Equal(t, expectedErrorMsg.Error(), echoHTTPErr.Message) }) // Should we test sending wrong body formats ? @@ -442,8 +442,8 @@ func TestUDSPutTrustDomainByName(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) - expectedErrorMsg := fmt.Sprintf("trust domain exists: %s", td1) - assert.Equal(t, expectedErrorMsg, echoHTTPErr.Message) + expectedErrorMsg := fmt.Errorf("trust domain does not exists") + assert.Equal(t, expectedErrorMsg.Error(), echoHTTPErr.Message) }) } @@ -483,7 +483,7 @@ func TestUDSGetJoinToken(t *testing.T) { echoHttpErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) - expectedMsg := fmt.Errorf("trust domain exists: %q", td1) + expectedMsg := fmt.Errorf("trust domain '%s' does not exists", td1) assert.Equal(t, expectedMsg.Error(), echoHttpErr.Message) }) } From d7015eea72884a054d30fe79fb2017625c95f471 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Thu, 18 May 2023 18:18:52 -0300 Subject: [PATCH 11/12] trying to fix code duplication --- cmd/server/util/client.go | 126 +++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 62 deletions(-) diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index a63f7620..0ae3466b 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -3,7 +3,6 @@ package util import ( "context" "encoding/json" - "errors" "fmt" "io" "net" @@ -66,18 +65,14 @@ func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } - var trustDomain *entity.TrustDomain - if err = json.Unmarshal(body, &trustDomain); err != nil { - return nil, fmt.Errorf(errUnmarshalTrustDomains, err) + trustDomain, err := unmarshalTrustDomain(body) + if err != nil { + return nil, err } return trustDomain, nil @@ -91,18 +86,14 @@ func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainN } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } - var trustDomain *entity.TrustDomain - if err = json.Unmarshal(body, &trustDomain); err != nil { - return nil, fmt.Errorf(errUnmarshalTrustDomains, err) + trustDomain, err := unmarshalTrustDomain(body) + if err != nil { + return nil, err } return trustDomain, nil @@ -117,21 +108,17 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomainName ap } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusCreated { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } - var trustDomainRes *entity.TrustDomain - if err = json.Unmarshal(body, &trustDomainRes); err != nil { - return nil, fmt.Errorf(errUnmarshalTrustDomains, err) + trustDomain, err := unmarshalTrustDomain(body) + if err != nil { + return nil, err } - return trustDomainRes, nil + return trustDomain, nil } func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relationship) (*entity.Relationship, error) { @@ -142,21 +129,17 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { return nil, err } - if res.StatusCode != http.StatusCreated { - return nil, errors.New(string(body)) - } - - var relationships *entity.Relationship - if err = json.Unmarshal(body, &relationships); err != nil { - return nil, fmt.Errorf(errUnmarshalRelationships, err) + relationship, err := unmarshalRelationship(body) + if err != nil { + return nil, err } - return relationships, nil + return relationship, nil } func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.ConsentStatus, trustDomainName api.TrustDomainName) (*entity.Relationship, error) { payload := &admin.GetRelationshipsParams{Status: (*api.ConsentStatus)(&consentStatus), TrustDomainName: &trustDomainName} @@ -167,18 +150,14 @@ func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.C } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } - var relationship *entity.Relationship - if err = json.Unmarshal(body, &relationship); err != nil { - return nil, fmt.Errorf(errUnmarshalRelationships, err) + relationship, err := unmarshalRelationship(body) + if err != nil { + return nil, err } return relationship, nil @@ -191,18 +170,14 @@ func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } - var relationship *entity.Relationship - if err = json.Unmarshal(body, &relationship); err != nil { - return nil, fmt.Errorf(errUnmarshalRelationships, err) + relationship, err := unmarshalRelationship(body) + if err != nil { + return nil, err } return relationship, nil @@ -215,13 +190,9 @@ func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName api.Tru } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err := readBodyAndStatusCode(res) if err != nil { - return nil, fmt.Errorf(errReadResponseBody, err) - } - - if res.StatusCode != http.StatusOK { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + return nil, err } var joinToken *entity.JoinToken @@ -231,3 +202,34 @@ func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName api.Tru return joinToken, nil } + +func unmarshalTrustDomain(body []byte) (*entity.TrustDomain, error) { + var trustDomain *entity.TrustDomain + if err := json.Unmarshal(body, &trustDomain); err != nil { + return nil, fmt.Errorf(errUnmarshalTrustDomains, err) + } + + return trustDomain, nil +} + +func unmarshalRelationship(body []byte) (*entity.Relationship, error) { + var relationship *entity.Relationship + if err := json.Unmarshal(body, &relationship); err != nil { + return nil, fmt.Errorf(errUnmarshalRelationships, err) + } + + return relationship, nil +} + +func readBodyAndStatusCode(res *http.Response) ([]byte, error) { + body, err := io.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf(errReadResponseBody, err) + } + + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) + } + + return body, nil +} From d1f309f707885ddff592352ea25a8cc0e2514ea4 Mon Sep 17 00:00:00 2001 From: Caio Milfont Date: Sat, 20 May 2023 14:34:31 -0300 Subject: [PATCH 12/12] address PR comments --- cmd/server/cli/list.go | 53 ++--------------------------- cmd/server/util/client.go | 26 +++++++------- pkg/server/api/admin/helper.go | 18 +++++++--- pkg/server/api/admin/helper_test.go | 3 +- pkg/server/endpoints/admin.go | 14 +++++--- pkg/server/endpoints/admin_test.go | 6 ++-- 6 files changed, 44 insertions(+), 76 deletions(-) diff --git a/cmd/server/cli/list.go b/cmd/server/cli/list.go index 04a097f6..b3d148f8 100644 --- a/cmd/server/cli/list.go +++ b/cmd/server/cli/list.go @@ -10,58 +10,9 @@ var listCmd = &cobra.Command{ } // TODO: Implement Get Relationships and Trust Domains -var listTrustDomainCmd = &cobra.Command{ - // Use: "trustdomains", - // Args: cobra.ExactArgs(0), - // Short: "Lists all the Trust Domains.", - // RunE: func(cmd *cobra.Command, args []string) error { - // c := util.NewServerClient(defaultSocketPath) - // trustDomains, err := c.ListTrustDomains() - // if err != nil { - // return err - // } +var listTrustDomainCmd = &cobra.Command{} - // if len(trustDomains) == 0 { - // fmt.Println("No trust domains found") - // return nil - // } - - // for _, m := range trustDomains { - // fmt.Printf("ID: %s\n", m.ID.UUID) - // fmt.Printf("Trust Domain: %s\n", m.Name) - // fmt.Println() - // } - - // return nil - // }, -} - -var listRelationshipsCmd = &cobra.Command{ - // Use: "relationships", - // Args: cobra.ExactArgs(0), - // Short: "Lists all the relationships.", - // RunE: func(cmd *cobra.Command, args []string) error { - // c := util.NewServerClient(defaultSocketPath) - // rels, err := c.GetRelationships(context.Background(), "status", "tdName") - // if err != nil { - // return err - // } - - // if len(rels) == 0 { - // fmt.Println("No relationships found") - // return nil - // } - - // for _, r := range rels { - // fmt.Printf("ID: %s\n", r.ID.UUID) - // fmt.Printf("Trust Domain A: %s\n", r.TrustDomainAName.String()) - // fmt.Printf("Trust Domain B: %s\n", r.TrustDomainBName.String()) - // fmt.Println() - // } - - // return nil - // }, -} +var listRelationshipsCmd = &cobra.Command{} func init() { listCmd.AddCommand(listTrustDomainCmd) diff --git a/cmd/server/util/client.go b/cmd/server/util/client.go index 0ae3466b..35e96afb 100644 --- a/cmd/server/util/client.go +++ b/cmd/server/util/client.go @@ -18,7 +18,7 @@ const ( baseURL = "http://localhost/" errFailedRequest = "failed to send request: %v" errReadResponseBody = "failed to read response body: %v" - errStatusCodeMsg = "request returned an error code %d: \n%s" + errStatusCodeMsg = "request returned an error code %d" errUnmarshalRelationships = "failed to unmarshal relationships: %v" errUnmarshalTrustDomains = "failed to unmarshal trust domain: %v" errUnmarshalJoinToken = "failed to unmarshal join token: %v" @@ -65,7 +65,7 @@ func (c *serverClient) GetTrustDomainByName(ctx context.Context, trustDomainName } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -86,7 +86,7 @@ func (c *serverClient) UpdateTrustDomainByName(ctx context.Context, trustDomainN } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -108,7 +108,7 @@ func (c *serverClient) CreateTrustDomain(ctx context.Context, trustDomainName ap } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -129,7 +129,7 @@ func (c *serverClient) CreateRelationship(ctx context.Context, rel *entity.Relat } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -150,7 +150,7 @@ func (c *serverClient) GetRelationships(ctx context.Context, consentStatus api.C } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -170,7 +170,7 @@ func (c *serverClient) GetRelationshipByID(ctx context.Context, relID uuid.UUID) } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -190,7 +190,7 @@ func (c *serverClient) GetJoinToken(ctx context.Context, trustDomainName api.Tru } defer res.Body.Close() - body, err := readBodyAndStatusCode(res) + body, err := readResponse(res) if err != nil { return nil, err } @@ -221,15 +221,15 @@ func unmarshalRelationship(body []byte) (*entity.Relationship, error) { return relationship, nil } -func readBodyAndStatusCode(res *http.Response) ([]byte, error) { +func readResponse(res *http.Response) ([]byte, error) { + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { + return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode) + } + body, err := io.ReadAll(res.Body) if err != nil { return nil, fmt.Errorf(errReadResponseBody, err) } - if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { - return nil, fmt.Errorf(errStatusCodeMsg, res.StatusCode, body) - } - return body, nil } diff --git a/pkg/server/api/admin/helper.go b/pkg/server/api/admin/helper.go index ab0b341b..0d3998af 100644 --- a/pkg/server/api/admin/helper.go +++ b/pkg/server/api/admin/helper.go @@ -7,11 +7,21 @@ import ( "github.com/spiffe/go-spiffe/v2/spiffeid" ) -func (r RelationshipRequest) ToEntity() *entity.Relationship { - return &entity.Relationship{ - TrustDomainAName: spiffeid.RequireTrustDomainFromString(r.TrustDomainAName), - TrustDomainBName: spiffeid.RequireTrustDomainFromString(r.TrustDomainBName), +func (r RelationshipRequest) ToEntity() (*entity.Relationship, error) { + tdA, err := spiffeid.TrustDomainFromString(r.TrustDomainAName) + if err != nil { + return nil, fmt.Errorf("malformed trust domain[%q]: %v", r.TrustDomainAName, err) + } + + tdB, err := spiffeid.TrustDomainFromString(r.TrustDomainBName) + if err != nil { + return nil, fmt.Errorf("malformed trust domain[%q]: %v", r.TrustDomainBName, err) } + + return &entity.Relationship{ + TrustDomainAName: tdA, + TrustDomainBName: tdB, + }, nil } func (td TrustDomainPut) ToEntity() (*entity.TrustDomain, error) { diff --git a/pkg/server/api/admin/helper_test.go b/pkg/server/api/admin/helper_test.go index 5c649919..e9823233 100644 --- a/pkg/server/api/admin/helper_test.go +++ b/pkg/server/api/admin/helper_test.go @@ -18,7 +18,8 @@ func TestRelationshipRequestToEntity(t *testing.T) { TrustDomainBName: td2, } - r := releationshipRequest.ToEntity() + r, err := releationshipRequest.ToEntity() + assert.NoError(t, err) assert.NotNil(t, r) assert.Equal(t, releationshipRequest.TrustDomainAName, r.TrustDomainAName.String()) diff --git a/pkg/server/endpoints/admin.go b/pkg/server/endpoints/admin.go index fe1e05fe..268b43e4 100644 --- a/pkg/server/endpoints/admin.go +++ b/pkg/server/endpoints/admin.go @@ -102,7 +102,10 @@ func (h *AdminAPIHandlers) PutRelationship(echoCtx echo.Context) error { err := fmt.Errorf("failed to read relationship put body: %v", err) return h.handleAndLog(err, http.StatusBadRequest) } - eRelationship := reqBody.ToEntity() + eRelationship, err := reqBody.ToEntity() + if err != nil { + return err + } dbTd1, err := h.lookupTrustDomain(ctx, eRelationship.TrustDomainAName.String(), http.StatusBadRequest) if err != nil { @@ -291,7 +294,7 @@ func (h *AdminAPIHandlers) GetJoinToken(echoCtx echo.Context, trustDomainName ap } if td == nil { - errMsg := fmt.Errorf("trust domain '%s' does not exists", trustDomainName) + errMsg := fmt.Errorf("trust domain %q does not exists", trustDomainName) return h.handleAndLog(errMsg, http.StatusBadRequest) } @@ -341,7 +344,10 @@ func (h *AdminAPIHandlers) findTrustDomainByName(ctx context.Context, trustDomai } func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainName api.TrustDomainName, code int) (*entity.TrustDomain, error) { - tdName := spiffeid.RequireTrustDomainFromString(trustDomainName) + tdName, err := spiffeid.TrustDomainFromString(trustDomainName) + if err != nil { + return nil, fmt.Errorf("malformed trust domain[%q]: %v", trustDomainName, err) + } td, err := h.Datastore.FindTrustDomainByName(ctx, tdName) if err != nil { @@ -351,7 +357,7 @@ func (h *AdminAPIHandlers) lookupTrustDomain(ctx context.Context, trustDomainNam } if td == nil { - errMsg := fmt.Errorf("trust domain does not exists") + errMsg := fmt.Errorf("trust domain %q does not exists", tdName.String()) return nil, h.handleAndLog(errMsg, code) } diff --git a/pkg/server/endpoints/admin_test.go b/pkg/server/endpoints/admin_test.go index f2b4a144..52717f8d 100644 --- a/pkg/server/endpoints/admin_test.go +++ b/pkg/server/endpoints/admin_test.go @@ -242,7 +242,7 @@ func TestUDSPutRelationships(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHTTPErr.Code) - expectedErrorMsg := fmt.Errorf("trust domain does not exists") + expectedErrorMsg := fmt.Errorf("trust domain %q does not exists", td2) assert.Equal(t, expectedErrorMsg.Error(), echoHTTPErr.Message) }) @@ -442,7 +442,7 @@ func TestUDSPutTrustDomainByName(t *testing.T) { echoHTTPErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusNotFound, echoHTTPErr.Code) - expectedErrorMsg := fmt.Errorf("trust domain does not exists") + expectedErrorMsg := fmt.Errorf("trust domain %q does not exists", td1) assert.Equal(t, expectedErrorMsg.Error(), echoHTTPErr.Message) }) } @@ -483,7 +483,7 @@ func TestUDSGetJoinToken(t *testing.T) { echoHttpErr := err.(*echo.HTTPError) assert.Equal(t, http.StatusBadRequest, echoHttpErr.Code) - expectedMsg := fmt.Errorf("trust domain '%s' does not exists", td1) + expectedMsg := fmt.Errorf("trust domain %q does not exists", td1) assert.Equal(t, expectedMsg.Error(), echoHttpErr.Message) }) }