-
Notifications
You must be signed in to change notification settings - Fork 149
/
auth_handler.go
199 lines (175 loc) · 5.43 KB
/
auth_handler.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
// Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpapi
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"go.uber.org/zap"
"github.com/pipe-cd/pipecd/pkg/config"
"github.com/pipe-cd/pipecd/pkg/jwt"
"github.com/pipe-cd/pipecd/pkg/model"
)
const (
rootPath = "/"
// loginPath is the path to login to pipecd projects.
loginPath = "/auth/login"
// staticLoginPath is the path to login to pipecd projects with password.
staticLoginPath = "/auth/login/static"
// callbackPath is the path configured in the GitHub oauth application settings.
callbackPath = "/auth/callback"
// logoutPath is the path for logging out from current session.
logoutPath = "/auth/logout"
projectFormKey = "project"
usernameFormKey = "username"
passwordFormKey = "password"
authCodeFormKey = "code"
stateFormKey = "state"
stateCookieKey = "state"
errorCookieKey = "error"
defaultTokenTTL = 7 * 24 * time.Hour
defaultStateCookieMaxAge = 30 * 60
defaultErrorCookieMaxAge = 10 * 60
defaultTokenCookieMaxAge = 7 * 24 * 60 * 60
)
type projectGetter interface {
Get(ctx context.Context, id string) (*model.Project, error)
}
type decrypter interface {
Decrypt(encryptedText string) (string, error)
}
// authHandler handles all imcoming requests about authentication.
type authHandler struct {
signer jwt.Signer
decrypter decrypter
callbackURL string
stateKey string
projectsInConfig map[string]config.ControlPlaneProject
sharedSSOConfigs map[string]*model.ProjectSSOConfig
projectGetter projectGetter
secureCookie bool
logger *zap.Logger
}
// newHandler returns a handler that will used for authentication.
func newAuthHandler(
signer jwt.Signer,
decrypter decrypter,
address string,
stateKey string,
projectsInConfig map[string]config.ControlPlaneProject,
sharedSSOConfigs map[string]*model.ProjectSSOConfig,
projectGetter projectGetter,
secureCookie bool,
logger *zap.Logger,
) *authHandler {
return &authHandler{
signer: signer,
decrypter: decrypter,
callbackURL: strings.TrimSuffix(address, "/") + callbackPath,
stateKey: stateKey,
projectsInConfig: projectsInConfig,
sharedSSOConfigs: sharedSSOConfigs,
projectGetter: projectGetter,
secureCookie: secureCookie,
logger: logger,
}
}
// handleLogout cleans current cookies and redirects to login page.
func (h *authHandler) handleLogout(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
http.SetCookie(w, makeExpiredTokenCookie(h.secureCookie))
http.SetCookie(w, makeExpiredStateCookie(h.secureCookie))
http.Redirect(w, r, rootPath, http.StatusFound)
}
func (h *authHandler) findSSOConfig(p *model.Project) (sso *model.ProjectSSOConfig, shared bool, err error) {
if p.SharedSsoName == "" {
if p.Sso == nil {
return nil, false, fmt.Errorf("missing SSO configuration in project data")
}
return p.Sso, false, nil
}
sso, ok := h.sharedSSOConfigs[p.SharedSsoName]
if ok {
return sso, true, nil
}
return nil, false, fmt.Errorf("not found shared sso configuration %s", p.SharedSsoName)
}
// handleError redirects to the root path and saves the error message to the cookie.
// Web will use that cookie data to handle auth error.
func (h *authHandler) handleError(w http.ResponseWriter, r *http.Request, responseMessage string, err error) {
if err != nil {
h.logger.Error(fmt.Sprintf("auth-handler: %s", responseMessage), zap.Error(err))
} else {
h.logger.Info(fmt.Sprintf("auth-handler: %s", responseMessage))
}
http.SetCookie(w, makeErrorCookie(responseMessage, h.secureCookie))
http.Redirect(w, r, rootPath, http.StatusSeeOther)
}
func makeTokenCookie(value string, secure bool) *http.Cookie {
return &http.Cookie{
Name: jwt.SignedTokenKey,
Value: value,
MaxAge: defaultTokenCookieMaxAge,
Path: rootPath,
Secure: secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}
func makeExpiredTokenCookie(secure bool) *http.Cookie {
return &http.Cookie{
Name: jwt.SignedTokenKey,
Value: "",
MaxAge: -1,
Path: rootPath,
Secure: secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}
func makeStateCookie(value string, secure bool) *http.Cookie {
return &http.Cookie{
Name: stateCookieKey,
Value: value,
MaxAge: defaultStateCookieMaxAge,
Path: rootPath,
Secure: secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}
func makeExpiredStateCookie(secure bool) *http.Cookie {
return &http.Cookie{
Name: stateCookieKey,
Value: "",
MaxAge: -1,
Path: rootPath,
Secure: secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}
}
func makeErrorCookie(value string, secure bool) *http.Cookie {
return &http.Cookie{
Name: errorCookieKey,
Value: value,
MaxAge: defaultErrorCookieMaxAge,
Path: rootPath,
Secure: secure,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
}
}