Skip to content

woodglue.auth_store

Users, Role assignments, and credentials in auth.db.

Users, Role assignments, and credentials in auth.db.

AuthStore is the only reader and writer of auth.db. Credentials are opaque random secrets looked up on every request (see docs/adr/0002), so revoking a token, disabling or deleting a User, or changing a Role assignment takes effect immediately, including on a running server.

A User's status (UserStatus) is pending, active, or disabled. A person whose Identity Provider sets admit_as: pending starts pending: signed in, with its synced Role assignments, but no Grants and no way to create credentials until approve_user makes it active. Only person Users are ever pending.

Disabling a User keeps its record, so the person stays refused; it is also how a pending User is denied. Enabling makes a disabled User active, never pending. Deleting erases a User, with its Role assignments, Linked Identities, and credentials; if the person signs in again they become a new User. Run history outside auth.db keeps the deleted User's id.

Each Role assignment has a source: manual for one an admin made, or the sign-in source that set it (provider:<id>, admins), which the next sign-in through it replaces. unassign_role removes a Role from every source, so a synced Role comes back at that User's next sign-in.

Role definitions are not stored here: they come from woodglue.yaml (see woodglue.access). A Role assignment naming a Role that is no longer defined grants nothing.

A Session is the credential behind a browser's cookie. It ends after session_idle without use or session_max after creation, whichever is first; woodglue does not re-check with the Identity Provider in between.

A Delegated Token lets a Process-backed UI call the API as the User viewing it. It belongs to one Session and one UI, carries the Session's Grants narrowed to the UI's own grants, and ends with the Session. Its use does not keep the Session alive: only the person's own requests, including those through the UI, do.

The built-in admin Service User owns the tokens that wgl token prints. Tokens from the pre-Users tokens table are migrated to it on first open, so existing scripts keep working. It cannot be disabled, deleted, or lose the admin Role, so wgl token always yields full access.

MANUAL = 'manual' module-attribute

Source of Role assignments made by an admin, as opposed to synced at sign-in.

UserStatus

Bases: StrEnum

pending Users are signed in but hold no Grants until approved; only person Users can be pending. disabled Users are refused everywhere.

Source code in src/woodglue/auth_store.py
class UserStatus(StrEnum):
    """
    `pending` Users are signed in but hold no Grants until approved; only
    `person` Users can be pending. `disabled` Users are refused everywhere.
    """

    pending = "pending"
    active = "active"
    disabled = "disabled"

RoleAssignment

Bases: BaseModel

One Role given to a User by one source: manual for an admin, otherwise a sign-in source such as provider:<id> or admins, which the next sign-in through it sets again.

Source code in src/woodglue/auth_store.py
class RoleAssignment(BaseModel):
    """
    One Role given to a User by one source: `manual` for an admin, otherwise a
    sign-in source such as `provider:<id>` or `admins`, which the next sign-in
    through it sets again.
    """

    role: str
    source: str

User

Bases: BaseModel

Source code in src/woodglue/auth_store.py
class User(BaseModel):
    id: str
    name: str
    email: str | None = None
    kind: UserKind
    status: UserStatus = UserStatus.active
    roles: list[str] = []
    """Distinct Roles from all of `role_assignments`."""
    role_assignments: list[RoleAssignment] = []
    providers: list[str] = []
    """Identity Providers of the User's Linked Identities."""
    builtin: bool = False
    """The built-in `admin` Service User, which cannot be disabled, deleted, or lose `admin`."""
    created_at: datetime

roles = [] class-attribute instance-attribute

Distinct Roles from all of role_assignments.

providers = [] class-attribute instance-attribute

Identity Providers of the User's Linked Identities.

builtin = False class-attribute instance-attribute

The built-in admin Service User, which cannot be disabled, deleted, or lose admin.

TokenInfo

Bases: BaseModel

A Personal Access Token as listed; never includes the secret.

Source code in src/woodglue/auth_store.py
class TokenInfo(BaseModel):
    """A Personal Access Token as listed; never includes the secret."""

    id: str
    user_id: str
    name: str
    grants: list[str] | None = None
    created_at: datetime
    expires_at: datetime | None = None

IssuedToken

Bases: BaseModel

A newly created Personal Access Token. The secret is shown only once.

Source code in src/woodglue/auth_store.py
class IssuedToken(BaseModel):
    """A newly created Personal Access Token. The secret is shown only once."""

    id: str
    secret: str

AuthStore

Access to auth.db. roles maps Role names to their Grants, as returned by woodglue.access.resolve_roles.

