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

+13 -13
View File
@@ -291,10 +291,10 @@ type Service struct {
// allowed email-only edits without the current password. Password changes
// always require current credentials in UpdateMe.
reauthenticateEmailChanges bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter
@@ -397,16 +397,16 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG
configurationError = errSecretNotUsable
}
return &Service{
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
}
}
+2 -130
View File
@@ -48,10 +48,7 @@ type SchemaOptions struct {
SingleUser bool
// APITokens creates the optional per-user API token table.
APITokens bool
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user
// 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 creates auth_known_projects for AuthGuard's project catalog and admin UI.
ProjectScoping bool
}
@@ -151,12 +148,6 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
label TEXT NOT NULL DEFAULT '',
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 {
return fmt.Errorf("ensure project-scoping schema: %w", err)
}
@@ -590,18 +581,6 @@ func (s *Store) DeleteAllUsers(ctx context.Context) error {
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
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
type KnownProject struct {
@@ -611,9 +590,7 @@ type KnownProject struct {
// 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
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
// against a user's own rows, never against auth_known_projects).
// registered is dropped, so the admin UI never offers a stale key.
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
if err := s.validate(); err != nil {
return err
@@ -665,111 +642,6 @@ func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
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")
// 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.
const (
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
TOTPSecretLength = 32
TOTPPeriod = 30 * time.Second
TOTPDigits = 6
TOTPSecretBytes = 20
TOTPWindow = 1
)
// 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
// it exclusively owns (e.g. ContentScanner's media_worker_jobs/
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media,
// ProjectConfigurator's mount_paths) - those are NOT run here.
// media_analysis_tasks, CraftStudio's generated_media/downloaded_media) -
// those are NOT run here.
func (c *Core) Migrate(ctx context.Context) error {
for _, statement := range migrationStatements {
if _, err := c.db.Exec(ctx, statement); err != nil {
@@ -67,6 +67,7 @@ var migrationStatements = []string{
file_path TEXT,
original_filename TEXT,
active BOOLEAN NOT NULL DEFAULT TRUE,
content_scanner_processed BOOLEAN NOT NULL DEFAULT FALSE,
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
width INT,
height INT,
@@ -81,6 +82,7 @@ var migrationStatements = []string{
created_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_avg_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) {
h := newDBHarness(t)
h.insertMedia(t, "rt-stats", "video", "rt-stats.mp4", true)
state := func(token string) map[string]any {
return dataOf(t, h.do(http.MethodGet, "/media/state?mediaKey=rt-stats", token, ""))
}