Skip to content

Installer Experience v2 - Milestone 1 #2187

New issue

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

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

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ go.work.sum
/local-dev/
*.tmp
.envrc
.DS_Store

# Ignore preflight bundles generated during local dev
preflightbundle*
Expand Down
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ list-distros:
.PHONY: create-node%
create-node%: DISTRO = debian-bookworm
create-node%: NODE_PORT = 30000
create-node%: MANAGER_NODE_PORT = 30080
create-node%: K0S_DATA_DIR = /var/lib/embedded-cluster/k0s
create-node%:
@docker run -d \
Expand All @@ -348,7 +349,9 @@ create-node%:
-v $(shell pwd):/replicatedhq/embedded-cluster \
-v $(shell dirname $(shell pwd))/kots:/replicatedhq/kots \
$(if $(filter node0,node$*),-p $(NODE_PORT):$(NODE_PORT)) \
$(if $(filter node0,node$*),-p $(MANAGER_NODE_PORT):$(MANAGER_NODE_PORT)) \
$(if $(filter node0,node$*),-p 30003:30003) \
-e EC_PUBLIC_ADDRESS=localhost \
replicated/ec-distro:$(DISTRO)

@$(MAKE) ssh-node$*
Expand Down
119 changes: 119 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package api

import (
"errors"
"fmt"
"net/http"

"github.com/gorilla/mux"
"github.com/sirupsen/logrus"

"github.com/replicatedhq/embedded-cluster/api/controllers/auth"
"github.com/replicatedhq/embedded-cluster/api/controllers/console"
"github.com/replicatedhq/embedded-cluster/api/controllers/install"
"github.com/replicatedhq/embedded-cluster/api/types"
)

type API struct {
authController auth.Controller
consoleController console.Controller
installController install.Controller
configChan chan<- *types.InstallationConfig
logger logrus.FieldLogger
}

type APIOption func(*API)

func WithAuthController(authController auth.Controller) APIOption {
return func(a *API) {
a.authController = authController
}
}

func WithConsoleController(consoleController console.Controller) APIOption {
return func(a *API) {
a.consoleController = consoleController
}
}

func WithInstallController(installController install.Controller) APIOption {
return func(a *API) {
a.installController = installController
}
}

func WithLogger(logger logrus.FieldLogger) APIOption {
return func(a *API) {
a.logger = logger
}
}

func WithConfigChan(configChan chan<- *types.InstallationConfig) APIOption {
return func(a *API) {
a.configChan = configChan
}
}

func New(password string, opts ...APIOption) (*API, error) {
api := &API{}
for _, opt := range opts {
opt(api)
}

if api.authController == nil {
authController, err := auth.NewAuthController(password)
if err != nil {
return nil, fmt.Errorf("new auth controller: %w", err)
}
api.authController = authController
}

if api.consoleController == nil {
consoleController, err := console.NewConsoleController()
if err != nil {
return nil, fmt.Errorf("new console controller: %w", err)
}
api.consoleController = consoleController
}

if api.installController == nil {
installController, err := install.NewInstallController()
if err != nil {
return nil, fmt.Errorf("new install controller: %w", err)
}
api.installController = installController
}

if api.logger == nil {
api.logger = NewDiscardLogger()
}

return api, nil
}

func (a *API) RegisterRoutes(router *mux.Router) {
router.HandleFunc("/health", a.getHealth).Methods("GET")

router.HandleFunc("/auth/login", a.postAuthLogin).Methods("POST")
router.HandleFunc("/branding", a.getBranding).Methods("GET")

authenticatedRouter := router.PathPrefix("").Subrouter()
authenticatedRouter.Use(a.authMiddleware)

installRouter := authenticatedRouter.PathPrefix("/install").Subrouter()
installRouter.HandleFunc("", a.getInstall).Methods("GET")
installRouter.HandleFunc("/config", a.setInstallConfig).Methods("POST")
installRouter.HandleFunc("/status", a.setInstallStatus).Methods("POST")
installRouter.HandleFunc("/status", a.getInstallStatus).Methods("GET")

consoleRouter := authenticatedRouter.PathPrefix("/console").Subrouter()
consoleRouter.HandleFunc("/available-network-interfaces", a.getListAvailableNetworkInterfaces).Methods("GET")
}

func handleError(w http.ResponseWriter, err error) {
var apiErr *types.APIError
if !errors.As(err, &apiErr) {
apiErr = types.NewInternalServerError(err)
}
apiErr.JSON(w)
}
82 changes: 82 additions & 0 deletions api/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package api