Source code in src/woodglue/auth_store.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
class AuthStore:
    """
    Access to `auth.db`. `roles` maps Role names to their Grants, as returned
    by `woodglue.access.resolve_roles`.
    """

    db_path: Path
    roles: dict[str, tuple[Grant, ...]]
    session_idle: timedelta
    session_max: timedelta
    clock: Callable[[], datetime]

    def __init__(
        self,
        db_path: Path,
        roles: dict[str, tuple[Grant, ...]],
        *,
        session_idle: timedelta = DEFAULT_SESSION_IDLE,
        session_max: timedelta = DEFAULT_SESSION_MAX,
        clock: Callable[[], datetime] = _now,
    ) -> None:
        self.db_path = db_path
        self.roles = roles
        self.session_idle = session_idle
        self.session_max = session_max
        self.clock = clock
        with self._connect() as conn:
            self._migrate(conn)

    @contextmanager
    def _connect(self) -> Generator[sqlite3.Connection, None, None]:
        with closing(sqlite3.connect(self.db_path)) as conn:
            conn.row_factory = sqlite3.Row
            conn.execute("PRAGMA foreign_keys = ON")
            yield conn
            conn.commit()

    def _migrate(self, conn: sqlite3.Connection) -> None:
        version = conn.execute("PRAGMA user_version").fetchone()[0]
        if version == 0:
            self._create_schema(conn)
            conn.execute(f"PRAGMA user_version = {_SCHEMA_VERSION}")
        elif version == 1:
            # One transaction with the version bump, so a crash cannot leave it half done.
            conn.executescript(
                """
                BEGIN;
                ALTER TABLE users ADD COLUMN status TEXT NOT NULL DEFAULT 'active';
                UPDATE users SET status = 'disabled' WHERE disabled;
                ALTER TABLE users DROP COLUMN disabled;
                PRAGMA user_version = 2;
                COMMIT;
                """
            )

    def _create_schema(self, conn: sqlite3.Connection) -> None:
        conn.executescript(
            """
            CREATE TABLE users (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT UNIQUE,
                kind TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'active',
                created_at TEXT NOT NULL
            );
            CREATE TABLE role_assignments (
                user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                role TEXT NOT NULL,
                source TEXT NOT NULL,
                PRIMARY KEY (user_id, role, source)
            );
            CREATE TABLE linked_identities (
                provider TEXT NOT NULL,
                subject TEXT NOT NULL,
                user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                created_at TEXT NOT NULL,
                PRIMARY KEY (provider, subject)
            );
            CREATE TABLE credentials (
                id TEXT PRIMARY KEY,
                secret TEXT NOT NULL UNIQUE,
                kind TEXT NOT NULL,
                user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
                name TEXT NOT NULL,
                grants TEXT,
                created_at TEXT NOT NULL,
                expires_at TEXT,
                last_used_at TEXT,
                parent_id TEXT REFERENCES credentials(id) ON DELETE CASCADE
            );
            """
        )
        self._ensure_admin_user(conn)
        # Before 0.0.9, auth.db held only a list of tokens, all with full access.
        has_legacy = conn.execute(
            "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tokens'"
        ).fetchone()
        if has_legacy:
            for row in conn.execute("SELECT token, created_at FROM tokens ORDER BY created_at"):
                conn.execute(
                    "INSERT INTO credentials (id, secret, kind, user_id, name, created_at) "
                    + "VALUES (?, ?, ?, ?, ?, ?)",
                    (
                        _new_id("tok"),
                        row["token"],
                        CredentialKind.token,
                        ADMIN_USER_ID,
                        "wgl token",
                        row["created_at"],
                    ),
                )
            conn.execute("DROP TABLE tokens")

    def _ensure_admin_user(self, conn: sqlite3.Connection) -> None:
        conn.execute(
            "INSERT OR IGNORE INTO users (id, name, kind, created_at) VALUES (?, ?, ?, ?)",
            (ADMIN_USER_ID, ADMIN_USER_ID, UserKind.service, self.clock().isoformat()),
        )
        conn.execute(
            "INSERT OR IGNORE INTO role_assignments (user_id, role, source) VALUES (?, ?, ?)",
            (ADMIN_USER_ID, ADMIN_ROLE, MANUAL),
        )

    # Users

    def _user_from_row(self, conn: sqlite3.Connection, row: sqlite3.Row) -> User:
        assignments = [
            RoleAssignment(role=r["role"], source=r["source"])
            for r in conn.execute(
                "SELECT role, source FROM role_assignments WHERE user_id = ? ORDER BY role, source",
                (row["id"],),
            )
        ]
        providers = [
            r["provider"]
            for r in conn.execute(
                "SELECT DISTINCT provider FROM linked_identities WHERE user_id = ? "
                + "ORDER BY provider",
                (row["id"],),
            )
        ]
        return User(
            id=row["id"],
            name=row["name"],
            email=row["email"],
            kind=UserKind(row["kind"]),
            status=UserStatus(row["status"]),
            roles=sorted({a.role for a in assignments}),
            role_assignments=assignments,
            providers=providers,
            builtin=row["id"] == ADMIN_USER_ID,
            created_at=datetime.fromisoformat(row["created_at"]),
        )

    def list_users(self) -> list[User]:
        with self._connect() as conn:
            rows = conn.execute("SELECT * FROM users ORDER BY created_at, id").fetchall()
            return [self._user_from_row(conn, r) for r in rows]

    def find_user(self, ref: str) -> User:
        """
        Look up a User by id, email, or name. A name matching several Users is
        ambiguous and raises `UnknownUser`.
        """
        with self._connect() as conn:
            rows = conn.execute(
                "SELECT * FROM users WHERE id = ? OR email = ?", (ref, ref)
            ).fetchall()
            if not rows:
                rows = conn.execute("SELECT * FROM users WHERE name = ?", (ref,)).fetchall()
            if len(rows) != 1:
                raise UnknownUser(f"No unique User matches {ref!r}")
            return self._user_from_row(conn, rows[0])

    def create_service_user(self, name: str) -> User:
        with self._connect() as conn:
            taken = conn.execute(
                "SELECT 1 FROM users WHERE name = ? OR id = ?", (name, name)
            ).fetchone()
            if taken:
                raise ValueError(f"A User named {name!r} already exists")
            user_id = _new_id("svc")
            conn.execute(
                "INSERT INTO users (id, name, kind, created_at) VALUES (?, ?, ?, ?)",
                (user_id, name, UserKind.service, self.clock().isoformat()),
            )
            row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
            return self._user_from_row(conn, row)

    def assign_role(self, user_id: str, role: str) -> None:
        if role not in self.roles:
            raise ValueError(f"Unknown Role {role!r}; defined: {', '.join(sorted(self.roles))}")
        with self._connect() as conn:
            self._require_user(conn, user_id)
            conn.execute(
                "INSERT OR IGNORE INTO role_assignments (user_id, role, source) VALUES (?, ?, ?)",
                (user_id, role, MANUAL),
            )

    def unassign_role(self, user_id: str, role: str) -> None:
        """Remove a Role from every source; a provider re-adds its own at the next sign-in."""
        if user_id == ADMIN_USER_ID and role == ADMIN_ROLE:
            raise ValueError("The built-in admin User cannot lose the 'admin' Role")
        with self._connect() as conn:
            self._require_user(conn, user_id)
            conn.execute(
                "DELETE FROM role_assignments WHERE user_id = ? AND role = ?", (user_id, role)
            )

    def approve_user(self, user_id: str, roles: Sequence[str] = ()) -> None:
        """
        Make a `pending` User `active`, assigning `roles` manually. Raises
        `ValueError` if the User is not pending, so that approving from a stale
        view fails visibly rather than doing nothing.
        """
        for role in roles:
            if role not in self.roles:
                raise ValueError(f"Unknown Role {role!r}; defined: {', '.join(sorted(self.roles))}")
        with self._connect() as conn:
            status = self._require_user(conn, user_id)
            if status != UserStatus.pending:
                raise ValueError(f"User {user_id} is {status}, not pending")
            conn.execute("UPDATE users SET status = ? WHERE id = ?", (UserStatus.active, user_id))
            for role in roles:
                conn.execute(
                    "INSERT OR IGNORE INTO role_assignments (user_id, role, source) "
                    + "VALUES (?, ?, ?)",
                    (user_id, role, MANUAL),
                )

    def set_disabled(self, user_id: str, disabled: bool) -> None:
        """
        Disable or re-enable a User. Disabling deletes all of its credentials
        and is also how a `pending` User is denied. Enabling makes the User
        `active`; a `pending` User must be approved instead.
        """
        if disabled and user_id == ADMIN_USER_ID:
            raise ValueError("The built-in admin User cannot be disabled")
        with self._connect() as conn:
            current = self._require_user(conn, user_id)
            if not disabled and current == UserStatus.pending:
                raise ValueError(f"User {user_id} is pending; approve it instead")
            status = UserStatus.disabled if disabled else UserStatus.active
            conn.execute("UPDATE users SET status = ? WHERE id = ?", (status, user_id))
            if disabled:
                conn.execute("DELETE FROM credentials WHERE user_id = ?", (user_id,))

    def delete_user(self, user_id: str) -> None:
        """
        Erase a User. `ON DELETE CASCADE` removes its Role assignments, Linked
        Identities, and credentials, including Delegated Tokens.
        """
        if user_id == ADMIN_USER_ID:
            raise ValueError("The built-in admin User cannot be deleted")
        with self._connect() as conn:
            self._require_user(conn, user_id)
            conn.execute("DELETE FROM users WHERE id = ?", (user_id,))

    def linked_user(self, provider: str, subject: str) -> str | None:
        """The id of the User linked to an Identity Provider's subject, if any."""
        with self._connect() as conn:
            row = conn.execute(
                "SELECT user_id FROM linked_identities WHERE provider = ? AND subject = ?",
                (provider, subject),
            ).fetchone()
        return row["user_id"] if row else None

    def sign_in_person(
        self,
        provider: str,
        subject: str,
        *,
        email: str | None,
        email_verified: bool,
        name: str,
        role_sources: dict[str, list[str]],
        admit_as: UserStatus = UserStatus.active,
        activate_pending: bool = False,
    ) -> User:
        """
        Find or create the User for an Identity Provider's assertion, after the
        caller has decided the person is admitted.

        The User is found by its Linked Identity, else by a verified email
        matching an existing User (linking the identity to it), else created.
        An unverified email is not stored, so it can never take over an account.
        Each entry of `role_sources` replaces that source's Role assignments,
        leaving assignments from other sources (and manual ones) alone.

        `admit_as` is the status of a User this creates, `active` or `pending`;
        an existing User keeps its status, except that `activate_pending`
        (set for configured admins) makes a `pending` User `active`.

        Raises `UserDisabled` if the User is disabled.
        """
        verified_email = email.lower() if email and email_verified else None
        with self._connect() as conn:
            row = conn.execute(
                "SELECT u.* FROM linked_identities l JOIN users u ON u.id = l.user_id "
                + "WHERE l.provider = ? AND l.subject = ?",
                (provider, subject),
            ).fetchone()
            if row is None and verified_email is not None:
                row = conn.execute(
                    "SELECT * FROM users WHERE email = ? AND kind = ?",
                    (verified_email, UserKind.person),
                ).fetchone()
            now = self.clock().isoformat()
            created = False
            if row is None:
                user_id = _new_id("usr")
                conn.execute(
                    "INSERT INTO users (id, name, email, kind, status, created_at) "
                    + "VALUES (?, ?, ?, ?, ?, ?)",
                    (user_id, name, verified_email, UserKind.person, admit_as, now),
                )
                created = True
            else:
                user_id = row["id"]
                if row["status"] == UserStatus.disabled:
                    raise UserDisabled(f"User {user_id} is disabled")
                conn.execute("UPDATE users SET name = ? WHERE id = ?", (name, user_id))
                if activate_pending and row["status"] == UserStatus.pending:
                    conn.execute(
                        "UPDATE users SET status = ? WHERE id = ?", (UserStatus.active, user_id)
                    )
                if verified_email and row["email"] != verified_email:
                    taken = conn.execute(
                        "SELECT 1 FROM users WHERE email = ?", (verified_email,)
                    ).fetchone()
                    if not taken:
                        conn.execute(
                            "UPDATE users SET email = ? WHERE id = ?", (verified_email, user_id)
                        )
            conn.execute(
                "INSERT OR IGNORE INTO linked_identities (provider, subject, user_id, created_at) "
                + "VALUES (?, ?, ?, ?)",
                (provider, subject, user_id, now),
            )
            for source, roles in role_sources.items():
                conn.execute(
                    "DELETE FROM role_assignments WHERE user_id = ? AND source = ?",
                    (user_id, source),
                )
                for role in roles:
                    if role not in self.roles:
                        logger.warning("Sign-in source %s names undefined Role %r", source, role)
                        continue
                    conn.execute(
                        "INSERT OR IGNORE INTO role_assignments (user_id, role, source) "
                        + "VALUES (?, ?, ?)",
                        (user_id, role, source),
                    )
            user_row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
            user = self._user_from_row(conn, user_row)
        # Logged only once committed. No email: log lines cannot be erased with the User.
        if created and user.status == UserStatus.pending:
            logger.info("New pending User %s via %s", user.id, provider)
        return user

    def _require_user(self, conn: sqlite3.Connection, user_id: str) -> UserStatus:
        """The User's status; raises `UnknownUser` if there is no such User."""
        row = conn.execute("SELECT status FROM users WHERE id = ?", (user_id,)).fetchone()
        if row is None:
            raise UnknownUser(f"No User with id {user_id!r}")
        return UserStatus(row["status"])

    # Personal Access Tokens

    def create_token(
        self,
        user_id: str,
        name: str,
        *,
        expires_at: datetime | None = None,
        grants: list[str] | None = None,
    ) -> IssuedToken:
        """
        Issue a Personal Access Token. `grants`, if given, narrows the token to
        a subset of its User's Grants; they are validated but not checked
        against the User, since the effective set is computed per request.

        Raises `UserPending` or `UserDisabled` unless the User is `active`. The
        check is here, not only at each route, because a request approved
        earlier (such as a CLI code) can be redeemed after the status changed.
        """
        if grants is not None:
            grants = [str(Grant.parse(g)) for g in grants]
        with self._connect() as conn:
            status = self._require_user(conn, user_id)
            if status == UserStatus.pending:
                raise UserPending(f"User {user_id} is pending approval")
            if status == UserStatus.disabled:
                raise UserDisabled(f"User {user_id} is disabled")
            return self._insert_token(conn, user_id, name, expires_at, grants)

    def _insert_token(
        self,
        conn: sqlite3.Connection,
        user_id: str,
        name: str,
        expires_at: datetime | None = None,
        grants: list[str] | None = None,
    ) -> IssuedToken:
        issued = IssuedToken(id=_new_id("tok"), secret=secrets.token_urlsafe(32))
        conn.execute(
            "INSERT INTO credentials "
            + "(id, secret, kind, user_id, name, grants, created_at, expires_at) "
            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (
                issued.id,
                issued.secret,
                CredentialKind.token,
                user_id,
                name,
                json.dumps(grants) if grants is not None else None,
                self.clock().isoformat(),
                expires_at.isoformat() if expires_at else None,
            ),
        )
        return issued

    def list_tokens(self, user_id: str | None = None) -> list[TokenInfo]:
        query = "SELECT * FROM credentials WHERE kind = ?"
        params: list[str] = [CredentialKind.token]
        if user_id is not None:
            query += " AND user_id = ?"
            params.append(user_id)
        with self._connect() as conn:
            rows = conn.execute(query + " ORDER BY created_at, id", params).fetchall()
        return [
            TokenInfo(
                id=r["id"],
                user_id=r["user_id"],
                name=r["name"],
                grants=json.loads(r["grants"]) if r["grants"] else None,
                created_at=datetime.fromisoformat(r["created_at"]),
                expires_at=_parse_time(r["expires_at"]),
            )
            for r in rows
        ]

    def token_owner(self, token_id: str) -> str | None:
        with self._connect() as conn:
            row = conn.execute(
                "SELECT user_id FROM credentials WHERE id = ? AND kind = ?",
                (token_id, CredentialKind.token),
            ).fetchone()
        return row["user_id"] if row else None

    def revoke_token(self, token_id: str) -> bool:
        with self._connect() as conn:
            cur = conn.execute(
                "DELETE FROM credentials WHERE id = ? AND kind = ?",
                (token_id, CredentialKind.token),
            )
            return cur.rowcount > 0

    def ensure_admin_token(self) -> None:
        """Create a token for the built-in admin User if it has none."""
        with self._connect() as conn:
            if not self._admin_secrets(conn):
                self._insert_token(conn, ADMIN_USER_ID, "wgl token")

    def admin_tokens(self) -> list[str]:
        """Secrets of the admin User's tokens, oldest first."""
        with self._connect() as conn:
            return self._admin_secrets(conn)

    def _admin_secrets(self, conn: sqlite3.Connection) -> list[str]:
        rows = conn.execute(
            "SELECT secret FROM credentials WHERE user_id = ? AND kind = ? "
            + "ORDER BY created_at, id",
            (ADMIN_USER_ID, CredentialKind.token),
        ).fetchall()
        return [r["secret"] for r in rows]

    def rotate_admin_token(self) -> str:
        """
        Replace all admin tokens with one new one, in one transaction, so a
        concurrent `resolve` never sees the admin without a token.
        """
        with self._connect() as conn:
            conn.execute(
                "DELETE FROM credentials WHERE user_id = ? AND kind = ?",
                (ADMIN_USER_ID, CredentialKind.token),
            )
            return self._insert_token(conn, ADMIN_USER_ID, "wgl token").secret

    # Sessions

    def live_session(self, user_id: str, name: str) -> str | None:
        """The secret of a live Session of `user_id` started under `name`, if any."""
        with self._connect() as conn:
            rows = conn.execute(
                "SELECT secret FROM credentials WHERE user_id = ? AND kind = ? AND name = ? "
                + "ORDER BY created_at DESC",
                (user_id, CredentialKind.session, name),
            ).fetchall()
        return next((r["secret"] for r in rows if self.session_is_live(r["secret"])), None)

    def create_session(self, user_id: str, name: str = "browser") -> str:
        """
        Start a Session for a User and return its secret, for the browser
        cookie. `name` records how it was started.
        """
        now = self.clock()
        secret = secrets.token_urlsafe(32)
        with self._connect() as conn:
            self._require_user(conn, user_id)
            conn.execute(
                "INSERT INTO credentials "
                + "(id, secret, kind, user_id, name, created_at, expires_at, last_used_at) "
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    _new_id("ses"),
                    secret,
                    CredentialKind.session,
                    user_id,
                    name,
                    now.isoformat(),
                    (now + self.session_max).isoformat(),
                    now.isoformat(),
                ),
            )
        return secret

    def delegate(self, session_secret: str, ui_name: str, grants: list[str] | None = None) -> str:
        """
        The Delegated Token for a UI acting on behalf of a Session, created on
        first use. `grants`, the UI's configured Grants, narrows it like a
        narrowed Personal Access Token, and is updated on each call so a config
        change applies at once. Raises `ValueError` unless `session_secret` is
        a live Session.
        """
        grants_json = (
            json.dumps([str(Grant.parse(g)) for g in grants]) if grants is not None else None
        )
        with self._connect() as conn:
            row = conn.execute(
                "SELECT * FROM credentials WHERE secret = ? AND kind = ?",
                (session_secret, CredentialKind.session),
            ).fetchone()
            if row is None or not self._session_alive(conn, row, self.clock()):
                raise ValueError("Only a live Session can be delegated")
            existing = conn.execute(
                "SELECT secret FROM credentials WHERE parent_id = ? AND kind = ? AND name = ?",
                (row["id"], CredentialKind.delegated, ui_name),
            ).fetchone()
            if existing is not None:
                conn.execute(
                    "UPDATE credentials SET grants = ? WHERE secret = ?",
                    (grants_json, existing["secret"]),
                )
                return existing["secret"]
            secret = secrets.token_urlsafe(32)
            conn.execute(
                "INSERT INTO credentials "
                + "(id, secret, kind, user_id, name, grants, created_at, parent_id) "
                + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    _new_id("dlg"),
                    secret,
                    CredentialKind.delegated,
                    row["user_id"],
                    ui_name,
                    grants_json,
                    self.clock().isoformat(),
                    row["id"],
                ),
            )
            return secret

    def _session_alive(
        self, conn: sqlite3.Connection, row: sqlite3.Row, now: datetime, *, use: bool = True
    ) -> bool:
        """
        Apply a Session's limits, deleting it (and its Delegated Tokens) once it
        has expired, and with `use`, record that it was used.
        """
        expires_at = _parse_time(row["expires_at"])
        last_used = _parse_time(row["last_used_at"]) or now
        if (expires_at is not None and expires_at <= now) or last_used + self.session_idle <= now:
            conn.execute("DELETE FROM credentials WHERE id = ?", (row["id"],))
            return False
        if use and now - last_used >= _TOUCH_INTERVAL:
            conn.execute(
                "UPDATE credentials SET last_used_at = ? WHERE id = ?",
                (now.isoformat(), row["id"]),
            )
        return True

    def session_is_live(self, secret: str) -> bool:
        """Whether a Session is still valid, without counting this check as use."""
        now = self.clock()
        with self._connect() as conn:
            row = conn.execute(
                "SELECT c.expires_at, c.last_used_at, u.status FROM credentials c "
                + "JOIN users u ON u.id = c.user_id WHERE c.secret = ? AND c.kind = ?",
                (secret, CredentialKind.session),
            ).fetchone()
        if row is None or row["status"] == UserStatus.disabled:
            return False
        expires_at = _parse_time(row["expires_at"])
        last_used = _parse_time(row["last_used_at"]) or now
        return (expires_at is None or expires_at > now) and last_used + self.session_idle > now

    def end_session(self, secret: str) -> None:
        with self._connect() as conn:
            conn.execute(
                "DELETE FROM credentials WHERE secret = ? AND kind = ?",
                (secret, CredentialKind.session),
            )

    # Authentication

    def resolve(self, secret: str) -> Caller | None:
        """
        Return the Caller for a credential secret, or `None` if it is not valid
        now. Resolving a Session counts as using it; resolving one of its
        Delegated Tokens does not.
        """
        now = self.clock()
        with self._connect() as conn:
            row = conn.execute(
                "SELECT c.id AS cid, c.kind AS ckind, c.grants, c.expires_at, c.parent_id, "
                + "u.* FROM credentials c JOIN users u ON u.id = c.user_id WHERE c.secret = ?",
                (secret,),
            ).fetchone()
            if row is None or row["status"] == UserStatus.disabled:
                return None
            expires_at = _parse_time(row["expires_at"])
            if expires_at is not None and expires_at <= now:
                return None
            if row["ckind"] in (CredentialKind.session, CredentialKind.delegated):
                session_id = (
                    row["parent_id"] if row["ckind"] == CredentialKind.delegated else row["cid"]
                )
                session = conn.execute(
                    "SELECT * FROM credentials WHERE id = ?", (session_id,)
                ).fetchone()
                # A UI calling the API on its own is not the person using the Session.
                used = row["ckind"] == CredentialKind.session
                if session is None or not self._session_alive(conn, session, now, use=used):
                    return None
            user = self._user_from_row(conn, row)
        return self._caller(user, row["cid"], row["ckind"], row["grants"])

    def _caller(
        self, user: User, credential_id: str, credential_kind: str, token_grants: str | None
    ) -> Caller:
        user_grants: list[Grant] = []
        # A pending User's Roles keep syncing at sign-in but grant nothing until approval.
        for role in user.roles if user.status != UserStatus.pending else ():
            grants = self.roles.get(role)
            if grants is None:
                logger.warning("User %s has undefined Role %r; it grants nothing", user.id, role)
                continue
            user_grants.extend(grants)
        grant_sets = [tuple(user_grants)]
        if token_grants is not None:
            grant_sets.append(tuple(Grant.parse(g) for g in json.loads(token_grants)))
        return Caller(
            user_id=user.id,
            grant_sets=tuple(grant_sets),
            credential_id=credential_id,
            credential_kind=credential_kind,
            name=user.name,
            email=user.email,
            roles=tuple(user.roles),
            pending=user.status == UserStatus.pending,
        )

