Phase 12: signing in with the Core's Authelia

Admins make the client's secret under Settings → Sign-in, which shows the
entry for the Core's idproviders.yml (the secret's PBKDF2-SHA512 hash, the
redirect address, PKCE). People sign in with their Core account: invited
ones are matched by verified email, then by subject; optionally anyone at
the Core's domain joins. Passwords can be turned off but for the owner's,
and signing out ends the Core's session where it can. On multi-tenant, the
team is found by its proved domain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 13:00:36 -07:00
co-authored by Claude Opus 5.5
parent 637ef1cc25
commit 962dbe3286
19 changed files with 1458 additions and 15 deletions
+10
View File
@@ -291,6 +291,16 @@ CREATE UNIQUE INDEX teams_proved_domain ON teams(domain) WHERE verified_at <> ''
SQLite: `
ALTER TABLE sessions ADD COLUMN view_until TEXT NOT NULL DEFAULT ''; -- a platform admin viewing a team: until then
ALTER TABLE sessions ADD COLUMN view_reason TEXT NOT NULL DEFAULT '';
`,
},
// 43
{
Note: "signing in with the Core (OpenID Connect): who each person is there, and how a session signed in",
Platform: true,
SQLite: `
ALTER TABLE users ADD COLUMN oidc_subject TEXT NOT NULL DEFAULT ''; -- <issuer>|<subject>: who they are at the Core
CREATE UNIQUE INDEX users_oidc_subject ON users(oidc_subject) WHERE oidc_subject <> '';
ALTER TABLE sessions ADD COLUMN via TEXT NOT NULL DEFAULT 'password'; -- password or core
`,
},
}
+365
View File
@@ -0,0 +1,365 @@
// Package oidc signs people in with an OpenID Connect provider: the
// Federated Core's Authelia. The authorization code flow, with PKCE (S256)
// and a nonce; the client authenticates to the token endpoint with its
// secret in the form (client_secret_post).
//
// The ID token comes straight from the provider's token endpoint over TLS,
// so (as OpenID Connect Core 1.0, 3.1.3.7, allows) its issuer is trusted
// from TLS rather than by checking its signature; its claims are checked:
// the issuer, the audience, the expiry and the nonce.
package oidc
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/crypto/pbkdf2"
)
// Provider is what an issuer's discovery document says.
type Provider struct {
Issuer string `json:"issuer"`
Authorization string `json:"authorization_endpoint"`
Token string `json:"token_endpoint"`
UserInfo string `json:"userinfo_endpoint"`
EndSession string `json:"end_session_endpoint"` // empty if the provider has no sign-out
Scopes []string `json:"scopes_supported"`
PKCEMethods []string `json:"code_challenge_methods_supported"`
}
// Client is how Supermarket is registered with the provider.
type Client struct {
ID, Secret string
RedirectURI string
}
// Scopes are what Supermarket asks for.
const Scopes = "openid profile email groups"
// HTTP is the client used to reach providers; tests replace it.
var HTTP = &http.Client{Timeout: 20 * time.Second}
// Discover reads an issuer's discovery document, and checks it names the
// same issuer and the endpoints the code flow needs.
func Discover(ctx context.Context, issuer string) (*Provider, error) {
issuer = strings.TrimRight(issuer, "/")
req, err := http.NewRequestWithContext(ctx, http.MethodGet, issuer+"/.well-known/openid-configuration", nil)
if err != nil {
return nil, err
}
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching %s: %w", issuer, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s has no OpenID Connect discovery document (%s)", issuer, resp.Status)
}
var p Provider
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&p); err != nil {
return nil, fmt.Errorf("%s's discovery document can't be read: %w", issuer, err)
}
if strings.TrimRight(p.Issuer, "/") != issuer {
return nil, fmt.Errorf("the discovery document names another issuer (%s)", p.Issuer)
}
if p.Authorization == "" || p.Token == "" {
return nil, errors.New("the discovery document lacks the authorization or token endpoint")
}
return &p, nil
}
// Flow is a sign-in under way: kept until the provider sends the browser
// back.
type Flow struct {
State string `json:"state"`
Nonce string `json:"nonce"`
Verifier string `json:"verifier"`
Started time.Time `json:"started"`
Next string `json:"next,omitempty"`
}
func random() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Start begins a sign-in: the address to send the browser to, and the
// flow to keep. statePrefix goes before the random state (the team, on
// the multi-tenant edition).
func Start(p *Provider, c Client, statePrefix string) (string, *Flow, error) {
f := &Flow{Started: time.Now()}
var err error
if f.State, err = random(); err != nil {
return "", nil, err
}
f.State = statePrefix + f.State
if f.Nonce, err = random(); err != nil {
return "", nil, err
}
if f.Verifier, err = random(); err != nil {
return "", nil, err
}
sum := sha256.Sum256([]byte(f.Verifier))
q := url.Values{
"response_type": {"code"},
"client_id": {c.ID},
"redirect_uri": {c.RedirectURI},
"scope": {Scopes},
"state": {f.State},
"nonce": {f.Nonce},
"code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
"code_challenge_method": {"S256"},
}
sep := "?"
if strings.Contains(p.Authorization, "?") {
sep = "&"
}
return p.Authorization + sep + q.Encode(), f, nil
}
// Identity is who signed in.
type Identity struct {
Subject string // the provider's ID for them: stable, unlike the email
Email string
Verified bool // the provider vouches for the email
Name string
Groups []string
IDToken string // for signing out of the provider
}
// Finish trades the code for tokens, checks the ID token's claims, and
// reads who it is (the ID token, completed by the userinfo endpoint).
func Finish(ctx context.Context, p *Provider, c Client, f *Flow, code string, now time.Time) (*Identity, error) {
form := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {c.RedirectURI},
"client_id": {c.ID},
"client_secret": {c.Secret},
"code_verifier": {f.Verifier},
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Token, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
resp, err := HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("reaching the token endpoint: %w", err)
}
defer resp.Body.Close()
var tok struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
Error string `json:"error"`
Description string `json:"error_description"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&tok); err != nil {
return nil, fmt.Errorf("the token endpoint's answer can't be read (%s)", resp.Status)
}
if resp.StatusCode != http.StatusOK || tok.Error != "" {
return nil, fmt.Errorf("the provider refused the code: %s %s", tok.Error, tok.Description)
}
claims, err := parseIDToken(tok.IDToken)
if err != nil {
return nil, err
}
if err := claims.check(p.Issuer, c.ID, f.Nonce, now); err != nil {
return nil, err
}
id := &Identity{Subject: claims.Subject, Email: claims.Email, Verified: claims.EmailVerified, Name: claims.Name, Groups: claims.Groups, IDToken: tok.IDToken}
if p.UserInfo != "" && tok.AccessToken != "" {
if ui, err := userInfo(ctx, p.UserInfo, tok.AccessToken); err == nil && ui.Subject == claims.Subject {
if ui.Email != "" {
id.Email, id.Verified = ui.Email, ui.EmailVerified
}
if ui.Name != "" {
id.Name = ui.Name
}
if len(ui.Groups) > 0 {
id.Groups = ui.Groups
}
}
}
if id.Subject == "" {
return nil, errors.New("the provider sent no subject")
}
id.Email = strings.ToLower(strings.TrimSpace(id.Email))
return id, nil
}
// claims are the ID token's (and userinfo's).
type claims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience audience `json:"aud"`
Expiry int64 `json:"exp"`
IssuedAt int64 `json:"iat"`
Nonce string `json:"nonce"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Groups []string `json:"groups"`
}
// audience is a string or a list of them.
type audience []string
func (a *audience) UnmarshalJSON(b []byte) error {
var one string
if json.Unmarshal(b, &one) == nil {
*a = []string{one}
return nil
}
var many []string
if err := json.Unmarshal(b, &many); err != nil {
return err
}
*a = many
return nil
}
func parseIDToken(tok string) (*claims, error) {
parts := strings.Split(tok, ".")
if len(parts) != 3 {
return nil, errors.New("the provider sent no ID token")
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return nil, errors.New("the ID token can't be read")
}
var c claims
if err := json.Unmarshal(raw, &c); err != nil {
return nil, errors.New("the ID token can't be read")
}
return &c, nil
}
// leeway allows for clocks that differ a little.
const leeway = 2 * time.Minute
func (c *claims) check(issuer, clientID, nonce string, now time.Time) error {
switch {
case strings.TrimRight(c.Issuer, "/") != strings.TrimRight(issuer, "/"):
return errors.New("the ID token is from another issuer")
case !c.has(clientID):
return errors.New("the ID token is for another client")
case c.Expiry == 0 || now.After(time.Unix(c.Expiry, 0).Add(leeway)):
return errors.New("the ID token has expired: check the server's clock")
case c.IssuedAt != 0 && time.Unix(c.IssuedAt, 0).After(now.Add(leeway)):
return errors.New("the ID token is from the future: check the server's clock")
case nonce == "" || c.Nonce != nonce:
return errors.New("the ID token doesn't match this sign-in")
}
return nil
}
func (c *claims) has(clientID string) bool {
for _, a := range c.Audience {
if a == clientID {
return true
}
}
return false
}
func userInfo(ctx context.Context, endpoint, access string) (*claims, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+access)
resp, err := HTTP.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("userinfo: %s", resp.Status)
}
var c claims
return &c, json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&c)
}
// SignOutURL is where to send the browser to sign out of the provider too,
// or "" if it has no end-session endpoint.
func SignOutURL(p *Provider, idToken, back string) string {
if p == nil || p.EndSession == "" {
return ""
}
q := url.Values{"post_logout_redirect_uri": {back}}
if idToken != "" {
q.Set("id_token_hint", idToken)
}
sep := "?"
if strings.Contains(p.EndSession, "?") {
sep = "&"
}
return p.EndSession + sep + q.Encode()
}
// Secrets, as Authelia's configuration takes them.
// NewSecret is a client secret: 48 random characters.
func NewSecret() (string, error) {
b := make([]byte, 36)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// HashRounds is how many PBKDF2 rounds the Core's own clients use.
const HashRounds = 310000
// ab64 is passlib's base64: the standard alphabet with . for +, no padding.
func ab64(b []byte) string {
return strings.ReplaceAll(base64.RawStdEncoding.EncodeToString(b), "+", ".")
}
// HashSecret is a secret as Authelia's client_secret takes it:
// $pbkdf2-sha512$310000$<salt>$<key>, like the Core's other clients.
func HashSecret(secret string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
return hashWith(secret, salt, HashRounds), nil
}
func hashWith(secret string, salt []byte, rounds int) string {
key := pbkdf2.Key([]byte(secret), salt, rounds, sha512.Size, sha512.New)
return fmt.Sprintf("$pbkdf2-sha512$%d$%s$%s", rounds, ab64(salt), ab64(key))
}
// CheckHash says whether a secret matches a hash from HashSecret.
func CheckHash(secret, hash string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 5 || parts[1] != "pbkdf2-sha512" {
return false
}
var rounds int
if _, err := fmt.Sscanf(parts[2], "%d", &rounds); err != nil || rounds < 1 || rounds > 10_000_000 {
return false
}
salt, err := base64.RawStdEncoding.DecodeString(strings.ReplaceAll(parts[3], ".", "+"))
if err != nil {
return false
}
return hashWith(secret, salt, rounds) == hash
}
+131
View File
@@ -0,0 +1,131 @@
package oidc
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
)
func TestHashSecret(t *testing.T) {
// The same as Python's hashlib.pbkdf2_hmac, in passlib's base64.
if got := hashWith("correct horse", []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, 1000); got != "$pbkdf2-sha512$1000$AAECAwQFBgcICQoLDA0ODw$Xpx07WjVx4vCIvrmBRj8uOoVVtGqJqtUv2J5bhizSQs7osCteF7W4A61dZDqSIqQjO.dxO6p5FT/Uy7QRBXSXA" {
t.Errorf("hash %s", got)
}
h, err := HashSecret("s3cret")
if err != nil {
t.Fatal(err)
}
// Shaped like the Core's own clients' secrets.
if !regexp.MustCompile(`^\$pbkdf2-sha512\$310000\$[A-Za-z0-9./]{22}\$[A-Za-z0-9./]{86}$`).MatchString(h) {
t.Errorf("shape %s", h)
}
if !CheckHash("s3cret", h) || CheckHash("s3creT", h) || CheckHash("s3cret", "$pbkdf2-sha256$1$a$b") {
t.Error("check")
}
if s, _ := NewSecret(); len(s) != 48 {
t.Errorf("secret %q", s)
}
}
// fakeAuthelia is a provider for tests.
func fakeAuthelia(t *testing.T, claims map[string]any) (*httptest.Server, *string) {
t.Helper()
var challenge string
var srv *httptest.Server
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/.well-known/openid-configuration":
json.NewEncoder(w).Encode(map[string]any{"issuer": srv.URL, "authorization_endpoint": srv.URL + "/api/oidc/authorization",
"token_endpoint": srv.URL + "/api/oidc/token", "userinfo_endpoint": srv.URL + "/api/oidc/userinfo"})
case "/api/oidc/token":
r.ParseForm()
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
if r.PostForm.Get("client_secret") != "s3cret" || r.PostForm.Get("code") != "c0de" ||
base64.RawURLEncoding.EncodeToString(sum[:]) != challenge {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
return
}
c := map[string]any{"iss": srv.URL, "aud": []string{"supermarket"}, "exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
for k, v := range claims {
c[k] = v
}
payload, _ := json.Marshal(c)
json.NewEncoder(w).Encode(map[string]string{"access_token": "at", "id_token": "e30." + base64.RawURLEncoding.EncodeToString(payload) + ".sig"})
case "/api/oidc/userinfo":
if r.Header.Get("Authorization") != "Bearer at" {
w.WriteHeader(http.StatusUnauthorized)
return
}
json.NewEncoder(w).Encode(map[string]any{"sub": claims["sub"], "email": "Pat@Example.com", "email_verified": true, "groups": []string{"admins"}})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv, &challenge
}
func TestCodeFlow(t *testing.T) {
ctx := context.Background()
claims := map[string]any{"sub": "abc-123", "name": "Pat"}
srv, challenge := fakeAuthelia(t, claims)
if _, err := Discover(ctx, srv.URL+"/other"); err == nil {
t.Error("discovered a wrong issuer")
}
p, err := Discover(ctx, srv.URL+"/")
if err != nil {
t.Fatal(err)
}
c := Client{ID: "supermarket", Secret: "s3cret", RedirectURI: "https://sm.example.com/auth/core/callback"}
addr, f, err := Start(p, c, "7.")
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(addr)
q := u.Query()
if q.Get("code_challenge_method") != "S256" || q.Get("scope") != Scopes || q.Get("nonce") != f.Nonce || !strings.HasPrefix(f.State, "7.") || q.Get("state") != f.State {
t.Errorf("authorization address %s", addr)
}
*challenge = q.Get("code_challenge")
claims["nonce"] = f.Nonce
id, err := Finish(ctx, p, c, f, "c0de", time.Now())
if err != nil {
t.Fatal(err)
}
if id.Subject != "abc-123" || id.Email != "pat@example.com" || !id.Verified || id.Name != "Pat" || len(id.Groups) != 1 {
t.Errorf("identity %+v", id)
}
// What must fail.
if _, err := Finish(ctx, p, Client{ID: "supermarket", Secret: "wrong", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("a wrong secret")
}
bad := *f
bad.Verifier = "other"
if _, err := Finish(ctx, p, c, &bad, "c0de", time.Now()); err == nil {
t.Error("a wrong verifier")
}
claims["nonce"] = "replayed"
if _, err := Finish(ctx, p, c, f, "c0de", time.Now()); err == nil || !strings.Contains(err.Error(), "match") {
t.Errorf("a wrong nonce: %v", err)
}
claims["nonce"] = f.Nonce
if _, err := Finish(ctx, p, Client{ID: "other", Secret: "s3cret", RedirectURI: c.RedirectURI}, f, "c0de", time.Now()); err == nil {
t.Error("another client's token")
}
if _, err := Finish(ctx, p, c, f, "c0de", time.Now().Add(10*time.Minute)); err == nil || !strings.Contains(err.Error(), "expired") {
t.Errorf("expired: %v", err)
}
if SignOutURL(p, "x", "https://sm.example.com/signin") != "" {
t.Error("sign-out without an endpoint")
}
}
+9 -2
View File
@@ -36,6 +36,7 @@ type Session struct {
// A platform admin viewing a team: until when, and why.
ViewUntil time.Time
ViewReason string
Via string // password or core
}
// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired,
@@ -88,12 +89,12 @@ func expiry(created, seen time.Time) time.Time {
return max
}
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id, view_until, view_reason`
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id, view_until, view_reason, via`
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
var s Session
var created, seen, expires, until string
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team, &until, &s.ViewReason); err != nil {
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team, &until, &s.ViewReason, &s.Via); err != nil {
return nil, err
}
s.Created, s.Seen, s.Expires, s.ViewUntil = parseTS(created), parseTS(seen), parseTS(expires), parseTS(until)
@@ -185,3 +186,9 @@ func PruneSessions(d *db.DB, now time.Time) (int64, error) {
}
return res.RowsAffected()
}
// SetVia records how a session signed in.
func SetVia(d *db.DB, id, via string) error {
_, err := d.Exec(`UPDATE sessions SET via = ? WHERE id = ?`, via, id)
return err
}
+17 -2
View File
@@ -88,6 +88,7 @@ type User struct {
LockedAt time.Time // zero unless locked after too many failures
TwoFactor bool // signs in with an authenticator app's code too
RecoveryLeft int // unused recovery codes
OIDCSubject string // <issuer>|<subject> at the Core, once they've signed in with it
passwordHash string
totpStep int64
@@ -138,14 +139,14 @@ func NormalEmail(s string) (string, error) {
return strings.ToLower(s), nil
}
const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes`
const userCols = `id, email, name, kind, status, password_hash, title, description, time_zone, photo, emails, created_at, signed_in_at, failed_signins, locked_at, two_factor, totp_step, recovery_codes, oidc_subject`
func scanUser(row interface{ Scan(...any) error }) (*User, error) {
var u User
var kind, status, emails, created, signedIn, locked, codes string
var twoFactor int
err := row.Scan(&u.ID, &u.Email, &u.Name, &kind, &status, &u.passwordHash, &u.Title, &u.Description, &u.TimeZone, &u.Photo, &emails, &created, &signedIn,
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes)
&u.FailedSignIns, &locked, &twoFactor, &u.totpStep, &codes, &u.OIDCSubject)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
@@ -454,3 +455,17 @@ type rowWith struct {
}
func (r rowWith) Scan(dest ...any) error { return r.row.Scan(append(dest, r.more...)...) }
// ByOIDCSubject finds the user the Core knows by a subject.
func ByOIDCSubject(d *db.DB, subject string) (*User, error) {
if subject == "" {
return nil, ErrNotFound
}
return scanUser(d.QueryRow(`SELECT `+userCols+` FROM users WHERE oidc_subject = ?`, subject))
}
// SetOIDCSubject remembers who a user is at the Core.
func SetOIDCSubject(d *db.DB, id int64, subject string) error {
_, err := d.Exec(`UPDATE users SET oidc_subject = ? WHERE id = ?`, subject, id)
return err
}
+2
View File
@@ -44,6 +44,8 @@ var routeAreas = map[string]string{
// Signing in to a posting account: admins for the company's, anyone
// with Content for their own (oauthStart checks which).
"/auth": areaSignedIn,
// The Core's sign-in comes back here, before anyone is signed in.
"/auth/core": areaPublic,
"/content": "content", "/posts": "content", "/inbox": "content", "/drafts": "content", "/reddit": "content",
"/prospects": "prospects", "/signals": "prospects", "/lead-sources": "prospects", "/funnel": "prospects",
+1 -1
View File
@@ -180,7 +180,7 @@ var actionLabels = map[string]string{
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
"team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
"signin-settings": "changed how people sign in:", "team-created": "set up the team", "viewed-as": "looked at the team's data:", "team-suspended": "suspended the team", "team-restored": "restored the team",
"domain-released": "released the domain", "exported": "exported", "downloaded-export": "downloaded the export", "team-deleting": "asked to delete the team", "team-undeleted": "undid the team's deletion", "invitations-resent": "sent the invitations again:", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
+11 -1
View File
@@ -207,10 +207,20 @@ func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *users.U
return errors.New("you aren't in any team that's open")
}
}
token, _, err := users.StartSessionIn(s.platform(), u.ID, team, clientIP(r), r.UserAgent(), time.Now())
return s.startSessionIn(w, r, u, team, "password")
}
// startSessionIn signs a user in to a team, recording how (password, core).
func (s *Server) startSessionIn(w http.ResponseWriter, r *http.Request, u *users.User, team int64, via string) error {
token, sess, err := users.StartSessionIn(s.platform(), u.ID, team, clientIP(r), r.UserAgent(), time.Now())
if err != nil {
return err
}
if via != "password" {
if err := users.SetVia(s.platform(), sess.ID, via); err != nil {
return err
}
}
if err := users.SignedIn(s.platform(), u.ID, time.Now()); err != nil {
return err
}
+1
View File
@@ -38,6 +38,7 @@ var services = []service{
{"hunter", "Hunter.io", "Prospects: finding and checking emails", "/settings/sources", []string{secrets.HunterAPIKey}},
{"mail", "Outreach mailbox", "Sending outreach, reading replies", "/settings/email", []string{secrets.MailPassword}},
{"listmonk", "Listmonk", "Mailing lists", "/settings/email", []string{secrets.ListmonkToken}},
{"core-signin", "Sign-in with the Core", "People signing in with the Core's Authelia (OpenID Connect)", "/settings/signin", []string{"oidc.client_secret"}},
}
// serviceName is a service as people say it.
+507
View File
@@ -0,0 +1,507 @@
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>
}
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
}
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}
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"
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", c.Enabled, c.RequireCore, c.AutoJoin))
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 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
}
// 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)
if f == nil {
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
if u != nil {
_, merr := users.MembershipOf(s.platform(), s.team(), u.ID)
member = merr == nil
}
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")
}
+239
View File
@@ -0,0 +1,239 @@
package web
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"sync"
"testing"
"time"
"supermarket/internal/oidc"
"supermarket/internal/users"
)
// fakeCore is an Authelia for tests: whoever "signs in" there is who.
type fakeCore struct {
srv *httptest.Server
mu sync.Mutex
who map[string]any // the claims of the person signing in
challenge map[string]string
nonce map[string]string
secret string
}
func newFakeCore(t *testing.T) *fakeCore {
t.Helper()
f := &fakeCore{challenge: map[string]string{}, nonce: map[string]string{}}
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
switch r.URL.Path {
case "/.well-known/openid-configuration":
json.NewEncoder(w).Encode(map[string]any{"issuer": f.srv.URL, "authorization_endpoint": f.srv.URL + "/api/oidc/authorization",
"token_endpoint": f.srv.URL + "/api/oidc/token", "end_session_endpoint": f.srv.URL + "/logout"})
case "/api/oidc/token":
r.ParseForm()
code := r.PostForm.Get("code")
sum := sha256.Sum256([]byte(r.PostForm.Get("code_verifier")))
if r.PostForm.Get("client_secret") != f.secret || base64.RawURLEncoding.EncodeToString(sum[:]) != f.challenge[code] {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
return
}
c := map[string]any{"iss": f.srv.URL, "aud": "supermarket", "exp": time.Now().Add(time.Minute).Unix(), "nonce": f.nonce[code]}
for k, v := range f.who {
c[k] = v
}
p, _ := json.Marshal(c)
json.NewEncoder(w).Encode(map[string]string{"access_token": "at", "id_token": "e30." + base64.RawURLEncoding.EncodeToString(p) + ".x"})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(f.srv.Close)
return f
}
// signInWithCore goes through the whole sign-in, and returns the
// callback's answer.
func (f *fakeCore) signInWithCore(t *testing.T, h http.Handler, form url.Values) *httptest.ResponseRecorder {
t.Helper()
rec := postForm(h, "/signin/core", form)
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), f.srv.URL) {
return rec
}
u, _ := url.Parse(rec.Header().Get("Location"))
q := u.Query()
code := "code-" + q.Get("state")[:6]
f.mu.Lock()
f.challenge[code], f.nonce[code] = q.Get("code_challenge"), q.Get("nonce")
f.mu.Unlock()
return do(h, http.MethodGet, "/auth/core/callback?state="+url.QueryEscape(q.Get("state"))+"&code="+code, nil, nil)
}
// setUpCore makes the team's client and turns sign-in with the Core on.
func setUpCore(t *testing.T, s *Server, h http.Handler, c *http.Cookie, f *fakeCore, extra url.Values) {
t.Helper()
as(h, c, http.MethodPost, "/settings/core", url.Values{"domain": {"core.example.com"}})
as(h, c, http.MethodPost, "/settings/signin/secret", url.Values{"client_id": {"supermarket"}})
f.secret = s.Secrets.Get(coreSecret)
form := url.Values{"enabled": {"on"}, "issuer": {strings.Replace(f.srv.URL, "http://", "https://", 1)}}
for k, v := range extra {
form[k] = v
}
if rec := as(h, c, http.MethodPost, "/settings/signin/save", form); rec.Code != http.StatusSeeOther {
t.Fatalf("save: %d %s", rec.Code, rec.Body.String())
}
// The fake speaks plain HTTP: the setting says https, as the form wants.
cfg := s.coreSignin()
cfg.Issuer = f.srv.URL
s.DB.PutJSON(coreSigninKey, cfg)
}
func TestCoreSigninSettings(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, owner)
if body := as(h, c, http.MethodGet, "/settings/signin", nil).Body.String(); !strings.Contains(body, "Core &amp; Hermes") {
t.Error("asks for the Core first")
}
as(h, c, http.MethodPost, "/settings/core", url.Values{"domain": {"core.example.com"}})
as(h, c, http.MethodPost, "/settings/signin/secret", url.Values{"client_id": {"supermarket"}})
body := as(h, c, http.MethodGet, "/settings/signin", nil).Body.String()
m := regexp.MustCompile(`client_secret: &#39;(\$pbkdf2-sha512\$310000\$[^&]+)&#39;`).FindStringSubmatch(body)
if m == nil || !oidc.CheckHash(s.Secrets.Get(coreSecret), m[1]) {
t.Fatalf("the entry's hash: %s", body)
}
for _, want := range []string{"https://authelia.core.example.com", "- &#39;http://localhost:8470/auth/core/callback&#39;", "require_pkce: true", "&#39;groups&#39;"} {
if !strings.Contains(body, want) {
t.Errorf("lacks %s", want)
}
}
if strings.Contains(body, s.Secrets.Get(coreSecret)) {
t.Error("the secret itself is shown")
}
}
func TestSignInWithCore(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
f := newFakeCore(t)
setUpCore(t, s, h, oc, f, nil)
if body := do(h, http.MethodGet, "/signin", nil, nil).Body.String(); !strings.Contains(body, "Sign in with core.example.com") {
t.Error("no button on the sign-in page")
}
// Jo is invited; signing in with the Core accepts the invitation.
as(h, oc, http.MethodPost, "/settings/users", url.Values{"email": {"jo@example.com"}, "name": {"Jo"}, "role": {"member"}, "module:seo": {"view"}})
f.who = map[string]any{"sub": "jo-sub", "email": "Jo@Example.com", "email_verified": true, "name": "Jo Lee"}
rec := f.signInWithCore(t, h, url.Values{"next": {"/seo"}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/seo" || cookieOf(rec, sessionCookie) == nil {
t.Fatalf("callback: %d %s", rec.Code, rec.Body.String())
}
jo, _ := users.ByEmail(s.DB, "jo@example.com")
if jo.Status != users.Active || !strings.HasSuffix(jo.OIDCSubject, "|jo-sub") {
t.Errorf("jo %+v", jo)
}
// Next time by the subject, even with another address at the Core.
f.who = map[string]any{"sub": "jo-sub", "email": "jo.lee@example.com", "email_verified": true}
if rec := f.signInWithCore(t, h, url.Values{}); rec.Code != http.StatusSeeOther {
t.Errorf("by subject: %d %s", rec.Code, rec.Body.String())
}
// Someone not invited isn't let in, nor an unverified address.
f.who = map[string]any{"sub": "eve", "email": "eve@example.com", "email_verified": true}
if rec := f.signInWithCore(t, h, url.Values{}); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "invited") {
t.Errorf("not invited: %d", rec.Code)
}
f.who = map[string]any{"sub": "x", "email": "owner@example.com", "email_verified": false}
if rec := f.signInWithCore(t, h, url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("unverified email: %d", rec.Code)
}
// A state can't be used twice, nor made up.
if rec := do(h, http.MethodGet, "/auth/core/callback?state=made-up&code=x", nil, nil); rec.Code != http.StatusBadRequest {
t.Errorf("made-up state: %d", rec.Code)
}
// The log has them.
body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String()
if !strings.Contains(body, "with the Core") || !strings.Contains(body, "failed to sign in") {
t.Error("not in the log")
}
// Signing out of Supermarket signs out of the Core too.
f.who = map[string]any{"sub": "jo-sub", "email": "jo@example.com", "email_verified": true}
jc := cookieOf(f.signInWithCore(t, h, url.Values{}), sessionCookie)
if rec := as(h, jc, http.MethodPost, "/signout", url.Values{}); !strings.HasPrefix(rec.Header().Get("Location"), f.srv.URL+"/logout?") {
t.Errorf("sign-out: %s", rec.Header().Get("Location"))
}
}
func TestCoreOnlyAndAutoJoin(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.View})
oc := sessionFor(t, s, owner)
f := newFakeCore(t)
setUpCore(t, s, h, oc, f, url.Values{"require_core": {"on"}, "auto_join": {"on"}, "module:content": {"edit"}})
// Passwords off, but the owner's.
pw := url.Values{"email": {"sam@example.com"}, "password": {"a long enough one"}}
if rec := signin(h, "203.0.113.70", pw); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "Sign in with your Core") {
t.Errorf("member's password: %d", rec.Code)
}
pw.Set("email", "owner@example.com")
if rec := signin(h, "203.0.113.70", pw); rec.Code != http.StatusSeeOther {
t.Errorf("owner's password: %d", rec.Code)
}
// Anyone at the Core's domain joins, with the modules chosen.
f.who = map[string]any{"sub": "kim", "email": "kim@core.example.com", "email_verified": true, "name": "Kim"}
if rec := f.signInWithCore(t, h, url.Values{}); rec.Code != http.StatusSeeOther {
t.Fatalf("auto-join: %d %s", rec.Code, rec.Body.String())
}
kim, err := users.ByEmail(s.DB, "kim@core.example.com")
if err != nil {
t.Fatal(err)
}
m, _ := users.MembershipOf(s.DB, users.Team, kim.ID)
if m.Role != users.Member || m.Modules["content"] != users.Edit || len(m.Modules) != 1 || kim.Name != "Kim" {
t.Errorf("kim %+v %+v", kim, m)
}
// Elsewhere: no.
f.who = map[string]any{"sub": "out", "email": "out@other.example", "email_verified": true}
if rec := f.signInWithCore(t, h, url.Values{}); rec.Code != http.StatusForbidden {
t.Errorf("another domain: %d", rec.Code)
}
}
func TestCoreSigninMultiTenant(t *testing.T) {
s, h := newMultiEdition(t)
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
newTeam(t, s, "Bolt", "bea@bolt.example")
users.Prove(s.platform(), a.ID, "dns", time.Now())
ta, _ := s.forTeam(a.ID)
f := newFakeCore(t)
setUpCore(t, ta, h, ac, f, nil)
sam := addUserIn(t, s, a.ID, "sam@acme.example", users.Member)
_ = sam
if body := do(h, http.MethodGet, "/signin", nil, nil).Body.String(); !strings.Contains(body, `name="domain"`) {
t.Error("no domain field")
}
if rec := postForm(h, "/signin/core", url.Values{"domain": {"bolt.example"}}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("a team without its domain proved, or a Core: %d", rec.Code)
}
f.who = map[string]any{"sub": "sam", "email": "sam@acme.example", "email_verified": true}
rec := f.signInWithCore(t, h, url.Values{"domain": {"www.acme.example"}})
c := cookieOf(rec, sessionCookie)
if rec.Code != http.StatusSeeOther || c == nil {
t.Fatalf("callback: %d %s", rec.Code, rec.Body.String())
}
sess, _, _ := users.Lookup(s.platform(), c.Value, time.Now())
if sess.Team != a.ID || sess.Via != "core" {
t.Errorf("session %+v", sess)
}
}
+9
View File
@@ -33,6 +33,7 @@ import (
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/metrics"
"supermarket/internal/oidc"
"supermarket/internal/posting"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
@@ -113,6 +114,9 @@ type teamCache struct {
// Google's access token, which lasts an hour.
googleToken string
googleExpires time.Time
// The Core's Authelia: its discovery document, kept a while.
provider *oidc.Provider
providerAt time.Time
}
// st is the shared state, made on first use.
@@ -346,6 +350,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /teams/switch", (*Server).teamSwitch)
mux.HandleFunc("GET /teams/new", (*Server).teamNewPage)
mux.HandleFunc("POST /teams/new", (*Server).teamNew)
mux.HandleFunc("POST /signin/core", (*Server).signinCore)
mux.HandleFunc("GET /auth/core/callback", (*Server).coreCallbackPage)
mux.HandleFunc("GET /settings/signin", (*Server).signinSettingsPage)
mux.HandleFunc("POST /settings/signin/{action}", (*Server).signinSettingsAction)
mux.HandleFunc("GET /signin", (*Server).signinPage)
mux.HandleFunc("POST /signin", (*Server).signin)
mux.HandleFunc("POST /signin/code", (*Server).signinCode)
@@ -935,6 +943,7 @@ var flashes = map[string]string{
"team-restored": "Restored.",
"exported": "Exported: %d rows. Download it below.",
"undeleted": "The team won't be deleted: it's back as it was.",
"secret-made": "The client's secret is made: add the entry below to the Core, then Test.",
"domain-released": "Released: another team can prove the domain now.",
"invitations-resent": "Sent %d invitations again.",
"view-needs-reason": "Give a reason and how long: it's recorded in the team's own log.",
+37 -2
View File
@@ -25,6 +25,8 @@ type signinForm struct {
Problem string
Sent bool // a reset link went out (or would have)
Reset string
Core string // "Sign in with <the Core>": its domain, on the server edition
CoreMulti bool // the multi-tenant edition: ask for the team's domain
}
// safeNext is where to go after signing in: a path in this app, else the
@@ -46,10 +48,13 @@ func (s *Server) signinPage(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, next, http.StatusSeeOther)
return
}
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: signinForm{Next: next, Email: r.URL.Query().Get("email")}})
f := signinForm{Next: next, Email: r.URL.Query().Get("email")}
s.withCore(&f)
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f})
}
func (s *Server) signinFail(w http.ResponseWriter, r *http.Request, f signinForm, code int) {
s.withCore(&f)
w.WriteHeader(code)
s.render(w, r, "signin", page{Title: "Sign in", Bare: true, Data: f})
}
@@ -91,6 +96,11 @@ func (s *Server) signin(w http.ResponseWriter, r *http.Request) {
s.signinFail(w, r, f, http.StatusForbidden)
return
}
if msg := s.passwordsOff(u); msg != "" {
f.Problem = msg
s.signinFail(w, r, f, http.StatusForbidden)
return
}
if u.TwoFactor {
token, err := users.NewLink(s.DB, users.CodeLink, u.ID, now)
if err != nil {
@@ -254,16 +264,41 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti
}
func (s *Server) signout(w http.ResponseWriter, r *http.Request) {
if viewerOf(r).User != nil {
v := viewerOf(r)
if v.User != nil {
s.audit(r, "signout", "", "")
}
// Signed in with the Core: out of the Core too, where it can.
core := ""
if v.Session != nil && v.Session.Via == "core" {
if ts, err := s.forTeam(v.Session.Team); err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
core = ts.coreSignOut(ctx)
cancel()
}
}
if err := s.endSession(w, r); err != nil {
s.serverError(w, err)
return
}
if core != "" {
http.Redirect(w, r, core, http.StatusSeeOther)
return
}
redirect(w, r, "/signin", "signed-out")
}
// withCore adds the Core's sign-in to the sign-in page, where it's set up.
func (s *Server) withCore(f *signinForm) {
if s.multi() {
f.CoreMulti = true
return
}
if s.coreReady() {
f.Core = s.core().Domain
}
}
// Resetting a password.
func (s *Server) forgotPage(w http.ResponseWriter, r *http.Request) {
+4
View File
@@ -18,6 +18,10 @@
</fieldset>{{end}}
<button type="submit">Join</button>
</form>
{{with .Core}}<form class="card" method="post" action="/signin/core">
<p>Or join with your account at <strong>{{.}}</strong>, with no password here:</p>
<button type="submit" class="secondary">Sign in with {{.}}</button>
</form>{{end}}
{{else}}
<h1>This invitation doesn't work</h1>
<section class="card">
+1
View File
@@ -154,6 +154,7 @@
{{if $.Can "admin"}}
<div class="nav-label">Company</div>
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
{{with $.Viewer}}{{if .User}}<a href="/settings/signin" {{if eq $.Nav "settings/signin"}}aria-current="page"{{end}}>{{template "icon" "core"}}Sign-in</a>{{end}}{{end}}
{{if $.Multi}}<a href="/settings/domain" {{if eq .Nav "settings/domain"}}aria-current="page"{{end}}>{{template "icon" "sites"}}Domain</a>{{end}}
<div class="nav-label">Connections</div>
<a href="/settings/connections" {{if eq .Nav "settings/connections"}}aria-current="page"{{end}}>{{template "icon" "core"}}All connections</a>
@@ -0,0 +1,43 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Sign-in</h2>
<p class="lede">People can sign in with their Federated Core account, through the Core's Authelia (OpenID Connect), as well as, or instead of, a password here.</p>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
{{with .Tested}}<p class="flash" role="status">{{.}}</p>{{end}}
{{if not .Core}}
<section class="card"><p>First enter the Core's domain under <a href="/settings/core">Core &amp; Hermes</a>.</p></section>
{{else}}
<section class="card">
<h3>1. The client</h3>
<dl class="facts">
<dt>Issuer</dt><dd><code>{{.Issuer}}</code></dd>
<dt>Redirect address</dt><dd><code>{{.Callback}}</code></dd>
</dl>
<form method="post" action="/settings/signin/secret" class="row wrap">
<label class="small">Client ID <input name="client_id" value="{{.C.ClientID}}" size="16"></label>
<button type="submit" class="secondary" {{if .C.Hash}}data-confirm="Make a new secret? The entry on the Core must then be changed too."{{end}}>{{if .C.Hash}}Make a new secret{{else}}Make the client's secret{{end}}</button>
</form>
<p class="help">Supermarket keeps the secret, encrypted; only its hash goes to the Core.</p>
</section>
{{with .Block}}
<section class="card" id="block">
<h3>2. On the Core</h3>
<p>The Core's admin adds this entry under <code>identity_providers.oidc.clients</code> in Authelia's <code>idproviders.yml</code>, beside the other services', then restarts Authelia:</p>
<pre id="client-block">{{.}}</pre>
<button type="button" class="secondary small" data-copy="client-block">Copy</button>
</section>
<section class="card">
<h3>3. Test, and turn it on</h3>
<form method="post" action="/settings/signin/test"><button type="submit" class="secondary">Test</button> <span class="help">Reads Authelia's discovery document.</span></form>
<form method="post" action="/settings/signin/save">
<label class="small">Issuer, if not <code>https://authelia.{{$.Data.Domain}}</code> <input name="issuer" value="{{$.Data.C.Issuer}}" placeholder="https://authelia.{{$.Data.Domain}}"></label>
<label class="check"><input type="checkbox" name="enabled" {{if $.Data.C.Enabled}}checked{{end}}> <span>People may sign in with the Core</span></label>
<label class="check"><input type="checkbox" name="require_core" {{if $.Data.C.RequireCore}}checked{{end}}> <span>Only with the Core: passwords are off, except the owner's (a way in if the Core is down)</span></label>
<label class="check"><input type="checkbox" name="auto_join" {{if $.Data.C.AutoJoin}}checked{{end}}> <span>Anyone with an address at <strong>{{$.Data.Domain}}</strong> may join, as a member with these modules:</span></label>
{{template "access-fields" (dict "Role" "member" "Modules" $.Data.C.AutoModules "Grants" $.Data.Grants)}}
<p class="help">Otherwise only people invited may sign in: matched by their email the first time, then by their account at the Core.</p>
<button type="submit">Save</button>
</form>
</section>
{{end}}
{{end}}
{{end}}{{template "settings-end"}}{{end}}
+16
View File
@@ -20,6 +20,22 @@
<label>Password <input type="password" name="password" autocomplete="current-password" required {{if .Email}}autofocus{{end}}></label>
<button type="submit">Sign in</button>
</form>
{{if .Core}}
<form class="card" method="post" action="/signin/core">
<input type="hidden" name="next" value="{{.Next}}">
<button type="submit" class="secondary">Sign in with {{.Core}}</button>
<p class="help">Your Core's account, with its own two-factor sign-in if it has one.</p>
</form>
{{else if .CoreMulti}}
<details class="card">
<summary>Sign in with your Core</summary>
<form method="post" action="/signin/core">
<input type="hidden" name="next" value="{{.Next}}">
<label>Your company's website <input name="domain" placeholder="example.com" required></label>
<button type="submit" class="secondary">Continue to your Core</button>
</form>
</details>
{{end}}
<p class="help"><a href="/forgot{{with .Email}}?email={{.}}{{end}}">Forgotten your password?</a>{{if $.Multi}} · New here? <a href="/signup">Set up your team</a>{{end}}</p>
{{end}}
{{end}}{{end}}
+4
View File
@@ -502,6 +502,7 @@ type inviteData struct {
Emails []emailKind
Zones []string
Problem string
Core string // the Core's domain, if people can sign in with it
}
func (s *Server) invitePage(w http.ResponseWriter, r *http.Request) {
@@ -545,6 +546,9 @@ func (s *Server) inviteData(w http.ResponseWriter, r *http.Request) (*inviteData
return nil, false
}
d.Emails = emailsFor(m)
if s.coreReady() {
d.Core = s.core().Domain
}
return d, true
}