-
Notifications
You must be signed in to change notification settings - Fork 1
/
accounts.go
245 lines (230 loc) · 7.01 KB
/
accounts.go
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package gateway
import (
_ "embed"
"fmt"
"log/slog"
"net/http"
"net/http/httputil"
"strings"
"github.com/verifa/horizon/pkg/auth"
"github.com/verifa/horizon/pkg/extensions/accounts"
"github.com/verifa/horizon/pkg/extensions/serviceaccounts"
"github.com/verifa/horizon/pkg/hz"
"github.com/go-chi/chi/v5"
"github.com/nats-io/nats.go"
)
type AccountsHandler struct {
Middleware chi.Middlewares
Conn *nats.Conn
Auth *auth.Auth
Portals map[string]hz.Portal
}
func (h *AccountsHandler) Router() *chi.Mux {
r := chi.NewRouter()
r.Use(h.Middleware...)
r.Use(h.middlewareAccount)
r.Get("/", h.getAccount)
r.Get("/serviceaccounts", h.getServiceAccounts)
r.Post("/serviceaccounts", h.postServiceAccounts)
r.Delete("/serviceaccounts/{name}", h.deleteServiceAccounts)
r.HandleFunc("/portal/{portal}", h.servePortal)
r.HandleFunc("/portal/{portal}/*", h.servePortal)
return r
}
func (h *AccountsHandler) middlewareAccount(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
account := chi.URLParam(r, "account")
if account == "" {
http.Error(w, "account not found", http.StatusNotFound)
return
}
ok, err := h.Auth.Check(r.Context(), auth.CheckRequest{
Session: hz.SessionFromRequest(r),
Verb: auth.VerbRead,
Object: hz.ObjectKey{
Group: accounts.ObjectGroup,
Kind: accounts.ObjectKind,
Account: hz.RootAccount,
Name: account,
},
})
if err != nil {
httpError(w, err)
return
}
if !ok {
// TODO: display a prettty 403 page instead.
http.Error(w, "forbidden", http.StatusForbidden)
return
}
client := hz.Client{
Conn: h.Conn,
Session: hz.SessionFromRequest(r),
}
if _, err := client.Get(r.Context(), hz.WithGetKey(hz.ObjectKey{
Group: accounts.ObjectGroup,
Version: accounts.ObjectVersion,
Kind: accounts.ObjectKind,
Account: hz.RootAccount,
Name: account,
})); err != nil {
// TODO: display a pretty 404 page instead.
httpError(w, err)
return
}
next.ServeHTTP(w, r.WithContext(r.Context()))
})
}
func (h *AccountsHandler) getAccount(w http.ResponseWriter, r *http.Request) {
userInfo, ok := r.Context().Value(authContext).(auth.UserInfo)
if !ok {
http.Error(w, "no auth context", http.StatusUnauthorized)
return
}
account := chi.URLParam(r, "account")
body := accountLayout(account, h.Portals, accountPage())
layout("Account", &userInfo, body).Render(r.Context(), w)
}
func (h *AccountsHandler) getServiceAccounts(
w http.ResponseWriter,
r *http.Request,
) {
userInfo, ok := r.Context().Value(authContext).(auth.UserInfo)
if !ok {
http.Error(w, "no auth context", http.StatusUnauthorized)
return
}
account := chi.URLParam(r, "account")
if r.Header.Get("HX-Request") == "true" {
client := hz.NewClient(h.Conn, hz.WithClientSessionFromRequest(r))
saClient := hz.ObjectClient[serviceaccounts.ServiceAccount]{
Client: client,
}
svAccs, err := saClient.List(r.Context())
if err != nil {
httpError(w, err)
return
}
_ = serviceAccountsTableBody(account, svAccs).Render(r.Context(), w)
return
}
body := accountLayout(
hz.RootAccount,
h.Portals,
serviceAccountsPage(account),
)
layout("Service Accounts", &userInfo, body).Render(r.Context(), w)
}
func (h *AccountsHandler) postServiceAccounts(
w http.ResponseWriter,
r *http.Request,
) {
account := chi.URLParam(r, "account")
name := r.FormValue("serviceaccount-name")
sa := serviceaccounts.ServiceAccount{
ObjectMeta: hz.ObjectMeta{
Name: name,
Account: account,
},
}
slog.Info("creating service account", "account", account, "name", name)
client := hz.NewClient(h.Conn, hz.WithClientSessionFromRequest(r))
if err := client.Create(r.Context(), hz.WithCreateObject(sa)); err != nil {
_ = serviceAccountsForm(account, sa, err).Render(r.Context(), w)
return
}
w.Header().Add("HX-Trigger", "loadServiceAccounts")
w.WriteHeader(http.StatusCreated)
_ = serviceAccountsForm(
account,
serviceaccounts.ServiceAccount{},
nil,
).Render(r.Context(), w)
}
func (h *AccountsHandler) deleteServiceAccounts(
w http.ResponseWriter,
r *http.Request,
) {
account := chi.URLParam(r, "account")
name := chi.URLParam(r, "name")
sa := serviceaccounts.ServiceAccount{
ObjectMeta: hz.ObjectMeta{
Name: name,
Account: account,
},
}
slog.Info("deleting service account", "account", account, "name", name)
client := hz.NewClient(h.Conn, hz.WithClientSessionFromRequest(r))
if err := client.Delete(r.Context(), hz.WithDeleteObject(sa)); err != nil {
slog.Error("error deleting service account", "error", err)
httpError(w, err)
return
}
w.Header().Add("HX-Trigger", "loadServiceAccounts")
w.WriteHeader(http.StatusNoContent)
}
func (h *AccountsHandler) servePortal(
w http.ResponseWriter,
r *http.Request,
) {
userInfo, ok := r.Context().Value(authContext).(auth.UserInfo)
if !ok {
http.Error(w, "no auth context", http.StatusUnauthorized)
return
}
account := chi.URLParam(r, "account")
portal := chi.URLParam(r, "portal")
subpath := chi.URLParam(r, "*")
// If the request accepts text/event-stream it is an SSE connection request.
// SSE connection requests should be handled by the portal.
isEventStream := r.Header.Get("Accept") == "text/event-stream"
// If the request is an HX request, it should be handled by the portal.
isHXRequest := r.Header.Get("HX-Request") == "true"
isHZPortalLoad := r.Header.Get("HZ-Portal-Load-Request") == "true"
if isHXRequest || isEventStream {
if isHZPortalLoad {
r.Header.Del("HX-Request")
r.Header.Del("HZ-Portal-Load-Request")
}
proxy := httputil.ReverseProxy{}
proxy.Rewrite = func(req *httputil.ProxyRequest) {
// Remove prefix from the request URL.
prefix := fmt.Sprintf("/accounts/%s/portal/%s", account, portal)
req.Out.URL.Path = strings.TrimPrefix(req.Out.URL.Path, prefix)
req.Out.Header.Set(hz.RequestAccount, account)
req.Out.Header.Set(hz.RequestPortal, portal)
req.SetXForwarded()
}
proxy.Transport = &NATSHTTPTransport{
conn: h.Conn,
subject: fmt.Sprintf(hz.SubjectPortalRender, portal),
account: account,
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
// NOTE: this only handles errors returned from the proxy.
// I.e. if an HTTP response is received, then it is not considered
// an error.
w.WriteHeader(http.StatusOK)
_ = portalError(err).Render(r.Context(), w)
}
// This is one idea to handle errors returned from portals.
// Ideally portals should only return 2xx status codes, as per the
// HATEOS way of handling things.
// https://htmx.org/essays/hateoas/
// proxy.ModifyResponse = func(resp *http.Response) error {
// // Modify the response if the status code is not 2xx.
// if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// // Modify the response here to be 2xx for HTMX to render it.
// }
// return nil
// }
proxy.ServeHTTP(w, r)
return
}
body := accountLayout(
account,
h.Portals,
portalProxy(account, portal, subpath),
)
layout(portal, &userInfo, body).Render(r.Context(), w)
}