find_user(ref)

Look up a User by id, email, or name. A name matching several Users is ambiguous and raises UnknownUser.

Source code in src/woodglue/auth_store.py
def find_user(self, ref: str) -> User:
    """
    Look up a User by id, email, or name. A name matching several Users is
    ambiguous and raises `UnknownUser`.
    """
    with self._connect() as conn:
        rows = conn.execute(
            "SELECT * FROM users WHERE id = ? OR email = ?", (ref, ref)
        ).fetchall()
        if not rows:
            rows = conn.execute("SELECT * FROM users WHERE name = ?", (ref,)).fetchall()
        if len(rows) != 1:
            raise UnknownUser(f"No unique User matches {ref!r}")
        return self._user_from_row(conn, rows[0])

unassign_role(user_id, role)

Remove a Role from every source; a provider re-adds its own at the next sign-in.

Source code in src/woodglue/auth_store.py
def unassign_role(self, user_id: str, role: str) -> None:
    """Remove a Role from every source; a provider re-adds its own at the next sign-in."""
    if user_id == ADMIN_USER_ID and role == ADMIN_ROLE:
        raise ValueError("The built-in admin User cannot lose the 'admin' Role")
    with self._connect() as conn:
        self._require_user(conn, user_id)
        conn.execute(
            "DELETE FROM role_assignments WHERE user_id = ? AND role = ?", (user_id, role)
        )

