Skip to content

Commit 20b1c39

Browse files
authored
metadata server: redirect security-credentials when no trailing slash (uswitch#121)
* metadata server: redirect security-credentials when no trailing slash * aws metadata api uses a permanent redirect so we use the same
1 parent 47c4922 commit 20b1c39

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

pkg/aws/metadata/handler_role_name.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
log "github.com/sirupsen/logrus"
2323
"github.com/uswitch/kiam/pkg/server"
2424
"net/http"
25+
"net/url"
2526
"time"
2627
)
2728

@@ -30,10 +31,22 @@ type roleHandler struct {
3031
clientIP clientIPFunc
3132
}
3233

34+
func trailingSlashSuffixRedirectHandler(rw http.ResponseWriter, req *http.Request) {
35+
u, err := url.Parse(req.URL.String())
36+
if err != nil {
37+
log.Errorf("error parsing uri: %s", err)
38+
http.Error(rw, "error parsing uri", http.StatusInternalServerError)
39+
return
40+
}
41+
42+
u.Path = fmt.Sprintf("%s/", u.Path)
43+
http.Redirect(rw, req, u.String(), http.StatusPermanentRedirect)
44+
}
45+
3346
func (h *roleHandler) Install(router *mux.Router) {
3447
handler := adapt(withMeter("roleName", h))
35-
router.Handle("/{version}/meta-data/iam/security-credentials", handler)
3648
router.Handle("/{version}/meta-data/iam/security-credentials/", handler)
49+
router.HandleFunc("/{version}/meta-data/iam/security-credentials", trailingSlashSuffixRedirectHandler)
3750
}
3851

3952
func (h *roleHandler) Handle(ctx context.Context, w http.ResponseWriter, req *http.Request) (int, error) {

pkg/aws/metadata/handler_role_name_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,18 @@ import (
1212
"time"
1313
)
1414

15+
func TestRedirectsToCanonicalPath(t *testing.T) {
16+
r, _ := http.NewRequest("GET", "/latest/meta-data/iam/security-credentials", nil)
17+
rr := httptest.NewRecorder()
18+
19+
handler := newHandler(nil)
20+
handler.ServeHTTP(rr, r)
21+
22+
if rr.Code != http.StatusPermanentRedirect {
23+
t.Error("expected redirect, was", rr.Code)
24+
}
25+
}
26+
1527
func TestReturnRoleWhenClientResponds(t *testing.T) {
1628
r, _ := http.NewRequest("GET", "/latest/meta-data/iam/security-credentials/", nil)
1729
rr := httptest.NewRecorder()

0 commit comments

Comments
 (0)