Skip to content

Commit

Permalink
add node login command
Browse files Browse the repository at this point in the history
  • Loading branch information
djelusic committed Mar 3, 2022
1 parent 047679a commit 7d04f04
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 89 deletions.
3 changes: 1 addition & 2 deletions cli/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ func root() *cobra.Command {
//examples.NewErrorsCommand,
//examples.NewArgsCommand,
examples.NewGithubAuthCommand,
examples.NewUserCommand,
examples.NewLogoutCommand,
examples.NewNodeCommand,
}
for _, sub := range subCommands {
add(sub)
Expand Down
2 changes: 1 addition & 1 deletion cli/controller/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const (
func AuthToken(n *domain.Node) (string, error) {
t, err := n.AuthToken()
var terr *domain.TokenExpiredError
if errors.As(err, &terr) && n.GitHubAuthEnabled {
if errors.As(err, &terr) && n.GithubID != "" {
var err error
t, err = githubAuth(n)
if err != nil {
Expand Down
45 changes: 37 additions & 8 deletions cli/controller/examples/node_example.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@ import (
"github.com/spf13/cobra"
)

func NewUserCommand() *cobra.Command {
func NewNodeCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "user",
Use: "node",
Hidden: true,
}
cmd.AddCommand(NewUserAddCommand())
cmd.AddCommand(NewLoginCommand())
cmd.AddCommand(NewLogoutCommand())
return cmd
}

func NewUserAddCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "add",
Use: "user-add",
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
node := cmd.Flag("node").Value.String()
Expand Down Expand Up @@ -62,12 +64,31 @@ func NewUserAddCommand() *cobra.Command {
return cmd
}

func nodeInvoker(node *domain.Node) (*invoke.HTTPClient, error) {
t, err := controller.AuthToken(node)
if err != nil {
return nil, err
func NewLoginCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Hidden: true,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
nodeURL := args[0]
i := invoke.Node(nodeURL, "", ui.NodeLogsSink)
var rsp dto.LoginResponse
if err := i.Do("auth/login", nil, &rsp); err != nil {
return err
}
fs, err := domain.NewSingleDeveloperWorkspaceStore()
if err != nil {
return err
}
w := fs.Workspace()
w.AddNode(rsp.Node)
return fs.Store()
// buf, _ := json.Marshal(rsp)
// fmt.Println(string(buf))
// return nil
},
}
return invoke.Node(node.Endpoints.Rest, t, ui.NodeLogsSink), nil
return cmd
}

func NewLogoutCommand() *cobra.Command {
Expand Down Expand Up @@ -95,3 +116,11 @@ func NewLogoutCommand() *cobra.Command {
cmd.Flags().StringP("node", "", domain.DefaultNodeName, "")
return cmd
}

func nodeInvoker(node *domain.Node) (*invoke.HTTPClient, error) {
t, err := controller.AuthToken(node)
if err != nil {
return nil, err
}
return invoke.Node(node.Endpoints.Rest, t, ui.NodeLogsSink), nil
}
29 changes: 9 additions & 20 deletions cli/controller/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ type stackTemplateData struct {
Region string
Suffix string
APIGatewayLogsRole string
Env map[string]string
}

func NewSetup(a *SetupArgs) (*Setup, error) {
Expand Down Expand Up @@ -83,8 +84,7 @@ Available regions are:
}
ws := c.store.Workspace()
bucket, key := getPath(c.aws.Region())
ghAuth := c.githubID != ""
n, err := ws.NewNode(c.nodeName, c.aws.AccountID(), c.aws.Region(), bucket, key, version, ghAuth)
n, err := ws.NewNode(c.nodeName, c.aws.AccountID(), c.aws.Region(), bucket, key, version, c.githubID)
if err != nil {
return log.Wrap(err)
}
Expand Down Expand Up @@ -113,27 +113,21 @@ func (c *Setup) regionSupported() bool {

func (c *Setup) create(n *domain.Node) error {
tmr := timerFn()
if err := c.createSetupStack(n.Functions, n.ResourceSuffix()); err != nil {
if err := c.createSetupStack(n.Functions, n.ResourceSuffix(), n.SetupEnv()); err != nil {
return log.Wrap(err)
}
stackDuration := tmr()

ui.Info("")
ui.Title("Setting up AWS infrastructure\n")
req := &dto.SetupRequest{
BucketConfig: dto.SetupBucketConfig{
BucketConfig: &dto.SetupBucketConfig{
Name: n.Bucket,
ExpirePrefix: domain.FunctionsBucketPrefix,
ExpireDays: domain.FunctionsBucketExpireDays,
},
FunctionsBucket: n.Functions.Bucket,
FunctionsPath: n.Functions.Path,
AuthEnv: n.AuthEnv(),
ResourceSuffix: n.ResourceSuffix(),
NamingTemplate: n.ResourceNamingTemplate(),
Node: n,
APIGatewayLogsRole: APIGatewayLogsRole,
ResourceTags: c.resourceTags,
GithubID: c.githubID,
}
rsp := &dto.SetupResponse{}
if err := invoke.Lambda(c.aws.Lambda(), c.lambdaName, ui.NodeLogsSink).Do("create", req, rsp); err != nil {
Expand All @@ -158,14 +152,15 @@ func (c *Setup) backendExists() (bool, error) {
return c.aws.LambdaExists(c.lambdaName)
}

func (c *Setup) createSetupStack(acf domain.NodeFunctions, suffix string) error {
func (c *Setup) createSetupStack(acf domain.NodeFunctions, suffix string, env map[string]string) error {
td := stackTemplateData{
Name: c.stackName,
Bucket: acf.Bucket,
S3Key: fmt.Sprintf("%s/setup.zip", acf.Path),
Region: c.aws.Region(),
Suffix: suffix,
APIGatewayLogsRole: APIGatewayLogsRole,
Env: env,
}
t, err := c.renderStackTemplate(td)
if err != nil {
Expand Down Expand Up @@ -219,16 +214,10 @@ func (c *Setup) upgrade(n *domain.Node) error {
ui.Info("")
ui.Title("Upgrading AWS infrastructure\n")
req := &dto.SetupRequest{
BucketConfig: dto.SetupBucketConfig{
BucketConfig: &dto.SetupBucketConfig{
Name: n.Bucket,
},
FunctionsBucket: n.Functions.Bucket,
FunctionsPath: n.Functions.Path,
AuthEnv: n.AuthEnv(),
ResourceSuffix: n.ResourceSuffix(),
NamingTemplate: n.ResourceNamingTemplate(),
ResourceTags: c.resourceTags,
GithubID: c.githubID,
Node: n,
}
if err := invoke.Lambda(c.aws.Lambda(), c.lambdaName, ui.NodeLogsSink).Do("upgrade", req, nil); err != nil {
return log.Wrap(err, "failed to invoke setup function")
Expand Down
21 changes: 21 additions & 0 deletions cli/controller/setup_stack_template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,22 @@ Resources:
- ssm:DeleteParameter
Resource:
- "*"
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:DescribeContinuousBackups
- dynamodb:ListTagsOfResource
- dynamodb:TagResource
- dynamodb:DescribeTimeToLive
- dynamodb:CreateTable
- dynamodb:Query
- dynamodb:PutItem
- dynamodb:GetItem
- dynamodb:BatchWriteItem
- dynamodb:BatchGetItem
- dynamodb:DeleteItem
Resource:
- "arn:aws:dynamodb:*:*:table/mantil-kv-{{.Suffix}}"
MantilSetupLambda:
Type: AWS::Lambda::Function
Properties:
Expand All @@ -133,6 +149,11 @@ Resources:
Role: !GetAtt
- MantilSetupRole
- Arn
Environment:
Variables:
{{- range $key, $value := .Env}}
{{$key}}: "{{$value}}"
{{- end}}
DependsOn:
- MantilSetupRole
- MantilSetupLambdaLogGroup
Expand Down
3 changes: 3 additions & 0 deletions cli/controller/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ func TestRenderTemplate(t *testing.T) {
Region: "region",
Suffix: "suffix",
APIGatewayLogsRole: "logs-role",
Env: map[string]string{
"key": "value",
},
}
s := &Setup{}
actual, err := s.renderStackTemplate(td)
Expand Down
19 changes: 19 additions & 0 deletions cli/controller/testdata/template.yml
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,22 @@ Resources:
- ssm:DeleteParameter
Resource:
- "*"
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:DescribeContinuousBackups
- dynamodb:ListTagsOfResource
- dynamodb:TagResource
- dynamodb:DescribeTimeToLive
- dynamodb:CreateTable
- dynamodb:Query
- dynamodb:PutItem
- dynamodb:GetItem
- dynamodb:BatchWriteItem
- dynamodb:BatchGetItem
- dynamodb:DeleteItem
Resource:
- "arn:aws:dynamodb:*:*:table/mantil-kv-suffix"
MantilSetupLambda:
Type: AWS::Lambda::Function
Properties:
Expand All @@ -133,6 +149,9 @@ Resources:
Role: !GetAtt
- MantilSetupRole
- Arn
Environment:
Variables:
key: "value"
DependsOn:
- MantilSetupRole
- MantilSetupLambdaLogGroup
Expand Down
1 change: 0 additions & 1 deletion domain/stage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ func TestStageResourceTags(t *testing.T) {
tags := stage.ResourceTags()
require.NotEmpty(t, tags)

require.Equal(t, "my-workspace-id", tags[TagWorkspace])
require.Equal(t, "abcdefg", tags[TagKey])
require.Equal(t, "my-project", tags[TagProjectName])
require.Equal(t, "my-stage", tags[TagStageName])
Expand Down
36 changes: 27 additions & 9 deletions domain/workspace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ const (
SSMPrivateKey = "private_key"
SSMGithubIDKey = "github_id"

NodeConfigKey = "config"

TagWorkspace = EnvWorkspace
TagKey = EnvKey
TagProjectName = EnvProjectName
Expand Down Expand Up @@ -68,8 +70,8 @@ type Node struct {
Functions NodeFunctions `yaml:"functions"`
Stages []*NodeStage `yaml:"stages,omitempty"`

GitHubAuthEnabled bool `yaml:"github_auth_enabled,omitempty"`
JWT string `yaml:"jwt,omitempty"`
GithubID string `yaml:"github_id,omitempty"`
JWT string `yaml:"jwt,omitempty"`

workspace *Workspace
}
Expand Down Expand Up @@ -100,6 +102,13 @@ func newWorkspace() *Workspace {
}
}

func (w *Workspace) AddNode(n *Node) {
if w.nodeExists(n.Name) {
return
}
w.Nodes = append(w.Nodes, n)
}

func (w *Workspace) RemoveNode(name string) {
for idx, a := range w.Nodes {
if a.Name == name {
Expand All @@ -118,7 +127,7 @@ func (w *Workspace) Node(name string) *Node {
return nil
}

func (w *Workspace) NewNode(name, awsAccountID, awsRegion, functionsBucket, functionsPath, version string, githubAuth bool) (*Node, error) {
func (w *Workspace) NewNode(name, awsAccountID, awsRegion, functionsBucket, functionsPath, version string, githubID string) (*Node, error) {
if w.nodeExists(name) {
return nil, errors.WithStack(&NodeExistsError{name})
}
Expand All @@ -137,8 +146,8 @@ func (w *Workspace) NewNode(name, awsAccountID, awsRegion, functionsBucket, func
},
workspace: w,
}
if githubAuth {
a.GitHubAuthEnabled = true
if githubID != "" {
a.GithubID = githubID
} else {
publicKey, privateKey, err := token.KeyPair()
if err != nil {
Expand All @@ -164,8 +173,7 @@ func (w *Workspace) nodeExists(name string) bool {

func (n *Node) ResourceTags() map[string]string {
return map[string]string{
TagWorkspace: n.workspace.ID,
TagKey: n.ID,
TagKey: n.ID,
}
}

Expand All @@ -178,17 +186,27 @@ func (n *Node) UpgradeVersion(version, functionsBbucket, functionsPath string) {
func (n *Node) AuthEnv() map[string]string {
return map[string]string{
EnvPublicKey: n.Keys.Public,
EnvKVTable: fmt.Sprintf("mantil-kv-%s", n.ID),
EnvKVTable: n.KVTableName(),
EnvSSMPathPrefix: fmt.Sprintf("/mantil-node-%s", n.ID),
}
}

func (n *Node) SetupEnv() map[string]string {
return map[string]string{
EnvKVTable: n.KVTableName(),
}
}

func (w *Workspace) afterRestore() {
for _, n := range w.Nodes {
n.workspace = w
}
}

func (n *Node) KVTableName() string {
return fmt.Sprintf("mantil-kv-%s", n.ID)
}

const (
nodeResourcePrefix = "mantil-setup"
)
Expand Down Expand Up @@ -266,7 +284,7 @@ func Factory(w *Workspace, p *Project, e *EnvironmentConfig) error {
}

func (n *Node) AuthToken() (string, error) {
if !n.GitHubAuthEnabled {
if n.GithubID == "" {
claims := &AccessTokenClaims{
Role: Owner,
Workspace: n.workspace.ID,
Expand Down
Loading

0 comments on commit 7d04f04

Please sign in to comment.