approve_user(user_id, roles=())

Make a pending User active, assigning roles manually. Raises ValueError if the User is not pending, so that approving from a stale view fails visibly rather than doing nothing.

Source code in src/woodglue/auth_store.py
def approve_user(self, user_id: str, roles: Sequence[str] = ()) -> None:
    """
    Make a `pending` User `active`, assigning `roles` manually. Raises
    `ValueError` if the User is not pending, so that approving from a stale
    view fails visibly rather than doing nothing.
    """
    for role in roles:
        if role not in self.roles:
            raise ValueError(f"Unknown Role {role!r}; defined: {', '.join(sorted(self.roles))}")
    with self._connect() as conn:
        status = self._require_user(conn, user_id)
        if status != UserStatus.pending:
            raise ValueError(f"User {user_id} is {status}, not pending")
        conn.execute("UPDATE users SET status = ? WHERE id = ?", (UserStatus.active, user_id))
        for role in roles:
            conn.execute(
                "INSERT OR IGNORE INTO role_assignments (user_id, role, source) "
                + "VALUES (?, ?, ?)",
                (user_id, role, MANUAL),
            )

set_disabled(user_id, disabled)

Disable or re-enable a User. Disabling deletes all of its credentials and is also how a pending User is denied. Enabling makes the User active; a pending User must be approved instead.

