aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/api_account.go
blob: 8ef18cee302e6cfd9503a0051517613a170d7aa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package controllers

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"code.crute.us/mcrute/cloud-identity-broker/app/middleware"
	"code.crute.us/mcrute/cloud-identity-broker/app/models"
	"code.crute.us/mcrute/cloud-identity-broker/cloud/aws"

	glecho "code.crute.us/mcrute/golib/echo"
	"code.crute.us/mcrute/golib/echo/controller"
	"github.com/labstack/echo/v4"
)

type APIAccountHandler struct {
	Store      models.AccountStore
	AdminStore models.AccountStore
}

func (h *APIAccountHandler) Register(prefix string, r glecho.URLRouter, mw ...echo.MiddlewareFunc) {
	// This resource did not exist in the V1 API and thus has no V1
	// representation. We use the default handlers for V1 because otherwise
	// requests with V1 Accept headers would result in 406 Unacceptable errors.
	gh := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: h.HandleGet,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: h.HandleGet,
			contentTypeV2: h.HandleGet,
		},
	}
	r.GET(prefix, gh.Handle, mw...)

	ph := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: h.HandlePut,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: h.HandlePut,
			contentTypeV2: h.HandlePut,
		},
	}
	r.PUT(prefix, ph.Handle, mw...)

	poh := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: h.HandlePost,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: h.HandlePost,
			contentTypeV2: h.HandlePost,
		},
	}
	r.POST(prefix, poh.Handle, mw...)

	r.DELETE(prefix, h.HandleDelete, mw...)
}

func (h *APIAccountHandler) getPrincipalAndAccount(c echo.Context) (*models.User, *models.Account, error) {
	var err error
	ctx := context.Background()

	p, err := middleware.GetAuthorizedPrincipal(c)
	if err != nil {
		return nil, nil, echo.ErrUnauthorized
	}

	var a *models.Account
	if p.IsAdmin {
		a, err = h.AdminStore.GetForUser(ctx, c.Param("account"), p)
		if err != nil {
			return nil, nil, echo.NotFoundHandler(c)
		}
	} else {
		a, err = h.Store.GetForUser(ctx, c.Param("account"), p)
		if err != nil {
			return nil, nil, echo.NotFoundHandler(c)
		}
	}

	return p, a, nil
}

func (h *APIAccountHandler) HandleGet(c echo.Context) error {
	p, a, err := h.getPrincipalAndAccount(c)
	if err != nil {
		return err
	}

	// These fields are slightly sensitive and give away too many security
	// details about the account so they should only be visible to users who
	// can administer the account.
	if !a.CanBeModifiedBy(p) {
		a.VaultMaterial = ""
		a.Users = nil
	}

	return c.JSON(http.StatusOK, a)
}

func (h *APIAccountHandler) HandlePut(c echo.Context) error {
	var in models.Account
	if err := c.Echo().JSONSerializer.Deserialize(c, &in); err != nil {
		return echo.ErrBadRequest
	}

	p, a, err := h.getPrincipalAndAccount(c)
	if err != nil {
		return err
	}

	if !a.CanBeModifiedBy(p) {
		return echo.ErrForbidden
	}

	if in.ShortName != a.ShortName {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: "Account short_name can not be changed. Create a new account.",
		}
	}

	if in.AccountType != a.AccountType {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: "Account type can not be changed. Create a new account.",
		}
	}

	if in.Deleted != nil && a.Deleted == nil {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: "Use the DELETE method to delete a record",
		}
	}

	a.AccountNumber = in.AccountNumber
	a.Name = in.Name
	a.ConsoleSessionDuration = in.ConsoleSessionDuration
	a.VaultMaterial = in.VaultMaterial
	a.DefaultRegion = in.DefaultRegion
	a.Users = in.Users

	// PUT-ing Deleted equal to null effectively un-deletes the record
	a.Deleted = in.Deleted

	if err := h.Store.Put(context.Background(), a); err != nil {
		return echo.ErrInternalServerError
	}

	return c.String(http.StatusNoContent, "")
}

func (h *APIAccountHandler) HandlePost(c echo.Context) error {
	var in models.Account
	if err := c.Echo().JSONSerializer.Deserialize(c, &in); err != nil {
		return echo.ErrBadRequest
	}

	if _, err := h.AdminStore.Get(context.Background(), in.ShortName); err == nil {
		return &echo.HTTPError{
			Code:    http.StatusConflict,
			Message: "Account with short name already exists. Choose another short name.",
		}
	}

	if in.ConsoleSessionDuration < time.Hour {
		in.ConsoleSessionDuration = time.Hour
	}

	if in.ConsoleSessionDuration > 12*time.Hour {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: "Console duration is greater than the AWS maximum of 12 hours.",
		}
	}

	if in.Deleted != nil {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: "Can not create deleted account, set Deleted to null",
		}
	}

	if err := aws.ValidateVaultMaterial(in.VaultMaterial); err != nil {
		return &echo.HTTPError{
			Code:    http.StatusBadRequest,
			Message: fmt.Sprintf("Unable to access Vault material: %s", err),
		}
	}

	if err := h.Store.Put(context.Background(), &in); err != nil {
		return echo.ErrInternalServerError
	}

	c.Response().Header().Add("Location", glecho.URLFor(c, "/api/account", in.ShortName).String())

	return c.String(http.StatusCreated, "")
}

func (h *APIAccountHandler) HandleDelete(c echo.Context) error {
	p, a, err := h.getPrincipalAndAccount(c)
	if err != nil {
		return err
	}

	if a.CanBeModifiedBy(p) {
		if err := h.Store.Delete(context.Background(), a); err != nil {
			return echo.ErrInternalServerError
		}
	} else {
		return echo.ErrForbidden
	}

	return c.String(http.StatusNoContent, "")
}