aboutsummaryrefslogtreecommitdiff
path: root/app/controllers/api_console_redirect.go
blob: 2501a410dc95cc364c8cca6f1ab4e429dd29fb37 (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
package controllers

import (
	"net/http"

	"code.crute.us/mcrute/golib/echo/controller"
	"github.com/labstack/echo/v4"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
)

var consoleAllowed = promauto.NewCounterVec(prometheus.CounterOpts{
	Namespace: "aws_access", // Legacy Namespace
	Name:      "broker_console_access_total",
	Help:      "Total number of console logins allowed by broker",
}, []string{"account"})

type jsonConsoleUrl struct {
	ConsoleURL string `json:"console_url"`
}

type APIConsoleRedirectHandler struct {
	FederationIssuerEndpoint string
	*AWSAPI
}

func NewAPIConsoleRedirectHandler(a *AWSAPI, fe string) echo.HandlerFunc {
	al := &APIConsoleRedirectHandler{fe, a}
	h := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: al.Handle,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1: al.Handle,
			contentTypeV2: al.Handle,
		},
	}
	return h.Handle
}

func (h *APIConsoleRedirectHandler) Handle(c echo.Context) error {
	rc, err := h.GetContext(c) // Does all authorization checks
	if err != nil {
		return err
	}

	u, err := rc.AWS.GetFederationURL(rc.Principal.Username, h.FederationIssuerEndpoint)
	if err != nil {
		c.Logger().Errorf("Error fetching console URL: %w", err)
		return echo.ErrBadRequest
	}

	c.Logger().Infof(
		"Allowing '%s' to access account console '%s'",
		rc.Principal.Username, rc.Account.Name,
	)
	consoleAllowed.With(prometheus.Labels{
		"account": rc.Account.ShortName,
	}).Inc()

	if c.QueryParam("redirect") == "1" {
		return c.Redirect(http.StatusFound, u)
	} else {
		return c.JSON(http.StatusOK, &jsonConsoleUrl{u})
	}
}