SPB Git

Repository Public

service.go 12.2 KB 334 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/identity/service.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142package identity4344import (45	"context"46	"crypto/hmac"47	"crypto/rand"48	"crypto/sha256"49	"encoding/base64"50	"errors"51	"fmt"52	"net/http"53	"os"54	"path/filepath"55	"regexp"56	"strings"57	"time"5859	"github.com/go-webauthn/webauthn/protocol"60	"github.com/go-webauthn/webauthn/webauthn"61	"github.com/google/uuid"62	"github.com/jackc/pgx/v5"63	"github.com/jackc/pgx/v5/pgxpool"6465	"clustr.spboucher.ai/mcc/internal/audit"66	"clustr.spboucher.ai/mcc/internal/authz"67	"clustr.spboucher.ai/mcc/internal/config"68	"clustr.spboucher.ai/mcc/internal/httpx"69)7071type Service struct {72	pool    *pgxpool.Pool73	cfg     *config.Config74	wa      *webauthn.WebAuthn75	csrfKey []byte76	now     func() time.Time77}7879// Errors returned to clients. Messages never reveal whether an account,80// credential or invitation exists.81var (82	ErrChallenge       = httpx.Err(http.StatusBadRequest, "challenge_invalid", "This sign-in attempt has expired or was already used. Start again.")83	ErrCredential      = httpx.Err(http.StatusUnauthorized, "credential_rejected", "The passkey could not be verified.")84	ErrInvitation      = httpx.Err(http.StatusGone, "invitation_invalid", "This invitation is no longer valid.")85	ErrSetupTx         = httpx.Err(http.StatusGone, "setup_transaction_invalid", "This setup session has expired. Ask for a new invitation.")86	ErrHandleTaken     = httpx.Conflict("handle_taken", "This handle is already in use.")87	ErrLastPasskey     = httpx.Conflict("last_passkey", "You cannot remove your only passkey.")88	ErrLastOwner       = httpx.Conflict("last_owner", "The last active owner cannot be demoted or disabled.")89	ErrSelfModify      = httpx.Conflict("self_modification", "You cannot change your own role or disable yourself.")90	ErrRefresh         = httpx.Err(http.StatusUnauthorized, "refresh_rejected", "The session can no longer be refreshed. Sign in again.")91	ErrWrongAccount    = httpx.Err(http.StatusForbidden, "wrong_account", "This invitation is for a different account.")92	ErrProfileRequired = httpx.Conflict("profile_required", "Choose a handle and a display name first.")93)9495var handleRE = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{1,31}$`)9697func New(pool *pgxpool.Pool, cfg *config.Config) (*Service, error) {98	required := true99	wa, err := webauthn.New(&webauthn.Config{100		RPID:                  cfg.RPID,101		RPDisplayName:         "MacLustr Command Center",102		RPOrigins:             []string{cfg.PublicOrigin},103		AttestationPreference: protocol.PreferNoAttestation,104		AuthenticatorSelection: protocol.AuthenticatorSelection{105			ResidentKey:        protocol.ResidentKeyRequirementRequired,106			RequireResidentKey: &required,107			UserVerification:   protocol.VerificationRequired,108		},109		Timeouts: webauthn.TimeoutsConfig{110			Login:        webauthn.TimeoutConfig{Enforce: true, Timeout: challengeTTL, TimeoutUVD: challengeTTL},111			Registration: webauthn.TimeoutConfig{Enforce: true, Timeout: challengeTTL, TimeoutUVD: challengeTTL},112		},113	})114	if err != nil {115		return nil, fmt.Errorf("identity: webauthn config: %w", err)116	}117	key, err := loadOrCreateKey(cfg.SecretPath("csrf.key"))118	if err != nil {119		return nil, err120	}121	return &Service{pool: pool, cfg: cfg, wa: wa, csrfKey: key, now: func() time.Time { return time.Now().UTC() }}, nil122}123124// SetClock replaces the clock (tests only).125func (s *Service) SetClock(now func() time.Time) { s.now = now }126127func loadOrCreateKey(path string) ([]byte, error) {128	if b, err := os.ReadFile(path); err == nil {129		if len(b) != 32 {130			return nil, fmt.Errorf("identity: %s must hold 32 bytes", path)131		}132		return b, nil133	} else if !errors.Is(err, os.ErrNotExist) {134		return nil, err135	}136	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {137		return nil, err138	}139	b := make([]byte, 32)140	if _, err := rand.Read(b); err != nil {141		return nil, err142	}143	// O_EXCL: two services starting together cannot both create different keys.144	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)145	if errors.Is(err, os.ErrExist) {146		return loadOrCreateKey(path)147	}148	if err != nil {149		return nil, err150	}151	defer f.Close()152	if _, err := f.Write(b); err != nil {153		return nil, err154	}155	return b, f.Sync()156}157158// CSRFToken derives the anti-CSRF token bound to a cookie session token.159// A cross-site attacker can make the browser send the cookie but cannot read160// it, hence cannot compute this value.161func (s *Service) CSRFToken(sessionToken string) string {162	m := hmac.New(sha256.New, s.csrfKey)163	m.Write([]byte("mcc-csrf-v1\x00"))164	m.Write([]byte(sessionToken))165	return base64.RawURLEncoding.EncodeToString(m.Sum(nil))166}167168func (s *Service) CheckCSRF(sessionToken, presented string) bool {169	return presented != "" && hmac.Equal([]byte(s.CSRFToken(sessionToken)), []byte(presented))170}171172// StepUpFresh reports whether the session's last passkey ceremony is recent173// enough for sensitive operations.174func (s *Service) StepUpFresh(sess *Session) bool {175	return s.now().Sub(sess.AuthenticatedAt) <= s.cfg.StepUpWindow176}177178func (s *Service) audit(ctx context.Context, db audit.DB, sess *Session, meta ReqMeta, action, targetKind, targetID string, outcome audit.Outcome, detail string, params map[string]any) error {179	e := audit.Entry{ActorKind: "system", Action: action, TargetKind: targetKind, TargetID: targetID, Outcome: outcome,180		Detail: detail, Params: params, CorrelationID: meta.Correlation, IP: meta.IP}181	if sess != nil {182		e.ActorKind, e.ActorID, e.ActorLabel = "user", &sess.User.ID, sess.User.Handle183		e.SessionID, e.DeviceID = &sess.ID, &sess.DeviceID184	}185	_, err := audit.Append(ctx, db, e)186	return err187}188189func normalizeHandle(h string) (string, error) {190	h = strings.ToLower(strings.TrimSpace(h))191	if !handleRE.MatchString(h) {192		return "", httpx.Validation("Handle must be 2–32 characters: lowercase letters, digits, dot, dash, underscore.")193	}194	return h, nil195}196197func normalizeName(n string) (string, error) {198	n = strings.Join(strings.Fields(n), " ")199	if n == "" || len([]rune(n)) > 80 {200		return "", httpx.Validation("Display name must be 1–80 characters.")201	}202	return n, nil203}204205const userCols = `u.id, u.handle, u.display_name, u.role::text, u.locale, u.webauthn_handle, u.created_at, u.disabled_at`206207func scanUser(row pgx.Row, extra ...any) (User, error) {208	var u User209	var role string210	dst := append([]any{&u.ID, &u.Handle, &u.DisplayName, &role, &u.Locale, &u.WebAuthnHandle, &u.CreatedAt, &u.DisabledAt}, extra...)211	err := row.Scan(dst...)212	u.Role = authz.Role(role)213	return u, err214}215216func (s *Service) UserByID(ctx context.Context, id uuid.UUID) (User, error) {217	u, err := scanUser(s.pool.QueryRow(ctx, `select `+userCols+` from users u where u.id=$1`, id))218	if errors.Is(err, pgx.ErrNoRows) {219		return u, httpx.ErrNotFound220	}221	return u, err222}223224func (s *Service) ListUsers(ctx context.Context) ([]User, error) {225	rows, err := s.pool.Query(ctx, `select `+userCols+` from users u order by u.handle`)226	if err != nil {227		return nil, err228	}229	return pgx.CollectRows(rows, func(r pgx.CollectableRow) (User, error) { return scanUser(r) })230}231232// activeOwners counts owners who can still sign in.233func activeOwners(ctx context.Context, q interface {234	QueryRow(ctx context.Context, sql string, args ...any) pgx.Row235}) (int, error) {236	var n int237	err := q.QueryRow(ctx, `select count(*) from users u where u.role='owner' and u.disabled_at is null238		and exists (select 1 from passkeys p where p.user_id=u.id and p.revoked_at is null)`).Scan(&n)239	return n, err240}241242// UpdateProfile lets a user change their own display name and locale.243func (s *Service) UpdateProfile(ctx context.Context, sess *Session, displayName, locale *string, meta ReqMeta) (User, error) {244	if displayName != nil {245		n, err := normalizeName(*displayName)246		if err != nil {247			return User{}, err248		}249		displayName = &n250	}251	if locale != nil && *locale != "fr" && *locale != "en" {252		return User{}, httpx.Validation("Locale must be fr or en.")253	}254	if _, err := s.pool.Exec(ctx, `update users set display_name=coalesce($2,display_name), locale=coalesce($3,locale) where id=$1`,255		sess.User.ID, displayName, locale); err != nil {256		return User{}, err257	}258	return s.UserByID(ctx, sess.User.ID)259}260261// UpdateUser changes another user's role and/or disabled state.262func (s *Service) UpdateUser(ctx context.Context, actor *Session, targetID uuid.UUID, role *authz.Role, disabled *bool, meta ReqMeta) (User, error) {263	if actor.User.ID == targetID {264		return User{}, ErrSelfModify265	}266	tx, err := s.pool.Begin(ctx)267	if err != nil {268		return User{}, err269	}270	defer tx.Rollback(ctx)271	// Serialize ownership changes so two concurrent demotions cannot remove the last owner.272	if _, err := tx.Exec(ctx, `select pg_advisory_xact_lock(7305001)`); err != nil {273		return User{}, err274	}275	target, err := scanUser(tx.QueryRow(ctx, `select `+userCols+` from users u where u.id=$1 for update`, targetID))276	if errors.Is(err, pgx.ErrNoRows) {277		return User{}, httpx.ErrNotFound278	} else if err != nil {279		return User{}, err280	}281	deny := func(reason string) (User, error) {282		tx.Rollback(ctx)283		s.audit(ctx, s.pool, actor, meta, "user.update", "user", targetID.String(), audit.Denied, reason, nil)284		return User{}, httpx.ErrForbidden285	}286	next := target.Role287	if role != nil {288		if !authz.CanAssignRole(actor.User.Role, target.Role, *role) {289			return deny("role assignment not permitted")290		}291		next = *role292	}293	if disabled != nil && target.Role == authz.Owner && actor.User.Role != authz.Owner {294		return deny("only an owner may disable an owner")295	}296	willDisable := disabled != nil && *disabled297	if target.Role == authz.Owner && target.DisabledAt == nil && (next != authz.Owner || willDisable) {298		n, err := activeOwners(ctx, tx)299		if err != nil {300			return User{}, err301		}302		if n <= 1 {303			return User{}, ErrLastOwner304		}305	}306	params := map[string]any{}307	if role != nil && next != target.Role {308		params["role_from"], params["role_to"] = string(target.Role), string(next)309		if _, err := tx.Exec(ctx, `update users set role=$2::user_role where id=$1`, targetID, string(next)); err != nil {310			return User{}, err311		}312	}313	if disabled != nil && *disabled != (target.DisabledAt != nil) {314		params["disabled"] = *disabled315		if *disabled {316			if _, err := tx.Exec(ctx, `update users set disabled_at=now() where id=$1`, targetID); err != nil {317				return User{}, err318			}319			if _, err := tx.Exec(ctx, `update sessions set revoked_at=now(), revoked_reason='user_disabled' where user_id=$1 and revoked_at is null`, targetID); err != nil {320				return User{}, err321			}322		} else if _, err := tx.Exec(ctx, `update users set disabled_at=null where id=$1`, targetID); err != nil {323			return User{}, err324		}325	}326	if err := s.audit(ctx, tx, actor, meta, "user.update", "user", targetID.String(), audit.Success, "", params); err != nil {327		return User{}, err328	}329	if err := tx.Commit(ctx); err != nil {330		return User{}, err331	}332	return s.UserByID(ctx, targetID)333}334
Files main
Menu

Theme