Source code in src/woodglue/auth_store.py
def set_disabled(self, user_id: str, disabled: bool) -> None:
    """
    Disable or re-enable a User. Disabling deletes all of its credentials
    and is also how a `pending` User is denied. Enabling makes the User
    `active`; a `pending` User must be approved instead.
    """
    if disabled and user_id == ADMIN_USER_ID:
        raise ValueError("The built-in admin User cannot be disabled")
    with self._connect() as conn:
        current = self._require_user(conn, user_id)
        if not disabled and current == UserStatus.pending:
            raise ValueError(f"User {user_id} is pending; approve it instead")
        status = UserStatus.disabled if disabled else UserStatus.active
        conn.execute("UPDATE users SET status = ? WHERE id = ?", (status, user_id))
        if disabled:
            conn.execute("DELETE FROM credentials WHERE user_id = ?", (user_id,))

delete_user(user_id)

Erase a User. ON DELETE CASCADE removes its Role assignments, Linked Identities, and credentials, including Delegated Tokens.

Source code in src/woodglue/auth_store.py
def delete_user(self, user_id: str) -> None:
    """
    Erase a User. `ON DELETE CASCADE` removes its Role assignments, Linked
    Identities, and credentials, including Delegated Tokens.
    """
    if user_id == ADMIN_USER_ID:
        raise ValueError("The built-in admin User cannot be deleted")
    with self._connect() as conn:
        self._require_user(conn, user_id)
        conn.execute("DELETE FROM users WHERE id = ?", (user_id,))

