Skip to content

Commit

Permalink
Some minor changes/fixes to ux backend
Browse files Browse the repository at this point in the history
- Move content of services/types package to the services package
- Move onboading_tokens content into its own sub-package
- Separate onboarding_tokens message handlers to distinct functions based on the message method
- fix onboarding_tokens invalid content type

Signed-off-by: nb-ohad <[email protected]>
  • Loading branch information
nb-ohad committed Dec 24, 2023
1 parent 988b6e4 commit 9a2576f
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 43 deletions.
4 changes: 2 additions & 2 deletions services/provider/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
ocsVersion "github.com/red-hat-storage/ocs-operator/v4/version"
rookCephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"

sharedTypes "github.com/red-hat-storage/ocs-operator/v4/services/types"
"github.com/red-hat-storage/ocs-operator/v4/services"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
Expand Down Expand Up @@ -441,7 +441,7 @@ func validateTicket(ticket string, pubKey *rsa.PublicKey) error {
return fmt.Errorf("failed to decode onboarding ticket: %v", err)
}

var ticketData sharedTypes.OnboardingTicket
var ticketData services.OnboardingTicket
err = json.Unmarshal(message, &ticketData)
if err != nil {
return fmt.Errorf("failed to unmarshal onboarding ticket message. %v", err)
Expand Down
2 changes: 1 addition & 1 deletion services/types/types.go → services/types.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package types
package services

type OnboardingTicket struct {
ID string `json:"id"`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package handler
package onboardingtokens

import (
"crypto"
Expand All @@ -15,64 +15,63 @@ import (
"time"

"github.com/google/uuid"
"github.com/red-hat-storage/ocs-operator/v4/services/types"
"github.com/red-hat-storage/ocs-operator/v4/services"
"k8s.io/klog/v2"
)

const onboardingPrivateKeyFilePath = "/etc/private-key/key"

func OnboardingTokensHandler(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int) {
const (
onboardingPrivateKeyFilePath = "/etc/private-key/key"
ContentTypeTextPlain = "text/plain"
)

var err error
func HandleMessage(w http.ResponseWriter, r *http.Request, tokenLifetimeInHours int) {
switch r.Method {
case "POST":
handlePost(w, tokenLifetimeInHours)
default:
handleUnsupportedMethod(w, r)
}
}

onboardingToken, err := generateOnboardingToken(tokenLifetimeInHours)
if err != nil {
klog.Errorf("failed to get onboardig token: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "text/text")
_, err = w.Write([]byte("Failed to generate token"))

if err != nil {
klog.Errorf("failed write data to response writer, %v", err)
}
return
}
func handlePost(w http.ResponseWriter, tokenLifetimeInHours int) {
if onboardingToken, err := generateOnboardingToken(tokenLifetimeInHours); err != nil {
klog.Errorf("failed to get onboardig token: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", ContentTypeTextPlain)

if _, err := w.Write([]byte("Failed to generate token")); err != nil {
klog.Errorf("failed write data to response writer, %v", err)
}
} else {
klog.Info("onboarding token generated successfully")
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/text")
w.Header().Set("Content-Type", ContentTypeTextPlain)

_, err = w.Write([]byte(onboardingToken))
if err != nil {
if _, err = w.Write([]byte(onboardingToken)); err != nil {
klog.Errorf("failed write data to response writer: %v", err)
return
}
}
}

default:
klog.Info("Only POST method should be used to send data to this endpoint /onboarding-tokens")
w.WriteHeader(http.StatusMethodNotAllowed)
w.Header().Set("Content-Type", "text/text")
_, err = w.Write([]byte(fmt.Sprintf("Unsupported method : %s", r.Method)))
if err != nil {
klog.Errorf("failed write data to response writer: %v", err)
}
return
func handleUnsupportedMethod(w http.ResponseWriter, r *http.Request) {
klog.Info("Only POST method should be used to send data to this endpoint /onboarding-tokens")
w.WriteHeader(http.StatusMethodNotAllowed)
w.Header().Set("Content-Type", ContentTypeTextPlain)

if _, err := w.Write([]byte(fmt.Sprintf("Unsupported method : %s", r.Method))); err != nil {
klog.Errorf("failed write data to response writer: %v", err)
}
}

func generateOnboardingToken(tokenLifetimeInHours int) (string, error) {

tokenExpirationDate := time.Now().
Add(time.Duration(tokenLifetimeInHours) * time.Hour).
Unix()

payload, err := json.Marshal(types.OnboardingTicket{
payload, err := json.Marshal(services.OnboardingTicket{
ID: uuid.New().String(),
ExpirationDate: tokenExpirationDate,
})

if err != nil {
return "", fmt.Errorf("failed to marshal the payload: %v", err)
}
Expand Down Expand Up @@ -102,7 +101,6 @@ func generateOnboardingToken(tokenLifetimeInHours int) (string, error) {
}

func readAndDecodeOnboardingPrivateKey() (*rsa.PrivateKey, error) {

pemString, err := os.ReadFile(onboardingPrivateKeyFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read onboarding private key: %v", err)
Expand Down
11 changes: 6 additions & 5 deletions services/ux-backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import (
"os"
"strconv"

handler "github.com/red-hat-storage/ocs-operator/v4/services/ux-backend/handlers"
"k8s.io/klog/v2"

"github.com/red-hat-storage/ocs-operator/v4/services/ux-backend/handlers/onboardingtokens"
)

type serverConfig struct {
Expand All @@ -26,7 +27,7 @@ func loadAndValidateServerConfig() (*serverConfig, error) {
klog.Infof("No user-defined token lifetime provided, defaulting to %d ", defaultTokenLifetimeInHours)
config.tokenLifetimeInHours = defaultTokenLifetimeInHours
} else if config.tokenLifetimeInHours, err = strconv.Atoi(tokenLifetimeInHoursAsString); err != nil {
return nil, fmt.Errorf("Malformed user-defined Token lifetime: %s. shutting down: %v", tokenLifetimeInHoursAsString, err)
return nil, fmt.Errorf("malformed user-defined Token lifetime %s, %v", tokenLifetimeInHoursAsString, err)
}

klog.Infof("generated tokens will be valid for %d hours", config.tokenLifetimeInHours)
Expand All @@ -37,7 +38,7 @@ func loadAndValidateServerConfig() (*serverConfig, error) {
klog.Infof("No user-defined server listening port provided, defaulting to %d ", defaultListeningPort)
config.listenPort = defaultListeningPort
} else if config.listenPort, err = strconv.Atoi(listenPortAsString); err != nil {
return nil, fmt.Errorf("Malformed user-defined listening port: %s. shutting down: %v", listenPortAsString, err)
return nil, fmt.Errorf("malformed user-defined listening port %s, %v", listenPortAsString, err)
}

return &config, nil
Expand All @@ -50,11 +51,11 @@ func main() {
config, err := loadAndValidateServerConfig()
if err != nil {
klog.Errorf("failed to load server config: %v", err)
klog.Info("shutting down!")
os.Exit(-1)
}
http.HandleFunc("/onboarding-tokens", func(w http.ResponseWriter, r *http.Request) {
handler.OnboardingTokensHandler(w, r, config.tokenLifetimeInHours)

onboardingtokens.HandleMessage(w, r, config.tokenLifetimeInHours)
})

klog.Info("ux backend server listening on port ", config.listenPort)
Expand Down
Binary file added ux-backend-server
Binary file not shown.

0 comments on commit 9a2576f

Please sign in to comment.