Files
supermarket/internal/web/coresignin.go
T
davidandClaude Opus 5.5 cd2dc6145b Sign-ins finish only in the browser that started them
A Core sign-in, and a posting account's or Search Console's OAuth sign-in,
now sets a short-lived cookie whose hash the flow keeps on the server. The
callback refuses one without it (constant-time compare), clears the cookie
either way, and the flow is used up regardless. This stops login CSRF: a
callback URL brought to another browser signs nobody in.

The cookie uses the __Host- prefix over https, so its Path is "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:07:21 -07:00

630 lines
20 KiB
Go

package web
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/audit"
"supermarket/internal/oidc"
"supermarket/internal/users"
)
// Signing in with the Core: its Authelia, over OpenID Connect (the server
// and multi-tenant editions). An admin makes the client's secret under
// Settings → Sign-in, which shows the entry for the Core's idproviders.yml
// (the Core's admin adds it there). People are matched by their verified
// email the first time, then by their subject at the Core. Authelia does
// the two-factor sign-in, if any.
const (
coreSigninKey = "signin:core"
coreSecret = "oidc.client_secret" // in the team's secrets
coreFlowKey = "oidc:flow:" // a sign-in under way, in the team's settings
coreFlowTTL = 10 * time.Minute
)
// coreSignin is a team's setting.
type coreSignin struct {
Enabled bool `json:"enabled"`
ClientID string `json:"client_id"`
Hash string `json:"hash"` // the secret's, for idproviders.yml
RequireCore bool `json:"require_core"` // passwords off, but the owner's
AutoJoin bool `json:"auto_join"` // anyone at the Core's domain joins
AutoModules map[string]users.Access `json:"auto_modules"`
Issuer string `json:"issuer,omitempty"` // empty: https://authelia.<the Core's domain>
// Roles follow the Core's groups: <prefix>-admins, <prefix>-<module>
// (edit), <prefix>-<module>-view.
Groups bool `json:"groups"`
GroupPrefix string `json:"group_prefix,omitempty"` // empty: supermarket
}
func (c coreSignin) prefix() string {
if c.GroupPrefix == "" {
return "supermarket"
}
return c.GroupPrefix
}
// groupAccess is the role and modules the Core's groups give, and whether
// any of them is one of Supermarket's (if none is, access stays as it was
// set here).
func groupAccess(prefix string, groups []string) (users.Role, map[string]users.Access, bool) {
role, mods, any := users.Member, map[string]users.Access{}, false
for _, g := range groups {
rest, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(g)), strings.ToLower(prefix)+"-")
if !ok {
continue
}
if rest == "admins" {
role, any = users.Admin, true
continue
}
id, view := strings.CutSuffix(rest, "-view")
for _, gr := range grants() {
if gr.ID != id {
continue
}
any = true
if !view {
mods[id] = users.Edit
} else if mods[id] != users.Edit {
mods[id] = users.View
}
}
}
if role == users.Admin {
mods = map[string]users.Access{}
}
return role, mods, any
}
func (s *Server) coreSignin() coreSignin {
c := coreSignin{ClientID: "supermarket"}
_, _ = s.DB.GetJSON(coreSigninKey, &c)
if c.ClientID == "" {
c.ClientID = "supermarket"
}
return c
}
// coreIssuer is the team's Authelia: always at authelia.<the Core's domain>.
func (s *Server) coreIssuer() string {
c := s.core()
if c == nil {
return ""
}
if i := s.coreSignin().Issuer; i != "" {
return strings.TrimRight(i, "/")
}
return "https://authelia." + c.Domain
}
func (s *Server) coreCallback() string { return s.PublicURL + "/auth/core/callback" }
// coreReady says whether people can sign in with the team's Core.
func (s *Server) coreReady() bool {
c := s.coreSignin()
return s.signsIn() && c.Enabled && s.coreIssuer() != "" && s.Secrets.Has(coreSecret)
}
// provider is the team's Authelia's discovery document, kept 10 minutes.
func (s *Server) provider(ctx context.Context) (*oidc.Provider, error) {
tc := s.cache()
tc.mu.Lock()
p, at := tc.provider, tc.providerAt
tc.mu.Unlock()
if p != nil && time.Since(at) < 10*time.Minute && strings.TrimRight(p.Issuer, "/") == s.coreIssuer() {
return p, nil
}
p, err := oidc.Discover(ctx, s.coreIssuer())
if err != nil {
return nil, err
}
tc.mu.Lock()
tc.provider, tc.providerAt = p, time.Now()
tc.mu.Unlock()
return p, nil
}
func (s *Server) oidcClient() oidc.Client {
return oidc.Client{ID: s.coreSignin().ClientID, Secret: s.Secrets.Get(coreSecret), RedirectURI: s.coreCallback()}
}
// clientBlock is the entry for the Core's idproviders.yml.
func (s *Server) clientBlock() string {
c := s.coreSignin()
if c.Hash == "" {
return ""
}
return fmt.Sprintf(` ### Supermarket
- client_id: '%s'
client_name: 'Supermarket'
client_secret: '%s'
consent_mode: 'implicit'
public: false
authorization_policy: 'one_factor'
require_pkce: true
pkce_challenge_method: 'S256'
redirect_uris:
- '%s'
scopes:
- 'openid'
- 'profile'
- 'email'
- 'groups'
response_types:
- 'code'
grant_types:
- 'authorization_code'
userinfo_signed_response_alg: 'none'
token_endpoint_auth_method: 'client_secret_post'
`, c.ClientID, c.Hash, s.coreCallback())
}
// Settings → Sign-in.
type signinSettings struct {
Core bool
Domain string
Issuer string
Callback string
C coreSignin
Block string
Grants []grant
Problem string
Tested string
Prefix string // the groups'
}
func (s *Server) signinSettingsPage(w http.ResponseWriter, r *http.Request) {
s.renderSigninSettings(w, r, "", "")
}
func (s *Server) renderSigninSettings(w http.ResponseWriter, r *http.Request, problem, tested string) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
d := signinSettings{Core: s.core() != nil, Issuer: s.coreIssuer(), Callback: s.coreCallback(), C: s.coreSignin(),
Block: s.clientBlock(), Grants: grants(), Problem: problem, Tested: tested}
d.Prefix = d.C.prefix()
if c := s.core(); c != nil {
d.Domain = c.Domain
}
s.render(w, r, "signin-settings", page{Title: "Sign-in", Nav: "settings/signin", Data: d})
}
// signinSettingsAction: secret, test, save.
func (s *Server) signinSettingsAction(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
c := s.coreSignin()
switch r.PathValue("action") {
case "secret":
if id := strings.TrimSpace(r.PostFormValue("client_id")); id != "" {
c.ClientID = id
}
secret, err := oidc.NewSecret()
if err == nil {
c.Hash, err = oidc.HashSecret(secret)
}
if err == nil {
err = s.Secrets.Set(map[string]string{coreSecret: secret})
}
if err == nil {
err = s.DB.PutJSON(coreSigninKey, c)
}
if err != nil {
s.serverError(w, err)
return
}
s.recordConnection(r, "core-signin", true)
redirect(w, r, "/settings/signin#block", "secret-made")
case "test":
if s.coreIssuer() == "" {
s.renderSigninSettings(w, r, "Enter the Core's domain under Core & Hermes first.", "")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
s.cache().mu.Lock()
s.cache().provider = nil
s.cache().mu.Unlock()
p, err := s.provider(ctx)
if err != nil {
s.noteCheckErr("core-signin", err.Error())
s.renderSigninSettings(w, r, sentence(err.Error())+".", "")
return
}
s.noteCheckErr("core-signin", "")
note := "Authelia answers at " + p.Issuer + "."
if p.EndSession != "" {
note += " Signing out of Supermarket will sign out of the Core too."
}
s.renderSigninSettings(w, r, "", note)
case "save":
c.Enabled = r.PostFormValue("enabled") == "on"
c.RequireCore = r.PostFormValue("require_core") == "on"
c.AutoJoin = r.PostFormValue("auto_join") == "on"
c.Groups = r.PostFormValue("groups") == "on"
c.GroupPrefix = strings.ToLower(strings.TrimSpace(r.PostFormValue("group_prefix")))
if c.GroupPrefix == "supermarket" {
c.GroupPrefix = ""
}
if strings.ContainsAny(c.GroupPrefix, " ,") {
s.renderSigninSettings(w, r, "The groups' prefix is one word, such as supermarket.", "")
return
}
if i := strings.TrimSpace(r.PostFormValue("issuer")); i == "" || strings.HasPrefix(i, "https://") {
c.Issuer = strings.TrimRight(i, "/")
} else {
s.renderSigninSettings(w, r, "The issuer's address starts with https://.", "")
return
}
c.AutoModules = map[string]users.Access{}
for _, g := range grants() {
switch users.Access(r.PostFormValue("module:" + g.ID)) {
case users.View:
c.AutoModules[g.ID] = users.View
case users.Edit:
c.AutoModules[g.ID] = users.Edit
}
}
if c.Enabled && (!s.Secrets.Has(coreSecret) || s.coreIssuer() == "") {
s.renderSigninSettings(w, r, "Make the client's secret, and add the entry to the Core, first.", "")
return
}
if c.AutoJoin && len(c.AutoModules) == 0 {
s.renderSigninSettings(w, r, "Give the people who join this way at least one module.", "")
return
}
if err := s.DB.PutJSON(coreSigninKey, c); err != nil {
s.serverError(w, err)
return
}
s.audit(r, "signin-settings", "", fmt.Sprintf("with the Core %v, the Core only %v, anyone at the Core's domain joins %v, roles follow the Core's groups %v", c.Enabled, c.RequireCore, c.AutoJoin, c.Groups))
redirect(w, r, "/settings/signin", "saved")
default:
http.NotFound(w, r)
}
}
// Signing in.
// coreTeam is the Server whose Core a sign-in uses: the team's on the
// server edition; on the multi-tenant edition, the team that proved the
// domain typed in.
func (s *Server) coreTeam(r *http.Request) (*Server, error) {
if !s.multi() {
return s, nil
}
dom, err := registeredDomain(r.PostFormValue("domain"))
if err != nil {
return nil, errors.New("give your company's website, such as example.com")
}
id, err := users.DomainHolder(s.platform(), dom)
if err != nil {
return nil, err
}
if id == 0 {
return nil, errors.New("no team here signs in with a Core for " + dom)
}
return s.forTeam(id)
}
// signinCore starts a sign-in with the Core.
func (s *Server) signinCore(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
next := safeNext(r.PostFormValue("next"))
ts, err := s.coreTeam(r)
if err == nil && !ts.coreReady() {
err = errors.New("signing in with the Core isn't set up for this team")
}
if err != nil {
s.signinFail(w, r, signinForm{Next: next, Problem: sentence(err.Error()) + "."}, http.StatusUnprocessableEntity)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
p, err := ts.provider(ctx)
if err != nil {
s.signinFail(w, r, signinForm{Next: next, Problem: "The Core's sign-in can't be reached just now: " + err.Error() + ". Sign in with your password, or try again."}, http.StatusBadGateway)
return
}
prefix := ""
if s.multi() {
prefix = strconv.FormatInt(ts.team(), 10) + "."
}
addr, f, err := oidc.Start(p, ts.oidcClient(), prefix)
if err != nil {
s.serverError(w, err)
return
}
f.Next = next
if f.Browser, err = s.bindFlow(w, coreFlowCookie, coreFlowTTL); err != nil {
s.serverError(w, err)
return
}
if err := ts.DB.PutJSON(coreFlowKey+f.State, f); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, addr, http.StatusSeeOther)
}
// takeCoreFlow finds and removes a sign-in under way: once.
func (s *Server) takeCoreFlow(state string) *oidc.Flow {
var f oidc.Flow
if ok, err := s.DB.GetJSON(coreFlowKey+state, &f); !ok || err != nil {
return nil
}
res, err := s.DB.Exec(`DELETE FROM settings WHERE key = ?`, coreFlowKey+state)
if err != nil {
return nil
}
if n, _ := res.RowsAffected(); n != 1 || time.Since(f.Started) > coreFlowTTL {
return nil
}
return &f
}
func flowBrowser(f *oidc.Flow) string {
if f == nil {
return ""
}
return f.Browser
}
// coreCallbackPage finishes a sign-in with the Core.
func (s *Server) coreCallbackPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
http.NotFound(w, r)
return
}
q := r.URL.Query()
state := q.Get("state")
ts := s
if s.multi() {
team, _, ok := strings.Cut(state, ".")
id, err := strconv.ParseInt(team, 10, 64)
if !ok || err != nil {
s.signinFail(w, r, signinForm{Problem: "That sign-in took too long or was already used. Try again."}, http.StatusBadRequest)
return
}
if ts, err = s.forTeam(id); err != nil {
s.signinFail(w, r, signinForm{Problem: "That sign-in took too long or was already used. Try again."}, http.StatusBadRequest)
return
}
}
fail := func(msg string, code int) {
ts.Log.Info("signin: with the Core, failed", "reason", msg, "ip", clientIP(r))
ts.record(audit.Entry{Action: "signin-failed", Detail: "with the Core: " + msg, IP: clientIP(r)})
s.signinFail(w, r, signinForm{Problem: msg}, code)
}
f := ts.takeCoreFlow(state)
// Taken either way, and the cookie cleared: a callback opened in
// another browser can't sign it in, nor be tried again.
if fromHere := s.flowFromThisBrowser(w, r, coreFlowCookie, flowBrowser(f)); f == nil || !fromHere {
fail("That sign-in took too long or was already used. Try again.", http.StatusBadRequest)
return
}
if e := q.Get("error"); e != "" {
fail("The Core said: "+e+" "+q.Get("error_description"), http.StatusUnauthorized)
return
}
if !ts.coreReady() {
fail("Signing in with the Core isn't set up for this team.", http.StatusForbidden)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
p, err := ts.provider(ctx)
if err == nil {
var id *oidc.Identity
if id, err = oidc.Finish(ctx, p, ts.oidcClient(), f, q.Get("code"), time.Now()); err == nil {
ts.finishCore(w, r, p, id, f.Next)
return
}
}
fail(sentence(err.Error())+".", http.StatusUnauthorized)
}
// finishCore signs in the person the Core vouched for: known by their
// subject, or the first time by their verified email; or, if the team
// lets anyone at the Core's domain join, as a new member.
func (s *Server) finishCore(w http.ResponseWriter, r *http.Request, p *oidc.Provider, id *oidc.Identity, next string) {
now := time.Now()
subject := strings.TrimRight(p.Issuer, "/") + "|" + id.Subject
refuse := func(msg string) {
s.record(audit.Entry{Action: "signin-failed", Target: id.Email, Detail: "with the Core: " + msg, IP: clientIP(r)})
s.signinFail(w, r, signinForm{Problem: msg}, http.StatusForbidden)
}
u, err := users.ByOIDCSubject(s.platform(), subject)
if errors.Is(err, users.ErrNotFound) {
if !id.Verified || id.Email == "" {
refuse("The Core didn't vouch for an email address, so Supermarket can't tell who you are here.")
return
}
u, err = users.ByEmail(s.platform(), id.Email)
if err == nil && u.OIDCSubject != "" && u.OIDCSubject != subject {
refuse("That address is already linked to another Core account.")
return
}
}
if err != nil && !errors.Is(err, users.ErrNotFound) {
s.serverError(w, err)
return
}
cfg := s.coreSignin()
if u != nil && u.Kind != users.Person {
refuse("Agents can't sign in.")
return
}
member := false
var was users.Membership
if u != nil {
m, merr := users.MembershipOf(s.platform(), s.team(), u.ID)
member, was = merr == nil, m
}
gRole, gMods, inGroups := groupAccess(cfg.prefix(), id.Groups)
inGroups = inGroups && cfg.Groups
if !member && inGroups {
// In one of Supermarket's groups: invited by the Core.
if !id.Verified || id.Email == "" {
refuse("The Core didn't vouch for an email address, so Supermarket can't tell who you are here.")
return
}
if problem, _, _ := s.seatRoom(); problem != "" {
refuse("The team has no seat free for you. Ask its owner.")
return
}
if u == nil {
u = &users.User{Email: id.Email, Name: id.Name, Status: users.Active}
if err := users.Create(s.platform(), u, now); err != nil {
s.serverError(w, err)
return
}
}
if err := users.Join(s.platform(), s.team(), u.ID, gRole, gMods, now); err != nil {
s.serverError(w, err)
return
}
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "joined", Target: u.Email,
Detail: "with the Core, from its groups: " + accessText(users.Membership{Role: gRole, Modules: gMods}), IP: clientIP(r)})
member, was = true, users.Membership{Role: gRole, Modules: gMods}
} else if member && inGroups && was.Role != users.Owner && !sameAccess(was, gRole, gMods) {
// The Core's groups changed: so does their access.
if err := users.Join(s.platform(), s.team(), u.ID, gRole, gMods, now); err != nil {
s.serverError(w, err)
return
}
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "access-changed", Target: u.Email,
Detail: accessText(users.Membership{Role: gRole, Modules: gMods}) + ", from the Core's groups", IP: clientIP(r)})
}
if !member {
// Anyone at the Core's domain may join, if the team says so.
core := s.core()
_, at, _ := strings.Cut(id.Email, "@")
if !cfg.AutoJoin || core == nil || !id.Verified || !strings.EqualFold(at, core.Domain) {
refuse("You haven't been invited to this team. Ask one of its admins.")
return
}
if u == nil {
u = &users.User{Email: id.Email, Name: id.Name, Status: users.Active}
if err := users.Create(s.platform(), u, now); err != nil {
s.serverError(w, err)
return
}
}
if err := users.Join(s.platform(), s.team(), u.ID, users.Member, cfg.AutoModules, now); err != nil {
s.serverError(w, err)
return
}
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "joined", Target: u.Email, Detail: "with the Core, as anyone at " + core.Domain + " may", IP: clientIP(r)})
}
switch u.Status {
case users.Disabled:
refuse("This account is turned off. Ask an admin if you need it again.")
return
case users.Invited:
// Signing in with the Core accepts the invitation.
if err := users.SetStatus(s.platform(), u.ID, users.Active); err != nil {
s.serverError(w, err)
return
}
_ = users.DropLinks(s.platform(), users.InviteLink, u.ID)
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "joined", Target: u.Email, Detail: "with the Core", IP: clientIP(r)})
}
if u.OIDCSubject != subject {
if err := users.SetOIDCSubject(s.platform(), u.ID, subject); err != nil {
s.serverError(w, err)
return
}
}
if u.Name == "" && id.Name != "" {
u.Name = id.Name
_ = users.SaveProfile(s.platform(), u)
}
if err := users.Unlock(s.platform(), u.ID); err != nil {
s.serverError(w, err)
return
}
if err := s.startSessionIn(w, r, u, s.team(), "core"); err != nil {
s.serverError(w, err)
return
}
s.Log.Info("signin: with the Core", "user", u.Email, "ip", clientIP(r))
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin", Detail: "with the Core", IP: clientIP(r)})
http.Redirect(w, r, next, http.StatusSeeOther)
}
// passwordsOff says why a user may not sign in with a password: their
// team requires the Core, and they aren't its owner (whose password stays,
// a way in if the Core is down). "" if they may.
func (s *Server) passwordsOff(u *users.User) string {
teams := []int64{s.team()}
if s.multi() {
list, _ := users.TeamsOf(s.platform(), u.ID)
teams = teams[:0]
for _, t := range list {
teams = append(teams, t.ID)
}
}
for _, id := range teams {
ts, err := s.forTeam(id)
if err != nil {
continue
}
m, err := users.MembershipOf(s.platform(), id, u.ID)
if err != nil {
continue
}
if !ts.coreReady() || !ts.coreSignin().RequireCore || m.Role == users.Owner {
return "" // one team that takes their password is enough
}
}
if len(teams) == 0 {
return ""
}
return "This team signs in with the Core: use “Sign in with your Core” below."
}
// coreSignOut is where to send someone signed in with the Core when they
// sign out of Supermarket: the Core's sign-out, if it has one.
func (s *Server) coreSignOut(ctx context.Context) string {
p, err := s.provider(ctx)
if err != nil {
return ""
}
return oidc.SignOutURL(p, "", s.PublicURL+"/signin?msg=signed-out")
}
// sameAccess says whether a membership already has a role and modules.
func sameAccess(m users.Membership, role users.Role, mods map[string]users.Access) bool {
if m.Role != role {
return false
}
if role != users.Member {
return true
}
if len(m.Modules) != len(mods) {
return false
}
for k, v := range mods {
if m.Modules[k] != v {
return false
}
}
return true
}