linked_user(provider, subject)

The id of the User linked to an Identity Provider's subject, if any.

Source code in src/woodglue/auth_store.py
def linked_user(self, provider: str, subject: str) -> str | None:
    """The id of the User linked to an Identity Provider's subject, if any."""
    with self._connect() as conn:
        row = conn.execute(
            "SELECT user_id FROM linked_identities WHERE provider = ? AND subject = ?",
            (provider, subject),
        ).fetchone()
    return row["user_id"] if row else None

sign_in_person(provider, subject, *, email, email_verified, name, role_sources, admit_as=UserStatus.active, activate_pending=False)

Find or create the User for an Identity Provider's assertion, after the caller has decided the person is admitted.

The User is found by its Linked Identity, else by a verified email matching an existing User (linking the identity to it), else created. An unverified email is not stored, so it can never take over an account. Each entry of role_sources replaces that source's Role assignments, leaving assignments from other sources (and manual ones) alone.

admit_as is the status of a User this creates, active or pending; an existing User keeps its status, except that activate_pending (set for configured admins) makes a pending User active.

Raises UserDisabled if the User is disabled.

Source code in src/woodglue/auth_store.py
def sign_in_person(
    self,
    provider: str,
    subject: str,
    *,
    email: str | None,
    email_verified: bool,
    name: str,
    role_sources: dict[str, list[str]],
    admit_as: UserStatus = UserStatus.active,
    activate_pending: bool = False,
) -> User:
    """
    Find or create the User for an Identity Provider's assertion, after the
    caller has decided the person is admitted.

    The User is found by its Linked Identity, else by a verified email
    matching an existing User (linking the identity to it), else created.
    An unverified email is not stored, so it can never take over an account.
    Each entry of `role_sources` replaces that source's Role assignments,
    leaving assignments from other sources (and manual ones) alone.

    `admit_as` is the status of a User this creates, `active` or `pending`;
    an existing User keeps its status, except that `activate_pending`
    (set for configured admins) makes a `pending` User `active`.

    Raises `UserDisabled` if the User is disabled.
    """
    verified_email = email.lower() if email and email_verified else None
    with self._connect() as conn:
        row = conn.execute(
            "SELECT u.* FROM linked_identities l JOIN users u ON u.id = l.user_id "
            + "WHERE l.provider = ? AND l.subject = ?",
            (provider, subject),
        ).fetchone()
        if row is None and verified_email is not None:
            row = conn.execute(
                "SELECT * FROM users WHERE email = ? AND kind = ?",
                (verified_email, UserKind.person),
            ).fetchone()
        now = self.clock().isoformat()
        created = False
        if row is None:
            user_id = _new_id("usr")
            conn.execute(
                "INSERT INTO users (id, name, email, kind, status, created_at) "
                + "VALUES (?, ?, ?, ?, ?, ?)",
                (user_id, name, verified_email, UserKind.person, admit_as, now),
            )
            created = True
        else:
            user_id = row["id"]
            if row["status"] == UserStatus.disabled:
                raise UserDisabled(f"User {user_id} is disabled")
            conn.execute("UPDATE users SET name = ? WHERE id = ?", (name, user_id))
            if activate_pending and row["status"] == UserStatus.pending:
                conn.execute(
                    "UPDATE users SET status = ? WHERE id = ?", (UserStatus.active, user_id)
                )
            if verified_email and row["email"] != verified_email:
                taken = conn.execute(
                    "SELECT 1 FROM users WHERE email = ?", (verified_email,)
                ).fetchone()
                if not taken:
                    conn.execute(
                        "UPDATE users SET email = ? WHERE id = ?", (verified_email, user_id)
                    )
        conn.execute(
            "INSERT OR IGNORE INTO linked_identities (provider, subject, user_id, created_at) "
            + "VALUES (?, ?, ?, ?)",
            (provider, subject, user_id, now),
        )
        for source, roles in role_sources.items():
            conn.execute(
                "DELETE FROM role_assignments WHERE user_id = ? AND source = ?",
                (user_id, source),
            )
            for role in roles:
                if role not in self.roles:
                    logger.warning("Sign-in source %s names undefined Role %r", source, role)
                    continue
                conn.execute(
                    "INSERT OR IGNORE INTO role_assignments (user_id, role, source) "
                    + "VALUES (?, ?, ?)",
                    (user_id, role, source),
                )
        user_row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
        user = self._user_from_row(conn, user_row)
    # Logged only once committed. No email: log lines cannot be erased with the User.
    if created and user.status == UserStatus.pending:
        logger.info("New pending User %s via %s", user.id, provider)
    return user

