lavender/server/flow.go

236 lines
6.6 KiB
Go
Raw Normal View History

2023-10-01 21:44:49 +01:00
package server
import (
"context"
2023-10-01 21:44:49 +01:00
_ "embed"
2023-10-04 14:51:38 +01:00
"encoding/json"
"fmt"
2023-10-09 16:29:10 +01:00
"github.com/1f349/lavender/issuer"
"github.com/1f349/lavender/server/pages"
2023-11-03 07:39:58 +00:00
"github.com/1f349/mjwt/auth"
"github.com/1f349/mjwt/claims"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
2023-10-01 21:44:49 +01:00
"github.com/julienschmidt/httprouter"
"golang.org/x/oauth2"
2023-10-01 21:44:49 +01:00
"net/http"
"net/mail"
"net/url"
2023-10-04 14:51:38 +01:00
"strings"
2023-10-03 23:20:28 +01:00
"time"
2023-10-01 21:44:49 +01:00
)
2023-10-09 00:04:28 +01:00
var uuidNewStringState = uuid.NewString
var uuidNewStringAti = uuid.NewString
var uuidNewStringRti = uuid.NewString
2023-10-09 16:29:10 +01:00
var testOa2Exchange = func(oa2conf oauth2.Config, ctx context.Context, code string) (*oauth2.Token, error) {
return oa2conf.Exchange(ctx, code)
}
var testOa2UserInfo = func(oidc *issuer.WellKnownOIDC, ctx context.Context, exchange *oauth2.Token) (*http.Response, error) {
client := oidc.OAuth2Config.Client(ctx, exchange)
return client.Get(oidc.UserInfoEndpoint)
}
2023-10-01 21:44:49 +01:00
func (h *HttpServer) flowPopup(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
cookie, err := req.Cookie("lavender-login-name")
if err == nil && cookie.Valid() == nil {
pages.RenderPageTemplate(rw, "flow-popup-memory", map[string]any{
2023-11-15 09:21:09 +00:00
"ServiceName": h.conf.Load().ServiceName,
"Origin": req.URL.Query().Get("origin"),
"LoginName": cookie.Value,
})
return
}
2023-10-09 00:04:28 +01:00
pages.RenderPageTemplate(rw, "flow-popup", map[string]any{
2023-11-15 09:21:09 +00:00
"ServiceName": h.conf.Load().ServiceName,
2023-10-04 14:51:38 +01:00
"Origin": req.URL.Query().Get("origin"),
2023-10-01 21:44:49 +01:00
})
}
2023-10-03 23:20:28 +01:00
func (h *HttpServer) flowPopupPost(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
if req.PostFormValue("not-you") == "1" {
http.SetCookie(rw, &http.Cookie{
Name: "lavender-login-name",
Value: "",
Path: "/",
MaxAge: -1,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
http.Redirect(rw, req, (&url.URL{
Path: "/popup",
RawQuery: url.Values{
"origin": []string{req.PostFormValue("origin")},
}.Encode(),
}).String(), http.StatusFound)
return
}
loginName := req.PostFormValue("loginname")
2023-11-15 09:21:09 +00:00
login := h.manager.Load().FindServiceFromLogin(loginName)
2023-10-01 21:44:49 +01:00
if login == nil {
http.Error(rw, "No login service defined for this username", http.StatusBadRequest)
return
}
// the @ must exist if the service is defined
n := strings.IndexByte(loginName, '@')
loginUn := loginName[:n]
2023-10-01 21:44:49 +01:00
now := time.Now()
future := now.AddDate(1, 0, 0)
http.SetCookie(rw, &http.Cookie{
Name: "lavender-login-name",
Value: loginName,
Path: "/",
Expires: future,
MaxAge: int(future.Sub(now).Seconds()),
Secure: true,
SameSite: http.SameSiteStrictMode,
})
2023-10-04 14:51:38 +01:00
targetOrigin := req.PostFormValue("origin")
2023-11-15 09:21:09 +00:00
allowedService, found := (*h.services.Load())[targetOrigin]
2023-10-26 11:30:04 +01:00
if !found {
2023-10-04 14:51:38 +01:00
http.Error(rw, "Invalid target origin", http.StatusBadRequest)
2023-10-03 23:20:28 +01:00
return
}
// save state for use later
2023-10-09 00:04:28 +01:00
state := login.Config.Namespace + ":" + uuidNewStringState()
2023-10-03 23:20:28 +01:00
h.flowState.Set(state, flowStateData{
login,
2023-10-26 11:30:04 +01:00
allowedService,
2023-10-03 23:20:28 +01:00
}, time.Now().Add(15*time.Minute))
2023-10-01 21:44:49 +01:00
2023-10-03 23:20:28 +01:00
// generate oauth2 config and redirect to authorize URL
2023-10-04 14:51:38 +01:00
oa2conf := login.OAuth2Config
2023-11-15 09:21:09 +00:00
oa2conf.RedirectURL = h.conf.Load().BaseUrl + "/callback"
nextUrl := oa2conf.AuthCodeURL(state, oauth2.SetAuthURLParam("login_name", loginUn))
http.Redirect(rw, req, nextUrl, http.StatusFound)
2023-10-01 21:44:49 +01:00
}
2023-10-03 23:20:28 +01:00
func (h *HttpServer) flowCallback(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
err := req.ParseForm()
if err != nil {
http.Error(rw, "Error parsing form", http.StatusBadRequest)
return
}
2023-10-01 21:44:49 +01:00
2023-10-03 23:20:28 +01:00
q := req.URL.Query()
state := q.Get("state")
n := strings.IndexByte(state, ':')
2023-11-15 09:21:09 +00:00
if n == -1 || !h.manager.Load().CheckNamespace(state[:n]) {
2023-10-09 16:29:10 +01:00
http.Error(rw, "Invalid state namespace", http.StatusBadRequest)
2023-10-03 23:20:28 +01:00
return
}
v, found := h.flowState.Get(state)
if !found {
http.Error(rw, "Invalid state", http.StatusBadRequest)
return
}
oa2conf := v.sso.OAuth2Config
2023-11-15 09:21:09 +00:00
oa2conf.RedirectURL = h.conf.Load().BaseUrl + "/callback"
2023-10-09 16:29:10 +01:00
exchange, err := testOa2Exchange(oa2conf, context.Background(), q.Get("code"))
2023-10-04 14:51:38 +01:00
if err != nil {
fmt.Println("Failed exchange:", err)
2023-10-04 14:51:38 +01:00
http.Error(rw, "Failed to exchange code", http.StatusInternalServerError)
return
}
2023-10-09 16:29:10 +01:00
v2, err := testOa2UserInfo(v.sso, req.Context(), exchange)
2023-10-04 14:51:38 +01:00
if err != nil {
fmt.Println("Failed to get userinfo:", err)
2023-10-04 14:51:38 +01:00
http.Error(rw, "Failed to get userinfo", http.StatusInternalServerError)
return
}
defer v2.Body.Close()
if v2.StatusCode != http.StatusOK {
2023-10-09 16:29:10 +01:00
http.Error(rw, "Failed to get userinfo: unexpected status code", http.StatusInternalServerError)
2023-10-04 14:51:38 +01:00
return
}
var v3 map[string]any
if err = json.NewDecoder(v2.Body).Decode(&v3); err != nil {
fmt.Println("Failed to decode userinfo:", err)
2023-10-09 16:29:10 +01:00
http.Error(rw, "Failed to decode userinfo", http.StatusInternalServerError)
2023-10-04 14:51:38 +01:00
return
}
sub, ok := v3["sub"].(string)
if !ok {
2023-10-09 16:29:10 +01:00
http.Error(rw, "Invalid subject in userinfo", http.StatusInternalServerError)
return
}
aud, ok := v3["aud"].(string)
if !ok {
2023-10-09 16:29:10 +01:00
http.Error(rw, "Invalid audience in userinfo", http.StatusInternalServerError)
return
}
2023-10-27 09:40:10 +01:00
var needsMailFlag, needsDomains bool
2023-10-26 11:30:04 +01:00
ps := claims.NewPermStorage()
2023-10-26 11:30:04 +01:00
for _, i := range v.target.Permissions {
if strings.HasPrefix(i, "dynamic:") {
2023-10-27 09:40:10 +01:00
switch i {
case "dynamic:mail-client":
2023-10-26 11:30:04 +01:00
needsMailFlag = true
2023-10-27 09:40:10 +01:00
case "dynamic:domain-owns":
needsDomains = true
2023-10-26 11:30:04 +01:00
}
} else {
ps.Set(i)
}
2023-10-25 18:04:12 +01:00
}
2023-10-26 11:30:04 +01:00
if needsMailFlag {
if verified, ok := v3["email_verified"].(bool); ok && verified {
if mailAddress, ok := v3["email"].(string); ok {
address, err := mail.ParseAddress(mailAddress)
if err != nil {
http.Error(rw, "Invalid email in userinfo", http.StatusInternalServerError)
return
}
n := strings.IndexByte(address.Address, '@')
2023-11-15 09:21:09 +00:00
if n != -1 {
if address.Address[n+1:] == v.sso.Config.Namespace {
ps.Set("mail:client")
}
2023-10-26 11:30:04 +01:00
}
}
}
}
2023-10-27 09:40:10 +01:00
if needsDomains {
2023-11-15 09:21:09 +00:00
a := h.conf.Load().Users.AllDomains(sub + "@" + v.sso.Config.Namespace)
2023-10-27 09:40:10 +01:00
for _, i := range a {
ps.Set("domain:owns=" + i)
}
}
nsSub := sub + "@" + v.sso.Config.Namespace
2023-10-09 00:04:28 +01:00
ati := uuidNewStringAti()
accessToken, err := h.signer.GenerateJwt(nsSub, ati, jwt.ClaimStrings{aud}, 15*time.Minute, auth.AccessTokenClaims{
Perms: ps,
})
if err != nil {
http.Error(rw, "Error generating access token", http.StatusInternalServerError)
return
}
2023-10-09 00:04:28 +01:00
refreshToken, err := h.signer.GenerateJwt(nsSub, uuidNewStringRti(), jwt.ClaimStrings{aud}, 15*time.Minute, auth.RefreshTokenClaims{AccessTokenId: ati})
if err != nil {
http.Error(rw, "Error generating refresh token", http.StatusInternalServerError)
return
}
2023-10-09 00:04:28 +01:00
pages.RenderPageTemplate(rw, "flow-callback", map[string]any{
2023-11-15 09:21:09 +00:00
"ServiceName": h.conf.Load().ServiceName,
2023-10-26 11:30:04 +01:00
"TargetOrigin": v.target.Url.String(),
2023-10-04 14:51:38 +01:00
"TargetMessage": v3,
"AccessToken": accessToken,
"RefreshToken": refreshToken,
2023-10-04 14:51:38 +01:00
})
2023-10-01 21:44:49 +01:00
}