Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Spraywall can log users in through any OpenID Connect provider (Pocket-ID, Authe
| `OIDC_SCOPES` | `openid email profile groups` | Requested scopes |
| `OIDC_GROUPS_CLAIM` | `groups` | Claim holding the user's group names |
| `OIDC_ADMIN_GROUP` | | Members become instance admins; unconfirmed admins outside the group get setter rights, while confirmed admins removed from the group become climbers on their next SSO login. Other roles are preserved. If unset, roles are never touched |
| `OIDC_ADMIN_MAX_AGE` | `24h` | With `OIDC_ADMIN_GROUP` set, admin rights lapse this long after the user's last SSO login (sessions and password logins don't renew them), so removing someone from the group takes effect within this window. Signing in with SSO again restores them |
| `OIDC_ADMIN_MAX_AGE` | `24h` | With `OIDC_ADMIN_GROUP` set, admin rights lapse this long after the user's last SSO login (sessions and password logins don't renew them), so removing someone from the group takes effect within this window. Wall editing now depends on this instance role (gyms no longer grant separate permissions); sign in with SSO again to restore admin access |
| `PASSWORD_LOGIN_ENABLED` | `true` | `false` = SSO only (disables password login and registration). The server refuses to start unless OIDC is configured |

### Pocket-ID example
Expand Down
1 change: 1 addition & 0 deletions server/db/generated/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 54 additions & 13 deletions server/db/generated/users.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions server/db/migrations/0025_role_lapse.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- +goose Up
ALTER TABLE users ADD COLUMN role_lapsed_from user_role;

-- +goose Down
ALTER TABLE users DROP COLUMN role_lapsed_from;
10 changes: 7 additions & 3 deletions server/db/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ DELETE FROM refresh_tokens WHERE id = $1;
DELETE FROM refresh_tokens WHERE user_id = $1;

-- name: PromoteUserRole :exec
UPDATE users SET role = GREATEST(role, $2), updated_at = now() WHERE id = $1;
UPDATE users SET role = GREATEST(role, $2), role_lapsed_from = NULL, updated_at = now() WHERE id = $1;

-- name: UpdateUserRole :one
UPDATE users SET role = $2, updated_at = now() WHERE id = $1
UPDATE users SET role = $2, role_lapsed_from = NULL, updated_at = now() WHERE id = $1
RETURNING *;

-- name: UpdateUserDisplayName :one
Expand Down Expand Up @@ -74,7 +74,11 @@ DELETE FROM user_identities WHERE id = $1 AND user_id = $2;
SELECT * FROM users WHERE id = $1 FOR UPDATE;

-- name: SyncUserRole :one
UPDATE users SET role = $2, role_synced_at = now(), updated_at = now() WHERE id = $1
UPDATE users SET role = $2, role_synced_at = now(), role_lapsed_from = NULL, updated_at = now() WHERE id = $1
RETURNING *;

-- name: LapseUserRole :one
UPDATE users SET role = $2, role_lapsed_from = role, updated_at = now() WHERE id = $1
RETURNING *;

-- name: DeleteUserIdentitiesByUserID :exec
Expand Down
13 changes: 10 additions & 3 deletions server/internal/oidc/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,14 +544,21 @@ func TestAdminGroupPromotesAndDemotes(t *testing.T) {
t.Fatalf("db role = %s", u.Role)
}

// Groups only available through UserInfo, and no longer in the group.
// SSO clears a previous lapse marker even when the user was removed from the group.
if _, err := env.q.LapseUserRole(ctx, generated.LapseUserRoleParams{ID: pgUUID(res.userID), Role: generated.UserRoleClimber}); err != nil {
t.Fatal(err)
}
res = parseSuccess(t, env.login(t, "/walls", &grant{
claims: idClaims("sub-admin", "boss@example.com", nil),
userinfo: map[string]any{"groups": "users"},
}))
if res.role != "climber" {
t.Fatalf("expected demotion to climber, got %q", res.role)
}
updated, err := env.q.GetUserByID(ctx, pgUUID(res.userID))
if err != nil || updated.RoleLapsedFrom.Valid {
t.Fatalf("SSO login left admin lapse marker set: %+v, err=%v", updated.RoleLapsedFrom, err)
}

