refactor(auth): remove obsolete project restriction APIs

- Remove legacy project restriction schema and helpers
- Install Python test extras in CI
- Update the quality report status
This commit is contained in:
Gabriel20xx committed 2026-10-20 19:32:45 +00:00
1 parent f7819904b9
commit add64ff180
10 files changed
+32 -160

No files matched your search

+1 -1
View File
@@ -99,7 +99,7 @@ jobs:
with: with:
python-version: '3.12' python-version: '3.12'
- name: Install package - name: Install package
run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi]" run: python -m pip install --upgrade pip -e "packages/python-backend[fastapi,test]"
- name: Run Python tests - name: Run Python tests
run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py' run: python -m unittest discover -s packages/python-backend/tests -p 'test_*.py'
+3 -2
View File
@@ -117,10 +117,11 @@ The code is generally tidy: no TODO, FIXME or HACK markers in first-party non-te
- **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry. - **Recommendation:** Update the component count to match `index.ts` when the removal is committed, delete the `mediaauth` references, and remove the stale ignore entry.
### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low** ### Q-015 · Go code hygiene: dead code, an oversized file, duplicated helpers and nil-dependency constructors · **Low**
- **Location:** `backend/auth/reset.go` (`ResetManager` has no non-test consumer in this repository), `backend/auth/totp.go:23` (`TOTPSecretLength` unused), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages - **Location:** `backend/auth/reset.go` (`ResetManager` is used by AuthGuard outside this repository), `backend/auth/totp.go` (`TOTPSecretLength` unused), `backend/auth/store.go` (legacy per-user project APIs and expired-session cleanup helper), `backend/auth/proxy.go` (1525 lines mixing middleware, handlers and platform-user SQL), `backend/mediacore/mediacore.go:76-78` (`New` accepts nil CarrierNode or Sync; needs verification in the code), `backend/authclient/client.go:270-278` (two identical branches where the comment says there is a distinction), `writeJSON` and `writeError` duplicated across three packages
- **Description:** Exported helpers with no in-repository callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way. - **Description:** Exported helpers with no workspace callers, a 1525-line file that mixes concerns, duplicated HTTP helpers, a constructor that accepts nil dependencies (which panics on first use rather than at startup), and a branch that is meant to separate transport failures from invalid sessions but returns the same result either way.
- **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup. - **Impact:** Maintenance cost, and a misconfigured service fails on the first request rather than at startup.
- **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them. - **Recommendation:** Remove or move unused code. Split `proxy.go` into middleware, handlers and persistence files. Validate constructor arguments. Share one JSON helper package, and make the authclient branches distinct or merge them.
- **Status:** Partly fixed 2026-10-20 — removed the unused `TOTPSecretLength` constant, legacy per-user project APIs and their schema creation, and unused `DeleteExpiredSessions` helper. No table drop was added; AuthGuard's existing migration continues to transfer legacy restriction rows into roles before clearing them from the old table. `ResetManager` remains because AuthGuard uses it; file splitting, duplicated helpers, and the remaining findings are open.
### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low** ### Q-016 · Web UI: an unkeyed `{#each}` over a prop, and a login-field length rule that also applies to sign-in · **Low**
- **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup) - **Location:** `packages/web-ui/src/lib/components/Header.svelte:168` (`{#each navItems as item}` with no key), `packages/web-ui/src/lib/components/AuthPage.svelte:202` (`minlength="8"` on the sign-in password field, not only on setup)
+13 -13
View File
@@ -291,10 +291,10 @@ type Service struct {
// allowed email-only edits without the current password. Password changes // allowed email-only edits without the current password. Password changes
// always require current credentials in UpdateMe. // always require current credentials in UpdateMe.
reauthenticateEmailChanges bool reauthenticateEmailChanges bool
loginCacheMu sync.Mutex loginCacheMu sync.Mutex
loginCacheValue bool loginCacheValue bool
loginCacheSet bool loginCacheSet bool
loginCacheExpires time.Time loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go. // Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter loginClientAttempts *attemptLimiter
@@ -397,16 +397,16 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
configurationError = errSecretNotUsable configurationError = errSecretNotUsable
} }
return &Service{ return &Service{
store: store, store: store,
cookieName: cookieName, cookieName: cookieName,
secureCookies: secureCookies, secureCookies: secureCookies,
authGuard: client, authGuard: client,
configurationError: configurationError, configurationError: configurationError,
reauthenticateEmailChanges: options.reauthenticateEmailChanges, reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit), loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit), loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit), totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies, trustedProxies: options.trustedProxies,
} }
} }
+2 -130
View File
@@ -48,10 +48,7 @@ type SchemaOptions struct {
SingleUser bool SingleUser bool
// APITokens creates the optional per-user API token table. // APITokens creates the optional per-user API token table.
APITokens bool APITokens bool
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user // ProjectScoping creates auth_known_projects for AuthGuard's project catalog and admin UI.
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
// itself needs this - every other project only ever calls AuthGuard's own API, never these
// tables directly.
ProjectScoping bool ProjectScoping bool
} }
@@ -151,12 +148,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
label TEXT NOT NULL DEFAULT '', label TEXT NOT NULL DEFAULT '',
updated_at TIMESTAMPTZ NOT NULL DEFAULT now() updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
); );
CREATE TABLE IF NOT EXISTS auth_user_projects (
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
project TEXT NOT NULL,
PRIMARY KEY (user_id, project)
);
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
`); err != nil { `); err != nil {
return fmt.Errorf("ensure project-scoping schema: %w", err) return fmt.Errorf("ensure project-scoping schema: %w", err)
} }
@@ -590,18 +581,6 @@ func (s *Store) DeleteAllUsers(ctx context.Context) error {
return nil return nil
} }
// DeleteExpiredSessions performs the periodic session cleanup shared by the
// services. A caller can run it from its own scheduler.
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
return fmt.Errorf("delete expired auth sessions: %w", err)
}
return nil
}
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its // KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects. // admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
type KnownProject struct { type KnownProject struct {
@@ -611,9 +590,7 @@ type KnownProject struct {
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's // SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer // PUT /api/projects/internal whenever its registered-project list changes). A project no longer
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects // registered is dropped, so the admin UI never offers a stale key.
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
// against a user's own rows, never against auth_known_projects).
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error { func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
if err := s.validate(); err != nil { if err := s.validate(); err != nil {
return err return err
@@ -665,111 +642,6 @@ func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
return projects, rows.Err() return projects, rows.Err()
} }
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
// deployment's accounts on upgrade.
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
if err := s.validate(); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("set user projects: %w", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
seen := map[string]bool{}
for _, project := range projects {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || seen[key] {
continue
}
seen[key] = true
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("set user projects: %w", err)
}
return nil
}
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
projects := make([]string, 0)
for rows.Next() {
var project string
if err := rows.Scan(&project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
projects = append(projects, project)
}
return projects, rows.Err()
}
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
// user list screen (avoids one query per row).
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
if err := s.validate(); err != nil {
return nil, err
}
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
if err != nil {
return nil, fmt.Errorf("list user projects: %w", err)
}
defer rows.Close()
result := map[int64][]string{}
for rows.Next() {
var userID int64
var project string
if err := rows.Scan(&userID, &project); err != nil {
return nil, fmt.Errorf("scan user project: %w", err)
}
result[userID] = append(result[userID], project)
}
return result, rows.Err()
}
// IsProjectAllowed reports whether userID may authenticate against project: true when the
// account has no project restrictions at all (the default for every account), or when project is
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
// web UI, which is not itself a "project" another service authenticates against) is always
// allowed; restriction only ever applies once a caller actually identifies itself.
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
project = strings.ToLower(strings.TrimSpace(project))
if project == "" {
return true, nil
}
if err := s.validate(); err != nil {
return false, err
}
var total int
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
return false, fmt.Errorf("count user projects: %w", err)
}
if total == 0 {
return true, nil
}
var allowed bool
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
return false, fmt.Errorf("check user project: %w", err)
}
return allowed, nil
}
var ErrUserExists = errors.New("auth user already exists") var ErrUserExists = errors.New("auth user already exists")
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on. // ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
+4 -5
View File
@@ -16,11 +16,10 @@ import (
// TOTP follows RFC 6238's default interoperable profile. // TOTP follows RFC 6238's default interoperable profile.
const ( const (
TOTPPeriod = 30 * time.Second TOTPPeriod = 30 * time.Second
TOTPDigits = 6 TOTPDigits = 6
TOTPSecretBytes = 20 TOTPSecretBytes = 20
TOTPWindow = 1 TOTPWindow = 1
TOTPSecretLength = 32
) )
// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps. // GenerateTOTPSecret returns a base32 secret suitable for authenticator apps.
+4 -2
View File
@@ -17,8 +17,8 @@ import "context"
// //
// Each per-service backend additionally runs its own migration for tables // Each per-service backend additionally runs its own migration for tables
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/ // it exclusively owns (e.g. ContentScanner's media_worker_jobs/
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media, // media_analysis_tasks, CraftStudio's generated_media/downloaded_media) -
// ProjectConfigurator's mount_paths) - those are NOT run here. // those are NOT run here.
func (c *Core) Migrate(ctx context.Context) error { func (c *Core) Migrate(ctx context.Context) error {
for _, statement := range migrationStatements { for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil { if _, err := c.db.Exec(ctx, statement); err != nil {
@@ -67,6 +67,7 @@ var migrationStatements = []string{
file_path TEXT, file_path TEXT,
original_filename TEXT, original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE, active BOOLEAN NOT NULL DEFAULT TRUE,
content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb, metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT, width INT,
height INT, height INT,
@@ -81,6 +82,7 @@ var migrationStatements = []string{
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW() modified_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)`, )`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_action_count INT`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_avg_speed REAL`,
`ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`, `ALTER TABLE media ADD COLUMN IF NOT EXISTS funscript_max_speed REAL`,
+1
View File
@@ -255,6 +255,7 @@ func TestMediaStreamAndThumbnailAgainstPostgres(t *testing.T) {
func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) { func TestMediaStatsAndViewsAgainstPostgres(t *testing.T) {
h := newDBHarness(t) h := newDBHarness(t)
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
state := func(token string) map[string]any { state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, "")) return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
} }
+1 -5
View File
@@ -3,11 +3,7 @@ import assert from 'node:assert/strict';
import { existsSync, readFileSync } from 'node:fs'; import { existsSync, readFileSync } from 'node:fs';
import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js'; import { hashPassword, passwordHashNeedsUpgrade, verifyAndUpgradePasswordAsync, verifyPassword } from '../src/auth.js';
import { verifyTotp, verifyTotpStep } from '../src/totp.js'; import { verifyTotp, verifyTotpStep } from '../src/totp.js';
import { import { EXAMPLE_INTERNAL_SECRETS, MIN_INTERNAL_SECRET_LENGTH, internalSecretMatches } from '../src/coreconfig.js';
EXAMPLE_INTERNAL_SECRETS,
MIN_INTERNAL_SECRET_LENGTH,
internalSecretMatches,
} from '../src/coreconfig.js';
// The Go, Node and Python auth helpers load the same fixtures; see "description" in the file. // The Go, Node and Python auth helpers load the same fixtures; see "description" in the file.
const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url); const contractUrl = new URL('../../../contract/auth-contract.json', import.meta.url);
+1
View File
@@ -22,6 +22,7 @@ dependencies = [
# consumer does) satisfies this from its own requirements regardless. # consumer does) satisfies this from its own requirements regardless.
[project.optional-dependencies] [project.optional-dependencies]
fastapi = ["fastapi>=0.100", "pydantic>=2"] fastapi = ["fastapi>=0.100", "pydantic>=2"]
test = ["httpx2>=2"]
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
+2 -2
View File
@@ -36,12 +36,12 @@ describe('ProfileDialog password changes', () => {
await submit(); await submit();
expect(onSave).not.toHaveBeenCalled(); expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText('Enter your current password to change it.')).toBeTruthy(); expect(screen.getByText('Enter your current password to change your email or password.')).toBeTruthy();
await fill('currentPassword', 'old-password'); await fill('currentPassword', 'old-password');
await submit(); await submit();
expect(onSave).not.toHaveBeenCalled(); expect(onSave).not.toHaveBeenCalled();
expect(screen.getByText('Enter a current authenticator code to change your password.')).toBeTruthy(); expect(screen.getByText('Enter a current authenticator code to change your email or password.')).toBeTruthy();
await fill('totpToken', '123456'); await fill('totpToken', '123456');
await submit(); await submit();