create_token(user_id, name, *, expires_at=None, grants=None)

Issue a Personal Access Token. grants, if given, narrows the token to a subset of its User's Grants; they are validated but not checked against the User, since the effective set is computed per request.

Raises UserPending or UserDisabled unless the User is active. The check is here, not only at each route, because a request approved earlier (such as a CLI code) can be redeemed after the status changed.

Source code in src/woodglue/auth_store.py
def create_token(
    self,
    user_id: str,
    name: str,
    *,
    expires_at: datetime | None = None,
    grants: list[str] | None = None,
) -> IssuedToken:
    """
    Issue a Personal Access Token. `grants`, if given, narrows the token to
    a subset of its User's Grants; they are validated but not checked
    against the User, since the effective set is computed per request.

    Raises `UserPending` or `UserDisabled` unless the User is `active`. The
    check is here, not only at each route, because a request approved
    earlier (such as a CLI code) can be redeemed after the status changed.
    """
    if grants is not None:
        grants = [str(Grant.parse(g)) for g in grants]
    with self._connect() as conn:
        status = self._require_user(conn, user_id)
        if status == UserStatus.pending:
            raise UserPending(f"User {user_id} is pending approval")
        if status == UserStatus.disabled:
            raise UserDisabled(f"User {user_id} is disabled")
        return self._insert_token(conn, user_id, name, expires_at, grants)

ensure_admin_token()

Create a token for the built-in admin User if it has none.

Source code in src/woodglue/auth_store.py
def ensure_admin_token(self) -> None:
    """Create a token for the built-in admin User if it has none."""
    with self._connect() as conn:
        if not self._admin_secrets(conn):
            self._insert_token(conn, ADMIN_USER_ID, "wgl token")

admin_tokens()

Secrets of the admin User's tokens, oldest first.

Source code in src/woodglue/auth_store.py
def admin_tokens(self) -> list[str]:
    """Secrets of the admin User's tokens, oldest first."""
    with self._connect() as conn:
        return self._admin_secrets(conn)

rotate_admin_token()

Replace all admin tokens with one new one, in one transaction, so a concurrent resolve never sees the admin without a token.

Source code in src/woodglue/auth_store.py
def rotate_admin_token(self) -> str:
    """
    Replace all admin tokens with one new one, in one transaction, so a
    concurrent `resolve` never sees the admin without a token.
    """
    with self._connect() as conn:
        conn.execute(
            "DELETE FROM credentials WHERE user_id = ? AND kind = ?",
            (ADMIN_USER_ID, CredentialKind.token),
        )
        return self._insert_token(conn, ADMIN_USER_ID, "wgl token").secret