// Back in the group via UserInfo.
res = parseSuccess(t, env.login(t, "/walls", &grant{
Expand Down Expand Up @@ -585,8 +592,8 @@ func TestUnconfirmedLegacyAdminWithoutGroupKeepsSetterRole(t *testing.T) {
t.Fatalf("unconfirmed admin outside group got role %q, want setter", res.role)
}
updated, err := env.q.GetUserByID(ctx, admin.ID)
if err != nil || updated.Role != generated.UserRoleSetter {
t.Fatalf("stored role = %v, err=%v; want setter", updated.Role, err)
if err != nil || updated.Role != generated.UserRoleSetter || updated.RoleLapsedFrom.Valid {
t.Fatalf("stored role = %v, lapsed from %+v, err=%v; want setter without lapse", updated.Role, updated.RoleLapsedFrom, err)
}
}

Expand Down
31 changes: 22 additions & 9 deletions server/internal/user/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ type userResponse struct {
CreatedAt time.Time `json:"created_at"`
AvatarURL *string `json:"avatar_url"`
HasPassword bool `json:"has_password"`
AdminLapsed bool `json:"admin_lapsed"`
Identities []identityResponse `json:"identities"`
}

Expand Down Expand Up @@ -297,15 +298,21 @@ func (h *Handler) buildMe(ctx context.Context, u generated.User) (userResponse,
return userResponse{}, err
}

role := string(u.Role)
if effectiveRole := GetUserRole(ctx); effectiveRole != "" {
role = effectiveRole
}
resp := userResponse{
ID: uuidFromPg(u.ID),
Email: u.Email,
DisplayName: u.DisplayName,
Role: string(u.Role),
Role: role,
CreatedAt: u.CreatedAt.Time,
AvatarURL: AvatarURL(u),
HasPassword: u.PasswordHash != "",
Identities: make([]identityResponse, 0, len(identities)),
AdminLapsed: h.opts.AdminRoleMaxAge > 0 && ((u.RoleLapsedFrom.Valid &&
u.RoleLapsedFrom.UserRole == generated.UserRoleAdmin) || adminLapsedFromContext(ctx)),
Identities: make([]identityResponse, 0, len(identities)),
}
for _, ident := range identities {
resp.Identities = append(resp.Identities, identityResponse{
Expand Down Expand Up @@ -346,8 +353,14 @@ func SameIssuer(a, b string) bool {
func (h *Handler) IssueTokens(ctx context.Context, q *generated.Queries, u generated.User) (*TokenPair, error) {
userID := uuidFromPg(u.ID)

if role, demote := h.adminRoleDemotion(u, time.Now()); demote {
demoted, err := q.UpdateUserRole(ctx, generated.UpdateUserRoleParams{ID: u.ID, Role: role})
if role, demote, lapsed := h.adminRoleDemotion(u, time.Now()); demote {
var demoted generated.User
var err error
if lapsed {
demoted, err = q.LapseUserRole(ctx, generated.LapseUserRoleParams{ID: u.ID, Role: role})
} else {
demoted, err = q.UpdateUserRole(ctx, generated.UpdateUserRoleParams{ID: u.ID, Role: role})
}
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -396,17 +409,17 @@ func (h *Handler) IssueTokens(ctx context.Context, q *generated.Queries, u gener
}

// adminRoleDemotion returns the effective fallback for admins under SSO role management.
func (h *Handler) adminRoleDemotion(u generated.User, now time.Time) (generated.UserRole, bool) {
func (h *Handler) adminRoleDemotion(u generated.User, now time.Time) (generated.UserRole, bool, bool) {
if h.opts.AdminRoleMaxAge <= 0 || u.Role != generated.UserRoleAdmin {
return "", false
return "", false, false
}
if !u.RoleSyncedAt.Valid {
return generated.UserRoleSetter, true
return generated.UserRoleSetter, true, false
}
if now.Sub(u.RoleSyncedAt.Time) > h.opts.AdminRoleMaxAge {
return generated.UserRoleClimber, true
return generated.UserRoleClimber, true, true
}
return "", false
return "", false, false
}

func hashToken(token string) string {
Expand Down
11 changes: 10 additions & 1 deletion server/internal/user/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const (
// TokenVersionKey holds the access token's "ver" claim (0 if absent).
TokenVersionKey contextKey = "tokenVersion"
currentUserKey contextKey = "currentUser"
adminLapsedKey contextKey = "adminLapsed"
)

// Authenticate validates the bearer token and loads its account. Tokens
Expand Down Expand Up @@ -102,13 +103,16 @@ func (h *Handler) Authenticate(next http.Handler) http.Handler {

// Apply the same fallback used by IssueTokens before it is persisted.
role := string(u.Role)
if fallback, demote := h.adminRoleDemotion(u, time.Now()); demote {
adminLapsed := false
if fallback, demote, lapsed := h.adminRoleDemotion(u, time.Now()); demote {
role = string(fallback)
u.Role = fallback
adminLapsed = lapsed
}

ctx := context.WithValue(r.Context(), UserIDKey, userID)
ctx = context.WithValue(ctx, UserRoleKey, role)
ctx = context.WithValue(ctx, adminLapsedKey, adminLapsed)
ctx = context.WithValue(ctx, TokenVersionKey, int32(ver))
ctx = context.WithValue(ctx, currentUserKey, u)
next.ServeHTTP(w, r.WithContext(ctx))
Expand All @@ -131,6 +135,11 @@ func CurrentUser(ctx context.Context) (generated.User, bool) {
return u, ok
}

func adminLapsedFromContext(ctx context.Context) bool {
lapsed, _ := ctx.Value(adminLapsedKey).(bool)
return lapsed
}

// SessionCurrent reports whether the request's access token was issued after
// u's last session revocation. Authenticate checks it on every request;
// handlers that reload u later (e.g. under a lock) can check it again.
Expand Down
Loading
Loading