import (
"encoding/json"
"errors"
"net/http"
"strings"

"github.com/replicatedhq/embedded-cluster/api/controllers/auth"
"github.com/replicatedhq/embedded-cluster/api/types"
)

type AuthRequest struct {
Password string `json:"password"`
}

type AuthResponse struct {
Token string `json:"token"`
}

func (a *API) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
err := errors.New("authorization header is required")
a.logger.WithFields(logrusFieldsFromRequest(r)).WithError(err).
Error("failed to authenticate")
types.NewUnauthorizedError(err).JSON(w)
return
}

if !strings.HasPrefix(token, "Bearer ") {
err := errors.New("authorization header must start with Bearer ")
a.logger.WithFields(logrusFieldsFromRequest(r)).WithError(err).
Error("failed to authenticate")
types.NewUnauthorizedError(err).JSON(w)
return
}

token = token[len("Bearer "):]

err := a.authController.ValidateToken(r.Context(), token)
if err != nil {
a.logger.WithFields(logrusFieldsFromRequest(r)).WithError(err).
Error("failed to validate token")
types.NewUnauthorizedError(err).JSON(w)
return
}

next.ServeHTTP(w, r)
})
}

func (a *API) postAuthLogin(w http.ResponseWriter, r *http.Request) {
var request AuthRequest
err := json.NewDecoder(r.Body).Decode(&request)
if err != nil {
a.logger.WithFields(logrusFieldsFromRequest(r)).WithError(err).
Error("failed to decode auth request")
types.NewBadRequestError(err).JSON(w)
return
}

token, err := a.authController.Authenticate(r.Context(), request.Password)
if errors.Is(err, auth.ErrInvalidPassword) {
types.NewUnauthorizedError(err).JSON(w)
return
}

if err != nil {
a.logger.WithFields(logrusFieldsFromRequest(r)).WithError(err).
Error("failed to authenticate")
types.NewInternalServerError(err).JSON(w)
return
}

response := AuthResponse{
Token: token,
}

json.NewEncoder(w).Encode(response)
}
48 changes: 48 additions & 0 deletions api/client/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package client

import (
"bytes"
"encoding/json"
"net/http"
)

// Login sends a login request to the API server with the provided password and retrieves a session token. The token is stored in the client struct for subsequent requests.
func (c *client) Login(password string) error {
loginReq := struct {
Password string `json:"password"`
}{
Password: password,
}

b, err := json.Marshal(loginReq)
if err != nil {
return err
}

req, err := http.NewRequest("POST", c.apiURL+"/api/auth/login", bytes.NewBuffer(b))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")

resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return errorFromResponse(resp)
}

var loginResp struct {
Token string `json:"token"`
}
err = json.NewDecoder(resp.Body).Decode(&loginResp)
if err != nil {
return err
}

c.token = loginResp.Token
return nil
}
77 changes: 77 additions & 0 deletions api/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package client

import (
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/replicatedhq/embedded-cluster/api/types"
)

var defaultHTTPClient = &http.Client{
Transport: &http.Transport{
Proxy: nil, // This is a local client so no proxy is needed
},
}

type Client interface {
Login(password string) error
GetInstall() (*types.Install, error)
SetInstallConfig(config types.InstallationConfig) (*types.Install, error)
SetInstallStatus(status types.InstallationStatus) (*types.Install, error)
}

type client struct {
apiURL string
httpClient *http.Client
token string
}

type ClientOption func(*client)

func WithHTTPClient(httpClient *http.Client) ClientOption {
return func(c *client) {
c.httpClient = httpClient
}
}

func WithToken(token string) ClientOption {
return func(c *client) {
c.token = token
}
}

func New(apiURL string, opts ...ClientOption) Client {
c := &client{
apiURL: apiURL,
}
for _, opt := range opts {
opt(c)
}

if c.httpClient == nil {
c.httpClient = defaultHTTPClient
}

return c
}

func setAuthorizationHeader(req *http.Request, token string) {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}

func errorFromResponse(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("unexpected response: status=%d", resp.StatusCode)
}
var apiError types.APIError
err = json.Unmarshal(body, &apiError)
if err != nil {
return fmt.Errorf("unexpected response: status=%d, body=%q", resp.StatusCode, string(body))
}
return &apiError
}
Loading
Loading