live_session(user_id, name)

The secret of a live Session of user_id started under name, if any.

Source code in src/woodglue/auth_store.py
def live_session(self, user_id: str, name: str) -> str | None:
    """The secret of a live Session of `user_id` started under `name`, if any."""
    with self._connect() as conn:
        rows = conn.execute(
            "SELECT secret FROM credentials WHERE user_id = ? AND kind = ? AND name = ? "
            + "ORDER BY created_at DESC",
            (user_id, CredentialKind.session, name),
        ).fetchall()
    return next((r["secret"] for r in rows if self.session_is_live(r["secret"])), None)

create_session(user_id, name='browser')

Start a Session for a User and return its secret, for the browser cookie. name records how it was started.

Source code in src/woodglue/auth_store.py
def create_session(self, user_id: str, name: str = "browser") -> str:
    """
    Start a Session for a User and return its secret, for the browser
    cookie. `name` records how it was started.
    """
    now = self.clock()
    secret = secrets.token_urlsafe(32)
    with self._connect() as conn:
        self._require_user(conn, user_id)
        conn.execute(
            "INSERT INTO credentials "
            + "(id, secret, kind, user_id, name, created_at, expires_at, last_used_at) "
            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (
                _new_id("ses"),
                secret,
                CredentialKind.session,
                user_id,
                name,
                now.isoformat(),
                (now + self.session_max).isoformat(),
                now.isoformat(),
            ),
        )
    return secret

delegate(session_secret, ui_name, grants=None)

The Delegated Token for a UI acting on behalf of a Session, created on first use. grants, the UI's configured Grants, narrows it like a narrowed Personal Access Token, and is updated on each call so a config change applies at once. Raises ValueError unless session_secret is a live Session.

Source code in src/woodglue/auth_store.py
def delegate(self, session_secret: str, ui_name: str, grants: list[str] | None = None) -> str:
    """
    The Delegated Token for a UI acting on behalf of a Session, created on
    first use. `grants`, the UI's configured Grants, narrows it like a
    narrowed Personal Access Token, and is updated on each call so a config
    change applies at once. Raises `ValueError` unless `session_secret` is
    a live Session.
    """
    grants_json = (
        json.dumps([str(Grant.parse(g)) for g in grants]) if grants is not None else None
    )
    with self._connect() as conn:
        row = conn.execute(
            "SELECT * FROM credentials WHERE secret = ? AND kind = ?",
            (session_secret, CredentialKind.session),
        ).fetchone()
        if row is None or not self._session_alive(conn, row, self.clock()):
            raise ValueError("Only a live Session can be delegated")
        existing = conn.execute(
            "SELECT secret FROM credentials WHERE parent_id = ? AND kind = ? AND name = ?",
            (row["id"], CredentialKind.delegated, ui_name),
        ).fetchone()
        if existing is not None:
            conn.execute(
                "UPDATE credentials SET grants = ? WHERE secret = ?",
                (grants_json, existing["secret"]),
            )
            return existing["secret"]
        secret = secrets.token_urlsafe(32)
        conn.execute(
            "INSERT INTO credentials "
            + "(id, secret, kind, user_id, name, grants, created_at, parent_id) "
            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (
                _new_id("dlg"),
                secret,
                CredentialKind.delegated,
                row["user_id"],
                ui_name,
                grants_json,
                self.clock().isoformat(),
                row["id"],
            ),
        )
        return secret

session_is_live(secret)

Whether a Session is still valid, without counting this check as use.

Source code in src/woodglue/auth_store.py
def session_is_live(self, secret: str) -> bool:
    """Whether a Session is still valid, without counting this check as use."""
    now = self.clock()
    with self._connect() as conn:
        row = conn.execute(
            "SELECT c.expires_at, c.last_used_at, u.status FROM credentials c "
            + "JOIN users u ON u.id = c.user_id WHERE c.secret = ? AND c.kind = ?",
            (secret, CredentialKind.session),
        ).fetchone()
    if row is None or row["status"] == UserStatus.disabled:
        return False
    expires_at = _parse_time(row["expires_at"])
    last_used = _parse_time(row["last_used_at"]) or now
    return (expires_at is None or expires_at > now) and last_used + self.session_idle > now

resolve(secret)

Return the Caller for a credential secret, or None if it is not valid now. Resolving a Session counts as using it; resolving one of its Delegated Tokens does not.

Source code in src/woodglue/auth_store.py
def resolve(self, secret: str) -> Caller | None:
    """
    Return the Caller for a credential secret, or `None` if it is not valid
    now. Resolving a Session counts as using it; resolving one of its
    Delegated Tokens does not.
    """
    now = self.clock()
    with self._connect() as conn:
        row = conn.execute(
            "SELECT c.id AS cid, c.kind AS ckind, c.grants, c.expires_at, c.parent_id, "
            + "u.* FROM credentials c JOIN users u ON u.id = c.user_id WHERE c.secret = ?",
            (secret,),
        ).fetchone()
        if row is None or row["status"] == UserStatus.disabled:
            return None
        expires_at = _parse_time(row["expires_at"])
        if expires_at is not None and expires_at <= now:
            return None
        if row["ckind"] in (CredentialKind.session, CredentialKind.delegated):
            session_id = (
                row["parent_id"] if row["ckind"] == CredentialKind.delegated else row["cid"]
            )
            session = conn.execute(
                "SELECT * FROM credentials WHERE id = ?", (session_id,)
            ).fetchone()
            # A UI calling the API on its own is not the person using the Session.
            used = row["ckind"] == CredentialKind.session
            if session is None or not self._session_alive(conn, session, now, use=used):
                return None
        user = self._user_from_row(conn, row)
    return self._caller(user, row["cid"], row["ckind"], row["grants"])