auth/internal/auth/delivery/http/auth_http.go

373 lines
10 KiB
Go
Raw Normal View History

package http
import (
"crypto/subtle"
2022-01-13 20:49:41 +00:00
"fmt"
"path"
"strings"
"github.com/fasthttp/router"
json "github.com/goccy/go-json"
http "github.com/valyala/fasthttp"
2022-01-13 20:49:41 +00:00
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/xerrors"
"source.toby3d.me/toby3d/form"
"source.toby3d.me/toby3d/middleware"
"source.toby3d.me/website/indieauth/internal/auth"
"source.toby3d.me/website/indieauth/internal/client"
"source.toby3d.me/website/indieauth/internal/common"
"source.toby3d.me/website/indieauth/internal/domain"
"source.toby3d.me/website/indieauth/web"
)
type (
AuthorizeRequest struct {
2022-01-13 20:49:41 +00:00
// Indicates to the authorization server that an authorization
// code should be returned as the response.
ResponseType domain.ResponseType `form:"response_type"` // code
// The client URL.
ClientID *domain.ClientID `form:"client_id"`
// The redirect URL indicating where the user should be
// redirected to after approving the request.
RedirectURI *domain.URL `form:"redirect_uri"`
// A parameter set by the client which will be included when the
// user is redirected back to the client. This is used to
// prevent CSRF attacks. The authorization server MUST return
// the unmodified state value back to the client.
State string `form:"state"`
// The code challenge as previously described.
CodeChallenge string `form:"code_challenge"`
// The hashing method used to calculate the code challenge.
CodeChallengeMethod domain.CodeChallengeMethod `form:"code_challenge_method"`
// A space-separated list of scopes the client is requesting,
// e.g. "profile", or "profile create". If the client omits this
// value, the authorization server MUST NOT issue an access
// token for this authorization code. Only the user's profile
// URL may be returned without any scope requested.
Scope domain.Scopes `form:"scope"`
// The URL that the user entered.
Me *domain.Me `form:"me"`
}
2022-01-13 20:49:41 +00:00
VerifyRequest struct {
ClientID *domain.ClientID `form:"client_id"`
Me *domain.Me `form:"me"`
RedirectURI *domain.URL `form:"redirect_uri"`
CodeChallengeMethod domain.CodeChallengeMethod `form:"code_challenge_method"`
ResponseType domain.ResponseType `form:"response_type"`
Scope domain.Scopes `form:"scope[]"` // TODO(toby3d): fix parsing in form pkg
Authorize string `form:"authorize"`
CodeChallenge string `form:"code_challenge"`
State string `form:"state"`
}
ExchangeRequest struct {
2022-01-13 20:49:41 +00:00
GrantType domain.GrantType `form:"grant_type"` // authorization_code
2022-01-13 20:49:41 +00:00
// The authorization code received from the authorization
// endpoint in the redirect.
Code string `form:"code"`
2022-01-13 20:49:41 +00:00
// The client's URL, which MUST match the client_id used in the
// authentication request.
ClientID *domain.ClientID `form:"client_id"`
2022-01-13 20:49:41 +00:00
// The client's redirect URL, which MUST match the initial
// authentication request.
RedirectURI *domain.URL `form:"redirect_uri"`
2022-01-13 20:49:41 +00:00
// The original plaintext random string generated before
// starting the authorization request.
CodeVerifier string `form:"code_verifier"`
}
2022-01-13 20:49:41 +00:00
ExchangeResponse struct {
Me *domain.Me `json:"me"`
}
2022-01-13 20:49:41 +00:00
NewRequestHandlerOptions struct {
Auth auth.UseCase
Clients client.UseCase
Config *domain.Config
Matcher language.Matcher
}
2022-01-13 20:49:41 +00:00
RequestHandler struct {
clients client.UseCase
config *domain.Config
matcher language.Matcher
useCase auth.UseCase
}
)
2022-01-13 20:49:41 +00:00
func NewRequestHandler(opts NewRequestHandlerOptions) *RequestHandler {
return &RequestHandler{
clients: opts.Clients,
config: opts.Config,
matcher: opts.Matcher,
useCase: opts.Auth,
}
2022-01-13 20:49:41 +00:00
}
2022-01-13 20:49:41 +00:00
func (h *RequestHandler) Register(r *router.Router) {
chain := middleware.Chain{
middleware.CSRFWithConfig(middleware.CSRFConfig{
CookieSameSite: http.CookieSameSiteStrictMode,
CookieName: "_csrf",
TokenLookup: "form:_csrf",
CookieSecure: true,
CookieHTTPOnly: true,
2022-01-13 20:49:41 +00:00
Skipper: func(ctx *http.RequestCtx) bool {
matched, _ := path.Match("/api/*", string(ctx.Path()))
return ctx.IsPost() && matched
},
}),
middleware.BasicAuthWithConfig(middleware.BasicAuthConfig{
Skipper: func(ctx *http.RequestCtx) bool {
matched, _ := path.Match("/api/*", string(ctx.Path()))
return !matched
},
Validator: func(ctx *http.RequestCtx, login, password string) (bool, error) {
// TODO(toby3d): change this
return subtle.ConstantTimeCompare([]byte(login), []byte("admin")) == 1 &&
subtle.ConstantTimeCompare([]byte(password), []byte("hackme")) == 1, nil
},
2022-01-13 20:49:41 +00:00
}),
middleware.LogFmt(),
}
2022-01-13 20:49:41 +00:00
r.GET("/authorize", chain.RequestHandler(h.handleRender))
r.POST("/api/authorize", chain.RequestHandler(h.handleVerify))
r.POST("/authorize", chain.RequestHandler(h.handleExchange))
}
2022-01-13 20:49:41 +00:00
func (h *RequestHandler) handleRender(ctx *http.RequestCtx) {
req := new(AuthorizeRequest)
if err := req.bind(ctx); err != nil {
ctx.Error(err.Error(), http.StatusBadRequest)
return
}
2022-01-13 20:49:41 +00:00
client, err := h.clients.Discovery(ctx, req.ClientID)
if err != nil {
ctx.Error(err.Error(), http.StatusBadRequest)
return
}
2022-01-13 20:49:41 +00:00
if !client.ValidateRedirectURI(req.RedirectURI) {
ctx.Error("requested redirect_uri is not registered on client_id side", http.StatusBadRequest)
return
}
csrf, _ := ctx.UserValue(middleware.DefaultCSRFConfig.ContextKey).([]byte)
tags, _, _ := language.ParseAcceptLanguage(string(ctx.Request.Header.Peek(http.HeaderAcceptLanguage)))
tag, _, _ := h.matcher.Match(tags...)
2022-01-13 20:49:41 +00:00
ctx.SetContentType(common.MIMETextHTMLCharsetUTF8)
web.WriteTemplate(ctx, &web.AuthorizePage{
BaseOf: web.BaseOf{
Config: h.config,
Language: tag,
Printer: message.NewPrinter(tag),
},
Client: client,
2022-01-13 20:49:41 +00:00
CodeChallenge: req.CodeChallenge,
CodeChallengeMethod: req.CodeChallengeMethod,
CSRF: csrf,
2022-01-13 20:49:41 +00:00
Me: req.Me,
RedirectURI: req.RedirectURI,
ResponseType: req.ResponseType,
Scope: req.Scope,
State: req.State,
})
}
2022-01-13 20:49:41 +00:00
func (h *RequestHandler) handleVerify(ctx *http.RequestCtx) {
ctx.SetContentType(common.MIMEApplicationJSONCharsetUTF8)
2022-01-13 20:49:41 +00:00
encoder := json.NewEncoder(ctx)
2022-01-13 20:49:41 +00:00
req := new(VerifyRequest)
if err := req.bind(ctx); err != nil {
ctx.SetStatusCode(http.StatusBadRequest)
encoder.Encode(domain.Error{
Code: "invalid_request",
Description: err.Error(),
Frame: xerrors.Caller(1),
})
return
}
2022-01-13 20:49:41 +00:00
u := http.AcquireURI()
defer http.ReleaseURI(u)
req.RedirectURI.CopyTo(u)
2022-01-13 20:49:41 +00:00
if strings.EqualFold(req.Authorize, "deny") {
u.QueryArgs().Set("error", "access_denied")
u.QueryArgs().Set("error_description", "user deny authorization request")
ctx.Redirect(u.String(), http.StatusFound)
2022-01-13 20:49:41 +00:00
return
}
2022-01-13 20:49:41 +00:00
code, err := h.useCase.Generate(ctx, auth.GenerateOptions{
ClientID: req.ClientID,
RedirectURI: req.RedirectURI,
CodeChallenge: req.CodeChallenge,
CodeChallengeMethod: req.CodeChallengeMethod,
Scope: req.Scope,
Me: req.Me,
})
if err != nil {
ctx.SetStatusCode(http.StatusInternalServerError)
encoder.Encode(domain.Error{
Description: err.Error(),
Frame: xerrors.Caller(1),
})
2022-01-13 20:49:41 +00:00
return
}
2022-01-13 20:49:41 +00:00
for key, val := range map[string]string{
"code": code,
"iss": h.config.Server.GetRootURL(),
"state": req.State,
} {
u.QueryArgs().Set(key, val)
}
2022-01-13 20:49:41 +00:00
ctx.Redirect(u.String(), http.StatusFound)
}
2022-01-13 20:49:41 +00:00
func (h *RequestHandler) handleExchange(ctx *http.RequestCtx) {
ctx.SetContentType(common.MIMEApplicationJSONCharsetUTF8)
encoder := json.NewEncoder(ctx)
req := new(ExchangeRequest)
if err := req.bind(ctx); err != nil {
ctx.SetStatusCode(http.StatusBadRequest)
encoder.Encode(err)
return
}
2022-01-13 20:49:41 +00:00
me, err := h.useCase.Exchange(ctx, auth.ExchangeOptions{
Code: req.Code,
ClientID: req.ClientID,
RedirectURI: req.RedirectURI,
CodeVerifier: req.CodeVerifier,
})
if err != nil {
2022-01-13 20:49:41 +00:00
ctx.SetStatusCode(http.StatusBadRequest)
encoder.Encode(err)
return
}
2022-01-13 20:49:41 +00:00
encoder.Encode(&ExchangeResponse{
Me: me,
})
}
2022-01-13 20:49:41 +00:00
func (r *AuthorizeRequest) bind(ctx *http.RequestCtx) error {
if err := form.Unmarshal(ctx.QueryArgs(), r); err != nil {
return domain.Error{
Code: "invalid_request",
Description: err.Error(),
Frame: xerrors.Caller(1),
}
}
2022-01-13 20:49:41 +00:00
r.Scope = make(domain.Scopes, 0)
parseScope(r.Scope, ctx.QueryArgs().Peek("scope"))
if r.ResponseType == domain.ResponseTypeID {
r.ResponseType = domain.ResponseTypeCode
}
2022-01-13 20:49:41 +00:00
return nil
}
2022-01-13 20:49:41 +00:00
func (r *VerifyRequest) bind(ctx *http.RequestCtx) error {
if err := form.Unmarshal(ctx.PostArgs(), r); err != nil {
return domain.Error{
2022-01-13 20:49:41 +00:00
Code: "invalid_request",
Description: err.Error(),
Frame: xerrors.Caller(1),
}
}
2022-01-13 20:49:41 +00:00
r.Scope = make(domain.Scopes, 0)
parseScope(r.Scope, ctx.PostArgs().PeekMulti("scope[]")...)
if r.ResponseType == domain.ResponseTypeID {
r.ResponseType = domain.ResponseTypeCode
}
2022-01-13 20:49:41 +00:00
if !strings.EqualFold(r.Authorize, "allow") && !strings.EqualFold(r.Authorize, "deny") {
return domain.Error{
2022-01-13 20:49:41 +00:00
Code: "invalid_request",
Description: "cannot validate verification request",
Frame: xerrors.Caller(1),
}
}
2022-01-13 20:49:41 +00:00
return nil
}
func (r *ExchangeRequest) bind(ctx *http.RequestCtx) error {
if err := form.Unmarshal(ctx.PostArgs(), r); err != nil {
return domain.Error{
2022-01-13 20:49:41 +00:00
Code: "invalid_request",
Description: err.Error(),
Frame: xerrors.Caller(1),
}
}
return nil
}
2022-01-13 20:49:41 +00:00
// TODO(toby3d): fix this in form pkg.
func parseScope(dst domain.Scopes, src ...[]byte) error {
if len(src) == 0 {
return nil
}
2022-01-13 20:49:41 +00:00
var scopes []string
2022-01-13 20:49:41 +00:00
if len(src) == 1 {
scopes = strings.Fields(string(src[0]))
}
2022-01-13 20:49:41 +00:00
for _, rawScope := range scopes {
scope, err := domain.ParseScope(string(rawScope))
if err != nil {
return &domain.Error{
Code: "invalid_request",
Description: fmt.Sprintf("cannot parse scope: %v", err),
Frame: xerrors.Caller(1),
}
}
2022-01-13 20:49:41 +00:00
dst = append(dst, scope)
}
2022-01-13 20:49:41 +00:00
return nil
}