150 lines
4.4 KiB
Go
150 lines
4.4 KiB
Go
package transport
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"aeternalis/server/internal/game"
|
|
"aeternalis/server/internal/store"
|
|
"github.com/coreos/go-oidc/v3/oidc"
|
|
"golang.org/x/oauth2"
|
|
)
|
|
|
|
type Auth struct {
|
|
db *store.DB
|
|
dev bool
|
|
base string
|
|
oauth *oauth2.Config
|
|
verifier *oidc.IDTokenVerifier
|
|
mu sync.Mutex
|
|
flows map[string]flow
|
|
}
|
|
type flow struct {
|
|
verifier string
|
|
expires time.Time
|
|
}
|
|
|
|
func NewAuth(ctx context.Context, db *store.DB, dev bool, base, issuer, client, secret string) (*Auth, error) {
|
|
a := &Auth{db: db, dev: dev, base: base, flows: map[string]flow{}}
|
|
if dev {
|
|
return a, nil
|
|
}
|
|
if !strings.HasPrefix(base, "https://") || !strings.HasPrefix(issuer, "https://") || client == "" {
|
|
return nil, errors.New("production requires HTTPS PUBLIC_URL, OIDC_ISSUER, and OIDC_CLIENT_ID")
|
|
}
|
|
provider, err := oidc.NewProvider(ctx, issuer)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
a.oauth = &oauth2.Config{ClientID: client, ClientSecret: secret, Endpoint: provider.Endpoint(), RedirectURL: base + "/auth/callback", Scopes: []string{oidc.ScopeOpenID}}
|
|
a.verifier = provider.Verifier(&oidc.Config{ClientID: client})
|
|
return a, nil
|
|
}
|
|
func hash(s string) string { b := sha256.Sum256([]byte(s)); return hex.EncodeToString(b[:]) }
|
|
func (a *Auth) cookieName() string {
|
|
if a.dev {
|
|
return "aeternalis_session"
|
|
}
|
|
return "__Host-aeternalis_session"
|
|
}
|
|
func (a *Auth) account(r *http.Request) (string, error) {
|
|
c, err := r.Cookie(a.cookieName())
|
|
if err != nil || len(c.Value) != 64 {
|
|
return "", errors.New("not authenticated")
|
|
}
|
|
return a.db.Session(r.Context(), hash(c.Value))
|
|
}
|
|
func (a *Auth) session(w http.ResponseWriter, r *http.Request, account string) error {
|
|
token := game.ID() + game.ID()
|
|
if err := a.db.CreateSession(r.Context(), hash(token), account); err != nil {
|
|
return err
|
|
}
|
|
http.SetCookie(w, &http.Cookie{Name: a.cookieName(), Value: token, Path: "/", HttpOnly: true, Secure: !a.dev, SameSite: http.SameSiteLaxMode, MaxAge: 86400})
|
|
return nil
|
|
}
|
|
func (a *Auth) login(w http.ResponseWriter, r *http.Request) {
|
|
if a.dev {
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
return
|
|
}
|
|
state := game.ID() + game.ID()
|
|
v := oauth2.GenerateVerifier()
|
|
a.mu.Lock()
|
|
for key, f := range a.flows {
|
|
if time.Now().After(f.expires) {
|
|
delete(a.flows, key)
|
|
}
|
|
}
|
|
if len(a.flows) >= 4096 {
|
|
a.mu.Unlock()
|
|
fail(w, 503, "login capacity reached")
|
|
return
|
|
}
|
|
a.flows[state] = flow{v, time.Now().Add(10 * time.Minute)}
|
|
a.mu.Unlock()
|
|
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Value: state, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 600})
|
|
http.Redirect(w, r, a.oauth.AuthCodeURL(state, oauth2.S256ChallengeOption(v), oidc.Nonce(state)), http.StatusSeeOther)
|
|
}
|
|
func (a *Auth) callback(w http.ResponseWriter, r *http.Request) {
|
|
if a.dev {
|
|
fail(w, 404, "not enabled")
|
|
return
|
|
}
|
|
state := r.URL.Query().Get("state")
|
|
cookie, err := r.Cookie("__Host-aeternalis_login")
|
|
if err != nil || state == "" || cookie.Value != state {
|
|
fail(w, 400, "invalid login state")
|
|
return
|
|
}
|
|
a.mu.Lock()
|
|
f, ok := a.flows[state]
|
|
delete(a.flows, state)
|
|
a.mu.Unlock()
|
|
if !ok || time.Now().After(f.expires) {
|
|
fail(w, 400, "login expired")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
token, err := a.oauth.Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(f.verifier))
|
|
if err != nil {
|
|
fail(w, 401, "login exchange failed")
|
|
return
|
|
}
|
|
raw, ok := token.Extra("id_token").(string)
|
|
if !ok {
|
|
fail(w, 401, "identity token missing")
|
|
return
|
|
}
|
|
identity, err := a.verifier.Verify(ctx, raw)
|
|
if err != nil || identity.Nonce != state {
|
|
fail(w, 401, "invalid identity token")
|
|
return
|
|
}
|
|
if err = a.session(w, r, hash(identity.Issuer+"\x00"+identity.Subject)); err != nil {
|
|
fail(w, 503, "session unavailable")
|
|
return
|
|
}
|
|
http.SetCookie(w, &http.Cookie{Name: "__Host-aeternalis_login", Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: -1})
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
}
|
|
func validOrigin(r *http.Request, base string) bool {
|
|
origin := r.Header.Get("Origin")
|
|
if origin == "" {
|
|
return false
|
|
}
|
|
expected, err := url.Parse(base)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
actual, err := url.Parse(origin)
|
|
return err == nil && actual.Scheme == expected.Scheme && actual.Host == expected.Host && actual.Path == "" && actual.RawQuery == "" && actual.User == nil
|
|
}
|