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

import (
	"bytes"
	"net/http"
	"text/template"
	"time"

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

	"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 credsAllowed = promauto.NewCounterVec(prometheus.CounterOpts{
	Namespace: "aws_access", // Legacy namespace
	Name:      "broker_cred_access_total",
	Help:      "Total number of credential accesses allowed by broker",
}, []string{"account", "region"})

type jsonCredential struct {
	AccessKeyId     *string    `json:"access_key"`
	SecretAccessKey *string    `json:"secret_key"`
	SessionToken    *string    `json:"session_token"`
	Expiration      *time.Time `json:"expiration"`
	ShortName       string     `json:"-"`
}

var (
	bashTemplate = template.Must(template.New("").Parse(
		`export AWS_CREDS_EXPIRATION="{{ .Expiration }}"
export AWS_ACCESS_KEY_ID="{{ .AccessKeyId }}"
export AWS_SECRET_ACCESS_KEY="{{ .SecretAccessKey }}"
export AWS_SESSION_TOKEN="{{ .SessionToken }}"
`))

	pslTemplate = template.Must(template.New("").Parse(
		`Set-Item -path env:AWS_CREDS_EXPIRATION -value '{{ .Expiration }}'
Set-Item -path env:AWS_ACCESS_KEY_ID -value '{{ .AccessKeyId }}'
Set-Item -path env:AWS_SECRET_ACCESS_KEY -value '{{ .SecretAccessKey }}'
Set-Item -path env:AWS_SESSION_TOKEN -value '{{ .SessionToken }}'
`))

	iniTemplate = template.Must(template.New("").Parse(
		`[profile {{ .ShortName }}]
aws_access_key_id={{ .AccessKeyId }}
aws_secret_access_key={{ .SecretAccessKey }}
aws_session_token={{ .SessionToken }}
expiration={{ .Expiration }}
`))
)

type APICredentialsHandler struct {
	*AWSAPI
}

func NewAPICredentialsHandler(a *AWSAPI) echo.HandlerFunc {
	al := &APICredentialsHandler{a}
	h := &controller.ContentTypeNegotiatingHandler{
		DefaultHandler: al.HandleJSONV1,
		Handlers: map[string]echo.HandlerFunc{
			contentTypeV1:              al.HandleJSONV1,
			contentTypeV2:              al.HandleJSONV1,
			contentTypeV2AWSBash:       al.HandleBashV2,
			contentTypeV2AWSPowershell: al.HandlePSLV2,
			contentTypeV2AWSConfig:     al.HandleINIV2,
		},
	}
	return h.Handle
}

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

	region := c.Param("region")
	creds, err := rc.AWS.AssumeRole(rc.Principal.Username, &region)
	if err != nil {
		if aws.IsRegionNotExist(err) {
			return nil, echo.NotFoundHandler(c)
		}
		c.Logger().Errorf("Error retrieving credentials: %w", err)
		return nil, echo.ErrInternalServerError
	}

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

	c.Response().Header().Set("Expires", creds.Expiration.Add(-5*time.Minute).Format(time.RFC1123))

	return &jsonCredential{
		AccessKeyId:     creds.AccessKeyId,
		SecretAccessKey: creds.SecretAccessKey,
		SessionToken:    creds.SessionToken,
		Expiration:      creds.Expiration,
		ShortName:       rc.Account.ShortName,
	}, nil
}

func (h *APICredentialsHandler) renderTemplate(c echo.Context, t *template.Template, ct string) error {
	creds, err := h.getAWSCredential(c)
	if err != nil {
		return err
	}

	buf := &bytes.Buffer{}
	if err = t.Execute(buf, creds); err != nil {
		return echo.ErrInternalServerError
	}

	return c.Blob(http.StatusOK, ct, buf.Bytes())
}

func (h *APICredentialsHandler) HandleJSONV1(c echo.Context) error {
	creds, err := h.getAWSCredential(c)
	if err != nil {
		return err
	}

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

func (h *APICredentialsHandler) HandleBashV2(c echo.Context) error {
	return h.renderTemplate(c, bashTemplate, contentTypeV2AWSBash)
}

func (h *APICredentialsHandler) HandlePSLV2(c echo.Context) error {
	return h.renderTemplate(c, pslTemplate, contentTypeV2AWSPowershell)
}

func (h *APICredentialsHandler) HandleINIV2(c echo.Context) error {
	return h.renderTemplate(c, iniTemplate, contentTypeV2AWSConfig)
}