Skip to content

Users and accounts

octomate.managers.user

The cross-channel user registry: users, the channel profiles they own, and profile linking.

PROFILE_FIELDS module-attribute

PROFILE_FIELDS = {
    "name",
    "nickname",
    "gender",
    "age",
    "title",
}

LinkProfileUnavailable

Bases: RuntimeError

Profile linking cannot start: local auth or the callback origin is not configured.

Source code in octomate/managers/user.py
class LinkProfileUnavailable(RuntimeError):
    """Profile linking cannot start: local auth or the callback origin is not
    configured."""

InvalidLinkProfile

Bases: ValueError

A profile-link ticket that is invalid, expired or already used.

Source code in octomate/managers/user.py
class InvalidLinkProfile(ValueError):
    """A profile-link ticket that is invalid, expired or already used."""

    def __init__(self) -> None:
        super().__init__("This profile link is invalid, expired, or already used")

ProfileAlreadyLinked

Bases: ValueError

The channel profile is already linked to an account.

Source code in octomate/managers/user.py
class ProfileAlreadyLinked(ValueError):
    """The channel profile is already linked to an account."""

    def __init__(self) -> None:
        super().__init__("This channel profile is already linked")

ProfileNotLinked

Bases: ValueError

The profile is not linked to the requesting account.

Source code in octomate/managers/user.py
class ProfileNotLinked(ValueError):
    """The profile is not linked to the requesting account."""

    def __init__(self) -> None:
        super().__init__("This profile is not linked to your account")

UserManager

Bases: Manager, Locks[tuple[str, str] | UUID7]

The persisted cross-channel user registry and verified profile links.

Source code in octomate/managers/user.py
class UserManager(Manager, Locks[tuple[str, str] | UUID7]):
    """The persisted cross-channel user registry and verified profile links."""

    def __init__(
        self,
        *,
        authorization_base_uri: AnyHttpUrl | None = None,
        authorization_lifetime: timedelta = timedelta(minutes=10),
    ) -> None:
        self.authorization_base_uri = authorization_base_uri
        self.authorization_lifetime = authorization_lifetime

    async def get(self, user_id: UUID7) -> User | None:
        async with async_session() as session:
            return await session.get(User, user_id)

    async def unlink_profile(self, user: User, profile_id: UUID7) -> None:
        async with self.lock(profile_id), async_session() as session:
            profile = await session.get(UserProfile, profile_id)
            if profile is None or profile.user_id != user.id:
                raise ProfileNotLinked
            profile.user_id = None
            pending = await session.one_or_none(
                LinkProfileSession,
                expressions=[LinkProfileSession["profile_id"] == profile_id],
            )
            if pending is not None:
                pending.consumed_at = datetime.now(UTC)
            await session.commit()

    async def owner(self, profile: UserProfile) -> User | None:
        """Return the registered owner of ``profile``, or ``None`` for a visitor."""
        user_id = profile.user_id
        if user_id is None:
            return None
        async with async_session() as session:
            user = await session.get(User, user_id)
        if user is None:
            raise ValueError(f"unknown user {user_id}")
        return user

    async def linked_profiles(
        self,
        profile: UserProfile,
    ) -> list[UserProfile]:
        """This human's other channel identities — the same person on another
        platform, reachable precisely because the registry links the accounts.

        Empty for a visitor: only a registered `User` links identities, so an
        unregistered account is one account and can be followed nowhere. `owner`
        answers "whose is this"; this answers "where else are they".
        """
        user = await self.owner(profile)
        if user is None:
            return []
        async with async_session() as session:
            return list(
                await session.list(
                    UserProfile,
                    limit=None,
                    expressions=[
                        UserProfile["user_id"] == user.id,
                        UserProfile["channel_tentacle_id"]
                        != profile.channel_tentacle_id,
                    ],
                )
            )

    async def native_profile(self, runtime: str, username: str) -> UserProfile | None:
        """A transient anchor for `username`'s native session on `runtime`'s
        pseudo-channel, or None for an unknown username.

        Never persisted: a native session's identity comes from its verified
        bearer, not from a claimed row, so the profile exists only to give the
        linked-profile walk its starting point — owned like a stored profile,
        and standing on a channel id no channel ever resolves.
        """
        async with async_session() as session:
            user = await session.one_or_none(
                User, expressions=[User["username"] == username]
            )
        if user is None:
            return None
        return UserProfile(
            channel_tentacle_id=runtime,
            channel_user_id=username,
            user_id=user.id,
            user=Relation(user),
            name=user.name,
            nickname=user.nickname,
        )

    async def profile(
        self, channel_tentacle_id: str, channel_user_id: str
    ) -> UserProfile | None:
        """The stored profile for a channel identity, or ``None`` if never observed.

        The read-only sibling of ``ensure_profile``, for callers that hold only a
        channel identity — e.g. a deferred batch resuming long after the message
        that carried the sender's profile snapshot."""
        async with async_session() as session:
            return await session.one_or_none(
                UserProfile,
                expressions=[
                    UserProfile["channel_tentacle_id"] == channel_tentacle_id,
                    UserProfile["channel_user_id"] == channel_user_id,
                ],
            )

    async def ensure_profile(
        self, channel_tentacle_id: str, observed: UserProfile
    ) -> UserProfile:
        """Persist the latest channel snapshot and return its registry profile.

        First sight creates an ownerless visitor profile. An existing profile
        keeps its ownership while observations refresh its display fields. An
        `observed.user_id` is the one exception: no channel ever sets it —
        only a verified bearer's transient anchor (`native_profile`) carries
        one — so an identity that arrives owned stays owned.
        """
        key = (channel_tentacle_id, observed.channel_user_id)
        async with self.lock(key), async_session() as session:
            profile = await session.one_or_none(
                UserProfile,
                expressions=[
                    UserProfile["channel_tentacle_id"] == channel_tentacle_id,
                    UserProfile["channel_user_id"] == observed.channel_user_id,
                ],
            )
            if profile is None:
                profile = UserProfile(
                    channel_tentacle_id=channel_tentacle_id,
                    channel_user_id=observed.channel_user_id,
                    user_id=observed.user_id,
                    **observed.model_dump(include=PROFILE_FIELDS),
                )
                session.add(profile)
            else:
                for name in PROFILE_FIELDS:
                    setattr(profile, name, getattr(observed, name))
                if observed.user_id is not None:
                    profile.user_id = observed.user_id

            await session.commit()

        return profile

    @staticmethod
    def hash_link_token(token: SecretStr) -> SecretStr:
        return SecretStr(hashlib.sha256(token.get_secret_value().encode()).hexdigest())

    async def link_verified_profile(self, profile: UserProfile, user: User) -> None:
        """Link an OAuth-verified profile without replacing an existing owner."""
        async with self.lock(profile.id), async_session() as session:
            stored = await session.get(UserProfile, profile.id)
            if stored is None or await session.get(User, user.id) is None:
                raise InvalidLinkProfile
            if stored.user_id is not None and stored.user_id != user.id:
                raise ProfileAlreadyLinked
            stored.user_id = user.id
            pending = await session.one_or_none(
                LinkProfileSession,
                expressions=[LinkProfileSession["profile_id"] == stored.id],
            )
            if pending is not None:
                pending.consumed_at = datetime.now(UTC)
            await session.commit()

    async def start_link_profile(
        self, profile: UserProfile
    ) -> LinkProfileAuthorization:
        """Replace this ownerless profile's pending ticket and return its private URL."""
        if self.authorization_base_uri is None:
            raise LinkProfileUnavailable(
                "Configure local auth and oauth.callback_base_uri before linking channel profiles"
            )
        token = SecretStr(secrets.token_urlsafe(32))
        now = datetime.now(UTC)
        async with self.lock(profile.id), async_session() as session:
            stored = await session.get(UserProfile, profile.id)
            if stored is None:
                raise InvalidLinkProfile
            if stored.user_id is not None:
                raise ProfileAlreadyLinked
            pending = await session.one_or_none(
                LinkProfileSession,
                expressions=[LinkProfileSession["profile_id"] == stored.id],
            )
            if pending is None:
                pending = LinkProfileSession(
                    profile_id=stored.id,
                    token_hash=self.hash_link_token(token),
                    expires_at=now + self.authorization_lifetime,
                )
                session.add(pending)
            else:
                pending.token_hash = self.hash_link_token(token)
                pending.expires_at = now + self.authorization_lifetime
                pending.created_at = now
                pending.consumed_at = None
            await session.commit()

        root = str(self.authorization_base_uri).rstrip("/")
        return LinkProfileAuthorization(
            profile=stored,
            authorization_uri=AnyHttpUrl(
                f"{root}/#link-profile={token.get_secret_value()}"
            ),
            expires_at=now + self.authorization_lifetime,
        )

    async def inspect_link_profile(self, token: SecretStr) -> LinkProfileInfo:
        token_hash = self.hash_link_token(token)
        async with async_session() as session:
            pending = await session.one_or_none(
                LinkProfileSession,
                expressions=[
                    LinkProfileSession["token_hash"] == token_hash,
                    LinkProfileSession["consumed_at"].is_(None),
                    LinkProfileSession["expires_at"] > datetime.now(UTC),
                ],
            )
            if pending is None:
                raise InvalidLinkProfile
            profile = await session.get(UserProfile, pending.profile_id)
            if profile is None:
                raise InvalidLinkProfile
            if profile.user_id is not None:
                raise ProfileAlreadyLinked
            return LinkProfileInfo(profile=profile, expires_at=pending.expires_at)

    async def confirm_link_profile(self, token: SecretStr, user: User) -> UserProfile:
        """Consume a valid ticket and link its exact profile to ``user`` once."""
        token_hash = self.hash_link_token(token)
        async with async_session() as session:
            found = await session.one_or_none(
                LinkProfileSession,
                expressions=[LinkProfileSession["token_hash"] == token_hash],
            )
        if found is None:
            raise InvalidLinkProfile

        async with self.lock(found.profile_id), async_session() as session:
            pending = await session.one_or_none(
                LinkProfileSession,
                expressions=[
                    LinkProfileSession["token_hash"] == token_hash,
                    LinkProfileSession["consumed_at"].is_(None),
                    LinkProfileSession["expires_at"] > datetime.now(UTC),
                ],
            )
            if pending is None:
                raise InvalidLinkProfile
            profile = await session.get(UserProfile, pending.profile_id)
            if profile is None or await session.get(User, user.id) is None:
                raise InvalidLinkProfile
            if profile.user_id is not None:
                raise ProfileAlreadyLinked
            profile.user_id = user.id
            pending.consumed_at = datetime.now(UTC)
            try:
                await session.flush()
            except StaleDataError as error:
                raise InvalidLinkProfile from error
            await session.commit()
            return profile

authorization_base_uri instance-attribute

authorization_base_uri = authorization_base_uri

authorization_lifetime instance-attribute

authorization_lifetime = authorization_lifetime

get async

get(user_id: UUID7) -> User | None
Source code in octomate/managers/user.py
async def get(self, user_id: UUID7) -> User | None:
    async with async_session() as session:
        return await session.get(User, user_id)
unlink_profile(user: User, profile_id: UUID7) -> None
Source code in octomate/managers/user.py
async def unlink_profile(self, user: User, profile_id: UUID7) -> None:
    async with self.lock(profile_id), async_session() as session:
        profile = await session.get(UserProfile, profile_id)
        if profile is None or profile.user_id != user.id:
            raise ProfileNotLinked
        profile.user_id = None
        pending = await session.one_or_none(
            LinkProfileSession,
            expressions=[LinkProfileSession["profile_id"] == profile_id],
        )
        if pending is not None:
            pending.consumed_at = datetime.now(UTC)
        await session.commit()

owner async

owner(profile: UserProfile) -> User | None

Return the registered owner of profile, or None for a visitor.

Source code in octomate/managers/user.py
async def owner(self, profile: UserProfile) -> User | None:
    """Return the registered owner of ``profile``, or ``None`` for a visitor."""
    user_id = profile.user_id
    if user_id is None:
        return None
    async with async_session() as session:
        user = await session.get(User, user_id)
    if user is None:
        raise ValueError(f"unknown user {user_id}")
    return user

linked_profiles async

linked_profiles(profile: UserProfile) -> list[UserProfile]

This human's other channel identities — the same person on another platform, reachable precisely because the registry links the accounts.

Empty for a visitor: only a registered User links identities, so an unregistered account is one account and can be followed nowhere. owner answers "whose is this"; this answers "where else are they".

Source code in octomate/managers/user.py
async def linked_profiles(
    self,
    profile: UserProfile,
) -> list[UserProfile]:
    """This human's other channel identities — the same person on another
    platform, reachable precisely because the registry links the accounts.

    Empty for a visitor: only a registered `User` links identities, so an
    unregistered account is one account and can be followed nowhere. `owner`
    answers "whose is this"; this answers "where else are they".
    """
    user = await self.owner(profile)
    if user is None:
        return []
    async with async_session() as session:
        return list(
            await session.list(
                UserProfile,
                limit=None,
                expressions=[
                    UserProfile["user_id"] == user.id,
                    UserProfile["channel_tentacle_id"]
                    != profile.channel_tentacle_id,
                ],
            )
        )

native_profile async

native_profile(
    runtime: str, username: str
) -> UserProfile | None

A transient anchor for username's native session on runtime's pseudo-channel, or None for an unknown username.

Never persisted: a native session's identity comes from its verified bearer, not from a claimed row, so the profile exists only to give the linked-profile walk its starting point — owned like a stored profile, and standing on a channel id no channel ever resolves.

Source code in octomate/managers/user.py
async def native_profile(self, runtime: str, username: str) -> UserProfile | None:
    """A transient anchor for `username`'s native session on `runtime`'s
    pseudo-channel, or None for an unknown username.

    Never persisted: a native session's identity comes from its verified
    bearer, not from a claimed row, so the profile exists only to give the
    linked-profile walk its starting point — owned like a stored profile,
    and standing on a channel id no channel ever resolves.
    """
    async with async_session() as session:
        user = await session.one_or_none(
            User, expressions=[User["username"] == username]
        )
    if user is None:
        return None
    return UserProfile(
        channel_tentacle_id=runtime,
        channel_user_id=username,
        user_id=user.id,
        user=Relation(user),
        name=user.name,
        nickname=user.nickname,
    )

profile async

profile(
    channel_tentacle_id: str, channel_user_id: str
) -> UserProfile | None

The stored profile for a channel identity, or None if never observed.

The read-only sibling of ensure_profile, for callers that hold only a channel identity — e.g. a deferred batch resuming long after the message that carried the sender's profile snapshot.

Source code in octomate/managers/user.py
async def profile(
    self, channel_tentacle_id: str, channel_user_id: str
) -> UserProfile | None:
    """The stored profile for a channel identity, or ``None`` if never observed.

    The read-only sibling of ``ensure_profile``, for callers that hold only a
    channel identity — e.g. a deferred batch resuming long after the message
    that carried the sender's profile snapshot."""
    async with async_session() as session:
        return await session.one_or_none(
            UserProfile,
            expressions=[
                UserProfile["channel_tentacle_id"] == channel_tentacle_id,
                UserProfile["channel_user_id"] == channel_user_id,
            ],
        )

ensure_profile async

ensure_profile(
    channel_tentacle_id: str, observed: UserProfile
) -> UserProfile

Persist the latest channel snapshot and return its registry profile.

First sight creates an ownerless visitor profile. An existing profile keeps its ownership while observations refresh its display fields. An observed.user_id is the one exception: no channel ever sets it — only a verified bearer's transient anchor (native_profile) carries one — so an identity that arrives owned stays owned.

Source code in octomate/managers/user.py
async def ensure_profile(
    self, channel_tentacle_id: str, observed: UserProfile
) -> UserProfile:
    """Persist the latest channel snapshot and return its registry profile.

    First sight creates an ownerless visitor profile. An existing profile
    keeps its ownership while observations refresh its display fields. An
    `observed.user_id` is the one exception: no channel ever sets it —
    only a verified bearer's transient anchor (`native_profile`) carries
    one — so an identity that arrives owned stays owned.
    """
    key = (channel_tentacle_id, observed.channel_user_id)
    async with self.lock(key), async_session() as session:
        profile = await session.one_or_none(
            UserProfile,
            expressions=[
                UserProfile["channel_tentacle_id"] == channel_tentacle_id,
                UserProfile["channel_user_id"] == observed.channel_user_id,
            ],
        )
        if profile is None:
            profile = UserProfile(
                channel_tentacle_id=channel_tentacle_id,
                channel_user_id=observed.channel_user_id,
                user_id=observed.user_id,
                **observed.model_dump(include=PROFILE_FIELDS),
            )
            session.add(profile)
        else:
            for name in PROFILE_FIELDS:
                setattr(profile, name, getattr(observed, name))
            if observed.user_id is not None:
                profile.user_id = observed.user_id

        await session.commit()

    return profile
hash_link_token(token: SecretStr) -> SecretStr
Source code in octomate/managers/user.py
@staticmethod
def hash_link_token(token: SecretStr) -> SecretStr:
    return SecretStr(hashlib.sha256(token.get_secret_value().encode()).hexdigest())
link_verified_profile(
    profile: UserProfile, user: User
) -> None

Link an OAuth-verified profile without replacing an existing owner.

Source code in octomate/managers/user.py
async def link_verified_profile(self, profile: UserProfile, user: User) -> None:
    """Link an OAuth-verified profile without replacing an existing owner."""
    async with self.lock(profile.id), async_session() as session:
        stored = await session.get(UserProfile, profile.id)
        if stored is None or await session.get(User, user.id) is None:
            raise InvalidLinkProfile
        if stored.user_id is not None and stored.user_id != user.id:
            raise ProfileAlreadyLinked
        stored.user_id = user.id
        pending = await session.one_or_none(
            LinkProfileSession,
            expressions=[LinkProfileSession["profile_id"] == stored.id],
        )
        if pending is not None:
            pending.consumed_at = datetime.now(UTC)
        await session.commit()
start_link_profile(
    profile: UserProfile,
) -> LinkProfileAuthorization

Replace this ownerless profile's pending ticket and return its private URL.

Source code in octomate/managers/user.py
async def start_link_profile(
    self, profile: UserProfile
) -> LinkProfileAuthorization:
    """Replace this ownerless profile's pending ticket and return its private URL."""
    if self.authorization_base_uri is None:
        raise LinkProfileUnavailable(
            "Configure local auth and oauth.callback_base_uri before linking channel profiles"
        )
    token = SecretStr(secrets.token_urlsafe(32))
    now = datetime.now(UTC)
    async with self.lock(profile.id), async_session() as session:
        stored = await session.get(UserProfile, profile.id)
        if stored is None:
            raise InvalidLinkProfile
        if stored.user_id is not None:
            raise ProfileAlreadyLinked
        pending = await session.one_or_none(
            LinkProfileSession,
            expressions=[LinkProfileSession["profile_id"] == stored.id],
        )
        if pending is None:
            pending = LinkProfileSession(
                profile_id=stored.id,
                token_hash=self.hash_link_token(token),
                expires_at=now + self.authorization_lifetime,
            )
            session.add(pending)
        else:
            pending.token_hash = self.hash_link_token(token)
            pending.expires_at = now + self.authorization_lifetime
            pending.created_at = now
            pending.consumed_at = None
        await session.commit()

    root = str(self.authorization_base_uri).rstrip("/")
    return LinkProfileAuthorization(
        profile=stored,
        authorization_uri=AnyHttpUrl(
            f"{root}/#link-profile={token.get_secret_value()}"
        ),
        expires_at=now + self.authorization_lifetime,
    )
inspect_link_profile(token: SecretStr) -> LinkProfileInfo
Source code in octomate/managers/user.py
async def inspect_link_profile(self, token: SecretStr) -> LinkProfileInfo:
    token_hash = self.hash_link_token(token)
    async with async_session() as session:
        pending = await session.one_or_none(
            LinkProfileSession,
            expressions=[
                LinkProfileSession["token_hash"] == token_hash,
                LinkProfileSession["consumed_at"].is_(None),
                LinkProfileSession["expires_at"] > datetime.now(UTC),
            ],
        )
        if pending is None:
            raise InvalidLinkProfile
        profile = await session.get(UserProfile, pending.profile_id)
        if profile is None:
            raise InvalidLinkProfile
        if profile.user_id is not None:
            raise ProfileAlreadyLinked
        return LinkProfileInfo(profile=profile, expires_at=pending.expires_at)
confirm_link_profile(
    token: SecretStr, user: User
) -> UserProfile

Consume a valid ticket and link its exact profile to user once.

Source code in octomate/managers/user.py
async def confirm_link_profile(self, token: SecretStr, user: User) -> UserProfile:
    """Consume a valid ticket and link its exact profile to ``user`` once."""
    token_hash = self.hash_link_token(token)
    async with async_session() as session:
        found = await session.one_or_none(
            LinkProfileSession,
            expressions=[LinkProfileSession["token_hash"] == token_hash],
        )
    if found is None:
        raise InvalidLinkProfile

    async with self.lock(found.profile_id), async_session() as session:
        pending = await session.one_or_none(
            LinkProfileSession,
            expressions=[
                LinkProfileSession["token_hash"] == token_hash,
                LinkProfileSession["consumed_at"].is_(None),
                LinkProfileSession["expires_at"] > datetime.now(UTC),
            ],
        )
        if pending is None:
            raise InvalidLinkProfile
        profile = await session.get(UserProfile, pending.profile_id)
        if profile is None or await session.get(User, user.id) is None:
            raise InvalidLinkProfile
        if profile.user_id is not None:
            raise ProfileAlreadyLinked
        profile.user_id = user.id
        pending.consumed_at = datetime.now(UTC)
        try:
            await session.flush()
        except StaleDataError as error:
            raise InvalidLinkProfile from error
        await session.commit()
        return profile

octomate.managers.auth

Local accounts, browser sessions, API keys, and inbound OAuth grants.

InvalidCredentials

Bases: ValueError

An authentication or credential exchange that is invalid or expired.

Source code in octomate/managers/auth.py
class InvalidCredentials(ValueError):
    """An authentication or credential exchange that is invalid or expired."""

    def __init__(self) -> None:
        super().__init__("Invalid or expired credentials")

UsernameUnavailable

Bases: ValueError

A registration whose username is already taken.

Source code in octomate/managers/auth.py
class UsernameUnavailable(ValueError):
    """A registration whose username is already taken."""

    def __init__(self) -> None:
        super().__init__("This username is already taken")

InvalidOAuthScopes

Bases: ValueError

Requested scopes are empty or exceed the existing authorization.

Source code in octomate/managers/auth.py
class InvalidOAuthScopes(ValueError):
    """Requested scopes are empty or exceed the existing authorization."""

    def __init__(self) -> None:
        super().__init__("Scopes must be a nonempty subset of the authorization")

AuthManager

Bases: Manager, Locks[str]

Invite-only registration, local passwords, and user credentials.

Source code in octomate/managers/auth.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
class AuthManager(Manager, Locks[str]):
    """Invite-only registration, local passwords, and user credentials."""

    def __init__(self, config: AuthConfig) -> None:
        self.config: AuthConfig = config
        self.password_hasher: PasswordHasher = PasswordHasher()
        self.password_limiter: CapacityLimiter = CapacityLimiter(2)
        # Unknown and unenrolled users still pay the password verification cost.
        self.dummy_password_hash: str = self.password_hasher.hash(
            secrets.token_urlsafe(32)
        )

    async def hash_password(self, password: SecretStr) -> SecretStr:
        return SecretStr(
            await to_thread.run_sync(
                self.password_hasher.hash,
                password.get_secret_value(),
                limiter=self.password_limiter,
            )
        )

    @staticmethod
    def hash_token(token: SecretStr, salt: SecretStr) -> SecretStr:
        return SecretStr(
            hashlib.sha256(
                (token.get_secret_value() + salt.get_secret_value()).encode()
            ).hexdigest()
        )

    async def invite(self) -> SecretStr:
        """Issue an anonymous code that admits one new account."""
        token = SecretStr(secrets.token_urlsafe(32))
        async with async_session() as session:
            session.add(
                UserInvitation(
                    token_hash=SecretStr(
                        hashlib.sha256(token.get_secret_value().encode()).hexdigest()
                    ),
                    expires_at=datetime.now(UTC) + self.config.invitation_lifetime,
                )
            )
            await session.commit()
            return token

    async def register(
        self, username: str, password: SecretStr, invitation: SecretStr, *, name: str
    ) -> User:
        if not username or username != username.strip() or len(username) > 100:
            raise ValueError(
                "Username must contain 1-100 characters without surrounding spaces"
            )
        password = NewPasswordAdapter.validate_python(password)
        if not 1 <= len(name) <= 100:
            raise ValueError("Display name must contain 1-100 characters")
        async with self.lock(username), async_session() as session:
            token_hash = SecretStr(
                hashlib.sha256(invitation.get_secret_value().encode()).hexdigest()
            )
            current = await session.one_or_none(
                UserInvitation,
                expressions=[
                    UserInvitation["token_hash"] == token_hash,
                    UserInvitation["consumed_at"].is_(None),
                    UserInvitation["expires_at"] > datetime.now(UTC),
                ],
            )
            if current is None:
                raise InvalidCredentials
            if (
                await session.one_or_none(
                    User, expressions=[User["username"] == username]
                )
                is not None
            ):
                raise UsernameUnavailable
            user = User(
                username=username,
                name=name,
                password_hash=await self.hash_password(password),
            )
            session.add(user)
            now = datetime.now(UTC)
            if current.expires_at <= now:
                raise InvalidCredentials
            current.consumed_at = now
            try:
                await session.flush()
            except StaleDataError as error:
                raise InvalidCredentials from error
            await session.commit()
            return user

    async def login(self, username: str, password: SecretStr) -> SessionTokens:
        async with async_session() as session:
            user = await session.one_or_none(
                User, expressions=[User["username"] == username]
            )
            password_hash = (
                user.password_hash.get_secret_value()
                if user is not None and user.password_hash is not None
                else self.dummy_password_hash
            )
            try:
                await to_thread.run_sync(
                    self.password_hasher.verify,
                    password_hash,
                    password.get_secret_value(),
                    limiter=self.password_limiter,
                )
            except VerifyMismatchError as error:
                raise InvalidCredentials from error
            if user is None or user.password_hash is None:
                raise InvalidCredentials
            if self.password_hasher.check_needs_rehash(password_hash):
                user.password_hash = await self.hash_password(password)

            now = datetime.now(UTC)
            tokens = SessionTokens(
                session_id=uuid7(),
                user_id=user.id,
                access_token=SecretStr(secrets.token_urlsafe(32)),
                refresh_token=SecretStr(secrets.token_urlsafe(32)),
                access_expires_at=now + self.config.access_token_lifetime,
                refresh_expires_at=now + self.config.session_lifetime,
            )
            session.add(
                UserSession(
                    id=tokens.session_id,
                    user_id=user.id,
                    access_token_hash=self.hash_token(
                        tokens.access_token, self.config.access_token_salt
                    ),
                    refresh_token_hash=self.hash_token(
                        tokens.refresh_token, self.config.refresh_token_salt
                    ),
                    access_expires_at=tokens.access_expires_at,
                    refresh_expires_at=tokens.refresh_expires_at,
                )
            )
            await session.commit()
            return tokens

    async def authenticate_session(self, token: SecretStr) -> UserSession | None:
        now = datetime.now(UTC)
        async with async_session() as session:
            return await session.one_or_none(
                UserSession,
                expressions=[
                    UserSession["access_token_hash"]
                    == self.hash_token(token, self.config.access_token_salt),
                    UserSession["revoked_at"].is_(None),
                    UserSession["access_expires_at"] > now,
                    UserSession["refresh_expires_at"] > now,
                ],
            )

    async def set_password(
        self,
        username: str,
        password: SecretStr,
        *,
        current_password: SecretStr | None = None,
    ) -> None:
        """Replace a password and end browser sessions; HTTP callers must supply the old password."""
        password = NewPasswordAdapter.validate_python(password)
        async with self.lock(username), async_session() as session:
            user = await session.one_or_none(
                User, expressions=[User["username"] == username]
            )
            if user is None or user.password_hash is None:
                raise InvalidCredentials
            if current_password is not None:
                try:
                    await to_thread.run_sync(
                        self.password_hasher.verify,
                        user.password_hash.get_secret_value(),
                        current_password.get_secret_value(),
                        limiter=self.password_limiter,
                    )
                except VerifyMismatchError as error:
                    raise InvalidCredentials from error
            user.password_hash = await self.hash_password(password)
            now = datetime.now(UTC)
            for current in await session.list(
                UserSession,
                expressions=[
                    UserSession["user_id"] == user.id,
                    UserSession["revoked_at"].is_(None),
                ],
                limit=None,
            ):
                current.revoked_at = now
            await session.commit()

    async def logout(
        self, access_token: SecretStr | None, refresh_token: SecretStr | None
    ) -> None:
        expressions = []
        if access_token is not None:
            expressions.append(
                UserSession["access_token_hash"]
                == self.hash_token(access_token, self.config.access_token_salt)
            )
        if refresh_token is not None:
            expressions.append(
                UserSession["refresh_token_hash"]
                == self.hash_token(refresh_token, self.config.refresh_token_salt)
            )
        if not expressions:
            return
        async with async_session() as session:
            for current in await session.list(
                UserSession,
                expressions=[or_(*expressions), UserSession["revoked_at"].is_(None)],
                limit=None,
            ):
                current.revoked_at = datetime.now(UTC)
            await session.commit()

    async def refresh_session(self, token: SecretStr) -> SessionTokens:
        now = datetime.now(UTC)
        async with async_session() as session:
            current = await session.one_or_none(
                UserSession,
                expressions=[
                    UserSession["refresh_token_hash"]
                    == self.hash_token(token, self.config.refresh_token_salt),
                    UserSession["revoked_at"].is_(None),
                    UserSession["refresh_expires_at"] > now,
                ],
            )
            if current is None:
                raise InvalidCredentials
            deadline = current.refresh_expires_at
            tokens = SessionTokens(
                session_id=current.id,
                user_id=current.user_id,
                access_token=SecretStr(secrets.token_urlsafe(32)),
                refresh_token=SecretStr(secrets.token_urlsafe(32)),
                access_expires_at=min(
                    now + self.config.access_token_lifetime, deadline
                ),
                refresh_expires_at=deadline,
            )
            current.access_token_hash = self.hash_token(
                tokens.access_token, self.config.access_token_salt
            )
            current.refresh_token_hash = self.hash_token(
                tokens.refresh_token, self.config.refresh_token_salt
            )
            current.access_expires_at = tokens.access_expires_at
            try:
                await session.flush()
            except StaleDataError as error:
                raise InvalidCredentials from error
            await session.commit()
            return tokens

    async def revoke_session(self, user_id: UUID7, session_id: UUID7) -> None:
        async with async_session() as session:
            current = await session.get(UserSession, session_id)
            if current is None or current.user_id != user_id:
                raise InvalidCredentials
            if current.revoked_at is None:
                current.revoked_at = datetime.now(UTC)
                try:
                    await session.flush()
                except StaleDataError as error:
                    raise InvalidCredentials from error
                await session.commit()

    async def create_api_key(
        self,
        user_id: UUID7,
        *,
        name: str,
        scopes: list[ApiKeyScope],
        expires_at: AwareDatetime | None = None,
    ) -> UserApiKey:
        """Issue for a verified user; the HTTP caller must establish that identity."""
        token = SecretStr(self.config.api_key_prefix + secrets.token_urlsafe(32))
        key = UserApiKey(
            user_id=user_id,
            name=name,
            scopes=scopes,
            expires_at=expires_at,
            key_prefix=token.get_secret_value()[:12],
            key_hash=self.hash_token(token, self.config.api_key_salt),
        )
        if key.expires_at is not None and key.expires_at <= datetime.now(UTC):
            raise ValueError("API key expiry must be in the future")
        async with async_session() as session:
            if await session.get(User, user_id) is None:
                raise InvalidCredentials
            session.add(key)
            await session.commit()
        key.bearer = token
        return key

    async def authenticate_api_key(
        self, token: SecretStr, *, scope: ApiKeyScope
    ) -> ApiKey | None:
        token_hash = self.hash_token(token, self.config.api_key_salt)
        async with async_session() as session:
            now = datetime.now(UTC)
            key = await session.one_or_none(
                ApiKey,
                expressions=[
                    ApiKey["key_hash"] == token_hash,
                    ApiKey["revoked_at"].is_(None),
                    ApiKey["expires_at"].is_(None) | (ApiKey["expires_at"] > now),
                ],
            )
            if key is None or scope not in key.scopes:
                return None
            if not isinstance(key, RuntimeApiKey):
                return key
        async with self.lock(f"api-key:{key.user_id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                # SQLite has no row locks; reserve its writer before reading.
                await session.execute(text("BEGIN IMMEDIATE"))
            await session.get(User, key.user_id, with_for_update=True)
            current = await session.get(RuntimeApiKey, key.id)
            now = datetime.now(UTC)
            if (
                current is None
                or current.key_hash != token_hash
                or current.revoked_at is not None
                or (current.expires_at is not None and current.expires_at <= now)
                or scope not in current.scopes
            ):
                return None
            current.expires_at = max(
                current.expires_at or now, now + self.config.runtime_api_key_lifetime
            )
            await session.commit()
            return current

    def runtime_bearer(self, nonce: UUID7) -> SecretStr:
        """Reproduce a runtime API key without storing its bearer in the database."""
        digest = hmac.digest(
            self.config.api_key_salt.get_secret_value().encode(),
            b"octomate:runtime-api-key:v1:" + nonce.bytes,
            "sha256",
        ).hex()
        return SecretStr(self.config.api_key_prefix + digest)

    async def runtime_api_key(
        self, user_id: UUID7, *, agent_id: str, scopes: list[ApiKeyScope]
    ) -> RuntimeApiKey:
        """Reuse shared persisted state; expiry rotates the bearer, not the key row."""
        scopes = sorted(set(scopes))
        async with self.lock(f"api-key:{user_id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                # SQLite has no row locks; reserve its writer before reading.
                await session.execute(text("BEGIN IMMEDIATE"))
            if await session.get(User, user_id, with_for_update=True) is None:
                raise InvalidCredentials
            key = await session.one_or_none(
                RuntimeApiKey,
                expressions=[
                    RuntimeApiKey["user_id"] == user_id,
                    RuntimeApiKey["runtime_agent_id"] == agent_id,
                ],
            )
            now = datetime.now(UTC)
            deadline = now + self.config.runtime_api_key_lifetime
            if key is not None and key.revoked_at is not None:
                raise InvalidCredentials
            if (
                key is None
                or key.expires_at is None
                or key.expires_at <= now
                or key.scopes != scopes
            ):
                nonce = uuid7()
            else:
                nonce = key.runtime_nonce
            token = self.runtime_bearer(nonce)
            if (
                key is not None
                and nonce == key.runtime_nonce
                and key.key_hash != self.hash_token(token, self.config.api_key_salt)
            ):
                raise ValueError(
                    "Runtime API key does not match this core's auth secrets"
                )
            if key is None:
                key = RuntimeApiKey(
                    user_id=user_id,
                    scopes=scopes,
                    runtime_agent_id=agent_id,
                    runtime_nonce=nonce,
                    key_hash=self.hash_token(token, self.config.api_key_salt),
                    key_prefix=token.get_secret_value()[:12],
                )
                session.add(key)
            key.runtime_nonce = nonce
            key.key_hash = self.hash_token(token, self.config.api_key_salt)
            key.key_prefix = token.get_secret_value()[:12]
            key.scopes = scopes
            key.expires_at = max(key.expires_at or now, deadline)
            await session.commit()
            key.bearer = token
            return key

    async def get_api_key(self, user_id: UUID7, key_id: UUID7) -> ApiKey:
        async with async_session() as session:
            key = await session.get(ApiKey, key_id)
            if key is None or key.user_id != user_id:
                raise InvalidCredentials
            return key

    async def list_api_keys(self, user_id: UUID7) -> list[UserApiKey]:
        async with async_session() as session:
            return list(
                await session.list(
                    UserApiKey,
                    expressions=[UserApiKey["user_id"] == user_id],
                    limit=None,
                )
            )

    async def revoke_api_key(self, user_id: UUID7, key_id: UUID7) -> None:
        async with self.lock(f"api-key:{user_id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                # SQLite has no row locks; reserve its writer before reading.
                await session.execute(text("BEGIN IMMEDIATE"))
            await session.get(User, user_id, with_for_update=True)
            key = await session.get(ApiKey, key_id)
            if key is None or key.user_id != user_id:
                raise InvalidCredentials
            if key.revoked_at is not None:
                return
            key.revoked_at = datetime.now(UTC)
            await session.commit()

    async def register_oauth_client(self, client: OAuthClient) -> None:
        async with async_session() as session:
            session.add(client)
            await session.commit()

    async def get_oauth_client(self, client_id: UUID7) -> OAuthClient | None:
        async with async_session() as session:
            return await session.get(OAuthClient, client_id)

    async def create_oauth_authorization(self, pending: OAuthAuthorization) -> None:
        async with async_session() as session:
            session.add(pending)
            await session.commit()

    async def get_oauth_code(self, code: SecretStr) -> OAuthAuthorization | None:
        async with async_session() as session:
            return await session.one_or_none(
                OAuthAuthorization,
                expressions=[
                    OAuthAuthorization["code_hash"]
                    == self.hash_token(code, self.config.access_token_salt)
                ],
            )

    async def revoke_oauth_token(self, client_id: UUID7, bearer: SecretStr) -> None:
        """Revoke only a token belonging to the requesting public client."""
        async with async_session() as session:
            token = await session.one_or_none(
                OAuthToken,
                expressions=[
                    (
                        OAuthToken["access_token_hash"]
                        == self.hash_token(bearer, self.config.access_token_salt)
                    )
                    | (
                        OAuthToken["refresh_token_hash"]
                        == self.hash_token(bearer, self.config.refresh_token_salt)
                    )
                ],
            )
            grant = (
                await session.get(OAuthGrant, token.grant_id)
                if token is not None
                else None
            )
        if grant is not None and grant.client_id == client_id:
            await self.revoke_oauth_grant(grant.user_id, grant.id)

    async def get_oauth_authorization(self, ticket: SecretStr) -> OAuthAuthorization:
        """Inspect live, undecided consent without issuing credentials."""
        async with async_session() as session:
            pending = await session.one_or_none(
                OAuthAuthorization,
                expressions=[
                    OAuthAuthorization["ticket_hash"]
                    == self.hash_token(ticket, self.config.access_token_salt)
                ],
            )
        if (
            pending is None
            or pending.expires_at <= datetime.now(UTC)
            or pending.grant_id is not None
        ):
            raise InvalidCredentials
        return pending

    async def deny_oauth_authorization(self, ticket: SecretStr) -> OAuthAuthorization:
        """Expire pending consent under the same lock as approval."""
        pending = await self.get_oauth_authorization(ticket)
        async with self.lock(f"oauth-consent:{pending.id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                await session.execute(text("BEGIN IMMEDIATE"))
            pending = await session.get(
                OAuthAuthorization, pending.id, with_for_update=True
            )
            now = datetime.now(UTC)
            if (
                pending is None
                or pending.expires_at <= now
                or pending.grant_id is not None
            ):
                raise InvalidCredentials
            pending.expires_at = now
            await session.commit()
            return pending

    async def approve_oauth_authorization(
        self, user_id: UUID7, ticket: SecretStr
    ) -> OAuthAuthorization:
        """Bind pending consent to the authenticated browser user, once only."""
        ticket_hash = self.hash_token(ticket, self.config.access_token_salt)
        async with async_session() as session:
            pending = await session.one_or_none(
                OAuthAuthorization,
                expressions=[OAuthAuthorization["ticket_hash"] == ticket_hash],
            )
        if pending is None:
            raise InvalidCredentials
        async with self.lock(f"oauth-consent:{pending.id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                # SQLite has no row locks; reserve its writer before reading.
                await session.execute(text("BEGIN IMMEDIATE"))
            pending = await session.get(
                OAuthAuthorization, pending.id, with_for_update=True
            )
            now = datetime.now(UTC)
            if (
                pending is None
                or pending.ticket_hash != ticket_hash
                or pending.expires_at <= now
                or pending.grant_id is not None
            ):
                raise InvalidCredentials
            if await session.get(User, user_id) is None:
                raise InvalidCredentials
            client = await session.get(OAuthClient, pending.client_id)
            if client is None:
                raise InvalidCredentials
            if not pending.scopes or not set(pending.scopes) <= set(client.scopes):
                raise InvalidOAuthScopes
            grant = OAuthGrant(
                client_id=client.id,
                user_id=user_id,
                resource=pending.resource,
                scopes=sorted(set(pending.scopes)),
                expires_at=now + self.config.oauth_grant_idle_lifetime,
            )
            session.add(grant)
            await session.flush()
            code = SecretStr(secrets.token_urlsafe(32))
            pending.grant_id = grant.id
            pending.code_hash = self.hash_token(code, self.config.access_token_salt)
            pending.expires_at = min(
                grant.expires_at, now + self.config.oauth_authorization_lifetime
            )
            await session.commit()
            pending.code = code
            return pending

    async def exchange_oauth_code(
        self, client_id: UUID7, code: SecretStr, *, resource: str
    ) -> OAuthToken:
        """Consume a code after the OAuth handler verifies PKCE and redirect binding.

        The protocol handler owns request validation. Reload under the grant lock
        so expiry, replay, and revocation remain authoritative at issuance.
        """
        code_hash = self.hash_token(code, self.config.access_token_salt)
        authorization = await self.get_oauth_code(code)
        if authorization is None or authorization.grant_id is None:
            raise InvalidCredentials
        async with (
            self.lock(f"oauth-grant:{authorization.grant_id}"),
            async_session() as session,
        ):
            if session.get_bind().dialect.name == "sqlite":
                await session.execute(text("BEGIN IMMEDIATE"))
            grant = await session.get(
                OAuthGrant, authorization.grant_id, with_for_update=True
            )
            authorization = await session.get(OAuthAuthorization, authorization.id)
            now = datetime.now(UTC)
            if (
                grant is None
                or grant.client_id != client_id
                or grant.resource != resource
                or grant.revoked_at is not None
                or grant.expires_at <= now
                or authorization is None
                or authorization.code_hash != code_hash
            ):
                raise InvalidCredentials
            if authorization.consumed_at is not None:
                grant.revoked_at = now
                await session.commit()
                raise InvalidCredentials
            if authorization.expires_at <= now:
                raise InvalidCredentials
            access = SecretStr(secrets.token_urlsafe(32))
            refresh = SecretStr(secrets.token_urlsafe(32))
            token = OAuthToken(
                grant_id=grant.id,
                access_token_hash=self.hash_token(
                    access, self.config.access_token_salt
                ),
                refresh_token_hash=self.hash_token(
                    refresh, self.config.refresh_token_salt
                ),
                scopes=grant.scopes,
                access_expires_at=min(
                    grant.expires_at, now + self.config.access_token_lifetime
                ),
            )
            authorization.consumed_at = now
            session.add(token)
            await session.commit()
            token.access_token = access
            token.refresh_token = refresh
            return token

    async def refresh_oauth_token(
        self,
        client_id: UUID7,
        refresh_token: SecretStr,
        *,
        resource: str,
        scopes: list[ApiKeyScope] | None = None,
    ) -> OAuthToken:
        """Rotate once; replay revokes the entire grant, including newer tokens."""
        token_hash = self.hash_token(refresh_token, self.config.refresh_token_salt)
        async with async_session() as session:
            previous = await session.one_or_none(
                OAuthToken,
                expressions=[OAuthToken["refresh_token_hash"] == token_hash],
            )
        if previous is None:
            raise InvalidCredentials
        async with (
            self.lock(f"oauth-grant:{previous.grant_id}"),
            async_session() as session,
        ):
            if session.get_bind().dialect.name == "sqlite":
                await session.execute(text("BEGIN IMMEDIATE"))
            grant = await session.get(
                OAuthGrant, previous.grant_id, with_for_update=True
            )
            previous = await session.get(OAuthToken, previous.id)
            now = datetime.now(UTC)
            if (
                grant is None
                or grant.client_id != client_id
                or grant.resource != resource
                or grant.revoked_at is not None
                or grant.expires_at <= now
                or previous is None
                or previous.refresh_token_hash != token_hash
            ):
                raise InvalidCredentials
            if previous.refresh_used_at is not None:
                grant.revoked_at = now
                await session.commit()
                raise InvalidCredentials
            allowed = set(previous.scopes) & set(grant.scopes)
            requested = sorted(set(previous.scopes if scopes is None else scopes))
            if not requested or not set(requested) <= allowed:
                raise InvalidOAuthScopes
            grant.expires_at = now + self.config.oauth_grant_idle_lifetime
            access = SecretStr(secrets.token_urlsafe(32))
            refresh = SecretStr(secrets.token_urlsafe(32))
            token = OAuthToken(
                grant_id=grant.id,
                access_token_hash=self.hash_token(
                    access, self.config.access_token_salt
                ),
                refresh_token_hash=self.hash_token(
                    refresh, self.config.refresh_token_salt
                ),
                scopes=requested,
                access_expires_at=min(
                    grant.expires_at, now + self.config.access_token_lifetime
                ),
            )
            previous.refresh_used_at = now
            session.add(token)
            await session.commit()
            token.access_token = access
            token.refresh_token = refresh
            return token

    async def authenticate_oauth_token(
        self, access_token: SecretStr, *, resource: str, scope: ApiKeyScope
    ) -> OAuthPrincipal | None:
        """Check the token and its persisted grant on every resource request."""
        async with async_session() as session:
            token = await session.one_or_none(
                OAuthToken,
                expressions=[
                    OAuthToken["access_token_hash"]
                    == self.hash_token(access_token, self.config.access_token_salt)
                ],
            )
            if token is None:
                return None
            grant = await session.get(OAuthGrant, token.grant_id)
            now = datetime.now(UTC)
            if (
                grant is None
                or grant.resource != resource
                or grant.revoked_at is not None
                or grant.expires_at <= now
                or token.access_expires_at <= now
                or scope not in token.scopes
                or scope not in grant.scopes
            ):
                return None
            return OAuthPrincipal(
                grant_id=grant.id,
                user_id=grant.user_id,
                client_id=grant.client_id,
                resource=grant.resource,
                scopes=sorted(set(token.scopes) & set(grant.scopes)),
                expires_at=min(grant.expires_at, token.access_expires_at),
            )

    async def revoke_oauth_grant(self, user_id: UUID7, grant_id: UUID7) -> None:
        """Revoke one owned grant without affecting another installation's consent."""
        async with self.lock(f"oauth-grant:{grant_id}"), async_session() as session:
            if session.get_bind().dialect.name == "sqlite":
                await session.execute(text("BEGIN IMMEDIATE"))
            grant = await session.get(OAuthGrant, grant_id, with_for_update=True)
            if grant is None or grant.user_id != user_id:
                raise InvalidCredentials
            if grant.revoked_at is not None:
                return
            grant.revoked_at = datetime.now(UTC)
            await session.commit()

config instance-attribute

config: AuthConfig = config

password_hasher instance-attribute

password_hasher: PasswordHasher = PasswordHasher()

password_limiter instance-attribute

password_limiter: CapacityLimiter = CapacityLimiter(2)

dummy_password_hash instance-attribute

dummy_password_hash: str = self.password_hasher.hash(
    secrets.token_urlsafe(32)
)

hash_password async

hash_password(password: SecretStr) -> SecretStr
Source code in octomate/managers/auth.py
async def hash_password(self, password: SecretStr) -> SecretStr:
    return SecretStr(
        await to_thread.run_sync(
            self.password_hasher.hash,
            password.get_secret_value(),
            limiter=self.password_limiter,
        )
    )

hash_token staticmethod

hash_token(token: SecretStr, salt: SecretStr) -> SecretStr
Source code in octomate/managers/auth.py
@staticmethod
def hash_token(token: SecretStr, salt: SecretStr) -> SecretStr:
    return SecretStr(
        hashlib.sha256(
            (token.get_secret_value() + salt.get_secret_value()).encode()
        ).hexdigest()
    )

invite async

invite() -> SecretStr

Issue an anonymous code that admits one new account.

Source code in octomate/managers/auth.py
async def invite(self) -> SecretStr:
    """Issue an anonymous code that admits one new account."""
    token = SecretStr(secrets.token_urlsafe(32))
    async with async_session() as session:
        session.add(
            UserInvitation(
                token_hash=SecretStr(
                    hashlib.sha256(token.get_secret_value().encode()).hexdigest()
                ),
                expires_at=datetime.now(UTC) + self.config.invitation_lifetime,
            )
        )
        await session.commit()
        return token

register async

register(
    username: str,
    password: SecretStr,
    invitation: SecretStr,
    *,
    name: str,
) -> User
Source code in octomate/managers/auth.py
async def register(
    self, username: str, password: SecretStr, invitation: SecretStr, *, name: str
) -> User:
    if not username or username != username.strip() or len(username) > 100:
        raise ValueError(
            "Username must contain 1-100 characters without surrounding spaces"
        )
    password = NewPasswordAdapter.validate_python(password)
    if not 1 <= len(name) <= 100:
        raise ValueError("Display name must contain 1-100 characters")
    async with self.lock(username), async_session() as session:
        token_hash = SecretStr(
            hashlib.sha256(invitation.get_secret_value().encode()).hexdigest()
        )
        current = await session.one_or_none(
            UserInvitation,
            expressions=[
                UserInvitation["token_hash"] == token_hash,
                UserInvitation["consumed_at"].is_(None),
                UserInvitation["expires_at"] > datetime.now(UTC),
            ],
        )
        if current is None:
            raise InvalidCredentials
        if (
            await session.one_or_none(
                User, expressions=[User["username"] == username]
            )
            is not None
        ):
            raise UsernameUnavailable
        user = User(
            username=username,
            name=name,
            password_hash=await self.hash_password(password),
        )
        session.add(user)
        now = datetime.now(UTC)
        if current.expires_at <= now:
            raise InvalidCredentials
        current.consumed_at = now
        try:
            await session.flush()
        except StaleDataError as error:
            raise InvalidCredentials from error
        await session.commit()
        return user

login async

login(username: str, password: SecretStr) -> SessionTokens
Source code in octomate/managers/auth.py
async def login(self, username: str, password: SecretStr) -> SessionTokens:
    async with async_session() as session:
        user = await session.one_or_none(
            User, expressions=[User["username"] == username]
        )
        password_hash = (
            user.password_hash.get_secret_value()
            if user is not None and user.password_hash is not None
            else self.dummy_password_hash
        )
        try:
            await to_thread.run_sync(
                self.password_hasher.verify,
                password_hash,
                password.get_secret_value(),
                limiter=self.password_limiter,
            )
        except VerifyMismatchError as error:
            raise InvalidCredentials from error
        if user is None or user.password_hash is None:
            raise InvalidCredentials
        if self.password_hasher.check_needs_rehash(password_hash):
            user.password_hash = await self.hash_password(password)

        now = datetime.now(UTC)
        tokens = SessionTokens(
            session_id=uuid7(),
            user_id=user.id,
            access_token=SecretStr(secrets.token_urlsafe(32)),
            refresh_token=SecretStr(secrets.token_urlsafe(32)),
            access_expires_at=now + self.config.access_token_lifetime,
            refresh_expires_at=now + self.config.session_lifetime,
        )
        session.add(
            UserSession(
                id=tokens.session_id,
                user_id=user.id,
                access_token_hash=self.hash_token(
                    tokens.access_token, self.config.access_token_salt
                ),
                refresh_token_hash=self.hash_token(
                    tokens.refresh_token, self.config.refresh_token_salt
                ),
                access_expires_at=tokens.access_expires_at,
                refresh_expires_at=tokens.refresh_expires_at,
            )
        )
        await session.commit()
        return tokens

authenticate_session async

authenticate_session(
    token: SecretStr,
) -> UserSession | None
Source code in octomate/managers/auth.py
async def authenticate_session(self, token: SecretStr) -> UserSession | None:
    now = datetime.now(UTC)
    async with async_session() as session:
        return await session.one_or_none(
            UserSession,
            expressions=[
                UserSession["access_token_hash"]
                == self.hash_token(token, self.config.access_token_salt),
                UserSession["revoked_at"].is_(None),
                UserSession["access_expires_at"] > now,
                UserSession["refresh_expires_at"] > now,
            ],
        )

set_password async

set_password(
    username: str,
    password: SecretStr,
    *,
    current_password: SecretStr | None = None,
) -> None

Replace a password and end browser sessions; HTTP callers must supply the old password.

Source code in octomate/managers/auth.py
async def set_password(
    self,
    username: str,
    password: SecretStr,
    *,
    current_password: SecretStr | None = None,
) -> None:
    """Replace a password and end browser sessions; HTTP callers must supply the old password."""
    password = NewPasswordAdapter.validate_python(password)
    async with self.lock(username), async_session() as session:
        user = await session.one_or_none(
            User, expressions=[User["username"] == username]
        )
        if user is None or user.password_hash is None:
            raise InvalidCredentials
        if current_password is not None:
            try:
                await to_thread.run_sync(
                    self.password_hasher.verify,
                    user.password_hash.get_secret_value(),
                    current_password.get_secret_value(),
                    limiter=self.password_limiter,
                )
            except VerifyMismatchError as error:
                raise InvalidCredentials from error
        user.password_hash = await self.hash_password(password)
        now = datetime.now(UTC)
        for current in await session.list(
            UserSession,
            expressions=[
                UserSession["user_id"] == user.id,
                UserSession["revoked_at"].is_(None),
            ],
            limit=None,
        ):
            current.revoked_at = now
        await session.commit()

logout async

logout(
    access_token: SecretStr | None,
    refresh_token: SecretStr | None,
) -> None
Source code in octomate/managers/auth.py
async def logout(
    self, access_token: SecretStr | None, refresh_token: SecretStr | None
) -> None:
    expressions = []
    if access_token is not None:
        expressions.append(
            UserSession["access_token_hash"]
            == self.hash_token(access_token, self.config.access_token_salt)
        )
    if refresh_token is not None:
        expressions.append(
            UserSession["refresh_token_hash"]
            == self.hash_token(refresh_token, self.config.refresh_token_salt)
        )
    if not expressions:
        return
    async with async_session() as session:
        for current in await session.list(
            UserSession,
            expressions=[or_(*expressions), UserSession["revoked_at"].is_(None)],
            limit=None,
        ):
            current.revoked_at = datetime.now(UTC)
        await session.commit()

refresh_session async

refresh_session(token: SecretStr) -> SessionTokens
Source code in octomate/managers/auth.py
async def refresh_session(self, token: SecretStr) -> SessionTokens:
    now = datetime.now(UTC)
    async with async_session() as session:
        current = await session.one_or_none(
            UserSession,
            expressions=[
                UserSession["refresh_token_hash"]
                == self.hash_token(token, self.config.refresh_token_salt),
                UserSession["revoked_at"].is_(None),
                UserSession["refresh_expires_at"] > now,
            ],
        )
        if current is None:
            raise InvalidCredentials
        deadline = current.refresh_expires_at
        tokens = SessionTokens(
            session_id=current.id,
            user_id=current.user_id,
            access_token=SecretStr(secrets.token_urlsafe(32)),
            refresh_token=SecretStr(secrets.token_urlsafe(32)),
            access_expires_at=min(
                now + self.config.access_token_lifetime, deadline
            ),
            refresh_expires_at=deadline,
        )
        current.access_token_hash = self.hash_token(
            tokens.access_token, self.config.access_token_salt
        )
        current.refresh_token_hash = self.hash_token(
            tokens.refresh_token, self.config.refresh_token_salt
        )
        current.access_expires_at = tokens.access_expires_at
        try:
            await session.flush()
        except StaleDataError as error:
            raise InvalidCredentials from error
        await session.commit()
        return tokens

revoke_session async

revoke_session(user_id: UUID7, session_id: UUID7) -> None
Source code in octomate/managers/auth.py
async def revoke_session(self, user_id: UUID7, session_id: UUID7) -> None:
    async with async_session() as session:
        current = await session.get(UserSession, session_id)
        if current is None or current.user_id != user_id:
            raise InvalidCredentials
        if current.revoked_at is None:
            current.revoked_at = datetime.now(UTC)
            try:
                await session.flush()
            except StaleDataError as error:
                raise InvalidCredentials from error
            await session.commit()

create_api_key async

create_api_key(
    user_id: UUID7,
    *,
    name: str,
    scopes: list[ApiKeyScope],
    expires_at: AwareDatetime | None = None,
) -> UserApiKey

Issue for a verified user; the HTTP caller must establish that identity.

Source code in octomate/managers/auth.py
async def create_api_key(
    self,
    user_id: UUID7,
    *,
    name: str,
    scopes: list[ApiKeyScope],
    expires_at: AwareDatetime | None = None,
) -> UserApiKey:
    """Issue for a verified user; the HTTP caller must establish that identity."""
    token = SecretStr(self.config.api_key_prefix + secrets.token_urlsafe(32))
    key = UserApiKey(
        user_id=user_id,
        name=name,
        scopes=scopes,
        expires_at=expires_at,
        key_prefix=token.get_secret_value()[:12],
        key_hash=self.hash_token(token, self.config.api_key_salt),
    )
    if key.expires_at is not None and key.expires_at <= datetime.now(UTC):
        raise ValueError("API key expiry must be in the future")
    async with async_session() as session:
        if await session.get(User, user_id) is None:
            raise InvalidCredentials
        session.add(key)
        await session.commit()
    key.bearer = token
    return key

authenticate_api_key async

authenticate_api_key(
    token: SecretStr, *, scope: ApiKeyScope
) -> ApiKey | None
Source code in octomate/managers/auth.py
async def authenticate_api_key(
    self, token: SecretStr, *, scope: ApiKeyScope
) -> ApiKey | None:
    token_hash = self.hash_token(token, self.config.api_key_salt)
    async with async_session() as session:
        now = datetime.now(UTC)
        key = await session.one_or_none(
            ApiKey,
            expressions=[
                ApiKey["key_hash"] == token_hash,
                ApiKey["revoked_at"].is_(None),
                ApiKey["expires_at"].is_(None) | (ApiKey["expires_at"] > now),
            ],
        )
        if key is None or scope not in key.scopes:
            return None
        if not isinstance(key, RuntimeApiKey):
            return key
    async with self.lock(f"api-key:{key.user_id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            # SQLite has no row locks; reserve its writer before reading.
            await session.execute(text("BEGIN IMMEDIATE"))
        await session.get(User, key.user_id, with_for_update=True)
        current = await session.get(RuntimeApiKey, key.id)
        now = datetime.now(UTC)
        if (
            current is None
            or current.key_hash != token_hash
            or current.revoked_at is not None
            or (current.expires_at is not None and current.expires_at <= now)
            or scope not in current.scopes
        ):
            return None
        current.expires_at = max(
            current.expires_at or now, now + self.config.runtime_api_key_lifetime
        )
        await session.commit()
        return current

runtime_bearer

runtime_bearer(nonce: UUID7) -> SecretStr

Reproduce a runtime API key without storing its bearer in the database.

Source code in octomate/managers/auth.py
def runtime_bearer(self, nonce: UUID7) -> SecretStr:
    """Reproduce a runtime API key without storing its bearer in the database."""
    digest = hmac.digest(
        self.config.api_key_salt.get_secret_value().encode(),
        b"octomate:runtime-api-key:v1:" + nonce.bytes,
        "sha256",
    ).hex()
    return SecretStr(self.config.api_key_prefix + digest)

runtime_api_key async

runtime_api_key(
    user_id: UUID7,
    *,
    agent_id: str,
    scopes: list[ApiKeyScope],
) -> RuntimeApiKey

Reuse shared persisted state; expiry rotates the bearer, not the key row.

Source code in octomate/managers/auth.py
async def runtime_api_key(
    self, user_id: UUID7, *, agent_id: str, scopes: list[ApiKeyScope]
) -> RuntimeApiKey:
    """Reuse shared persisted state; expiry rotates the bearer, not the key row."""
    scopes = sorted(set(scopes))
    async with self.lock(f"api-key:{user_id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            # SQLite has no row locks; reserve its writer before reading.
            await session.execute(text("BEGIN IMMEDIATE"))
        if await session.get(User, user_id, with_for_update=True) is None:
            raise InvalidCredentials
        key = await session.one_or_none(
            RuntimeApiKey,
            expressions=[
                RuntimeApiKey["user_id"] == user_id,
                RuntimeApiKey["runtime_agent_id"] == agent_id,
            ],
        )
        now = datetime.now(UTC)
        deadline = now + self.config.runtime_api_key_lifetime
        if key is not None and key.revoked_at is not None:
            raise InvalidCredentials
        if (
            key is None
            or key.expires_at is None
            or key.expires_at <= now
            or key.scopes != scopes
        ):
            nonce = uuid7()
        else:
            nonce = key.runtime_nonce
        token = self.runtime_bearer(nonce)
        if (
            key is not None
            and nonce == key.runtime_nonce
            and key.key_hash != self.hash_token(token, self.config.api_key_salt)
        ):
            raise ValueError(
                "Runtime API key does not match this core's auth secrets"
            )
        if key is None:
            key = RuntimeApiKey(
                user_id=user_id,
                scopes=scopes,
                runtime_agent_id=agent_id,
                runtime_nonce=nonce,
                key_hash=self.hash_token(token, self.config.api_key_salt),
                key_prefix=token.get_secret_value()[:12],
            )
            session.add(key)
        key.runtime_nonce = nonce
        key.key_hash = self.hash_token(token, self.config.api_key_salt)
        key.key_prefix = token.get_secret_value()[:12]
        key.scopes = scopes
        key.expires_at = max(key.expires_at or now, deadline)
        await session.commit()
        key.bearer = token
        return key

get_api_key async

get_api_key(user_id: UUID7, key_id: UUID7) -> ApiKey
Source code in octomate/managers/auth.py
async def get_api_key(self, user_id: UUID7, key_id: UUID7) -> ApiKey:
    async with async_session() as session:
        key = await session.get(ApiKey, key_id)
        if key is None or key.user_id != user_id:
            raise InvalidCredentials
        return key

list_api_keys async

list_api_keys(user_id: UUID7) -> list[UserApiKey]
Source code in octomate/managers/auth.py
async def list_api_keys(self, user_id: UUID7) -> list[UserApiKey]:
    async with async_session() as session:
        return list(
            await session.list(
                UserApiKey,
                expressions=[UserApiKey["user_id"] == user_id],
                limit=None,
            )
        )

revoke_api_key async

revoke_api_key(user_id: UUID7, key_id: UUID7) -> None
Source code in octomate/managers/auth.py
async def revoke_api_key(self, user_id: UUID7, key_id: UUID7) -> None:
    async with self.lock(f"api-key:{user_id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            # SQLite has no row locks; reserve its writer before reading.
            await session.execute(text("BEGIN IMMEDIATE"))
        await session.get(User, user_id, with_for_update=True)
        key = await session.get(ApiKey, key_id)
        if key is None or key.user_id != user_id:
            raise InvalidCredentials
        if key.revoked_at is not None:
            return
        key.revoked_at = datetime.now(UTC)
        await session.commit()

register_oauth_client async

register_oauth_client(client: OAuthClient) -> None
Source code in octomate/managers/auth.py
async def register_oauth_client(self, client: OAuthClient) -> None:
    async with async_session() as session:
        session.add(client)
        await session.commit()

get_oauth_client async

get_oauth_client(client_id: UUID7) -> OAuthClient | None
Source code in octomate/managers/auth.py
async def get_oauth_client(self, client_id: UUID7) -> OAuthClient | None:
    async with async_session() as session:
        return await session.get(OAuthClient, client_id)

create_oauth_authorization async

create_oauth_authorization(
    pending: OAuthAuthorization,
) -> None
Source code in octomate/managers/auth.py
async def create_oauth_authorization(self, pending: OAuthAuthorization) -> None:
    async with async_session() as session:
        session.add(pending)
        await session.commit()

get_oauth_code async

get_oauth_code(
    code: SecretStr,
) -> OAuthAuthorization | None
Source code in octomate/managers/auth.py
async def get_oauth_code(self, code: SecretStr) -> OAuthAuthorization | None:
    async with async_session() as session:
        return await session.one_or_none(
            OAuthAuthorization,
            expressions=[
                OAuthAuthorization["code_hash"]
                == self.hash_token(code, self.config.access_token_salt)
            ],
        )

revoke_oauth_token async

revoke_oauth_token(
    client_id: UUID7, bearer: SecretStr
) -> None

Revoke only a token belonging to the requesting public client.

Source code in octomate/managers/auth.py
async def revoke_oauth_token(self, client_id: UUID7, bearer: SecretStr) -> None:
    """Revoke only a token belonging to the requesting public client."""
    async with async_session() as session:
        token = await session.one_or_none(
            OAuthToken,
            expressions=[
                (
                    OAuthToken["access_token_hash"]
                    == self.hash_token(bearer, self.config.access_token_salt)
                )
                | (
                    OAuthToken["refresh_token_hash"]
                    == self.hash_token(bearer, self.config.refresh_token_salt)
                )
            ],
        )
        grant = (
            await session.get(OAuthGrant, token.grant_id)
            if token is not None
            else None
        )
    if grant is not None and grant.client_id == client_id:
        await self.revoke_oauth_grant(grant.user_id, grant.id)

get_oauth_authorization async

get_oauth_authorization(
    ticket: SecretStr,
) -> OAuthAuthorization

Inspect live, undecided consent without issuing credentials.

Source code in octomate/managers/auth.py
async def get_oauth_authorization(self, ticket: SecretStr) -> OAuthAuthorization:
    """Inspect live, undecided consent without issuing credentials."""
    async with async_session() as session:
        pending = await session.one_or_none(
            OAuthAuthorization,
            expressions=[
                OAuthAuthorization["ticket_hash"]
                == self.hash_token(ticket, self.config.access_token_salt)
            ],
        )
    if (
        pending is None
        or pending.expires_at <= datetime.now(UTC)
        or pending.grant_id is not None
    ):
        raise InvalidCredentials
    return pending

deny_oauth_authorization async

deny_oauth_authorization(
    ticket: SecretStr,
) -> OAuthAuthorization

Expire pending consent under the same lock as approval.

Source code in octomate/managers/auth.py
async def deny_oauth_authorization(self, ticket: SecretStr) -> OAuthAuthorization:
    """Expire pending consent under the same lock as approval."""
    pending = await self.get_oauth_authorization(ticket)
    async with self.lock(f"oauth-consent:{pending.id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            await session.execute(text("BEGIN IMMEDIATE"))
        pending = await session.get(
            OAuthAuthorization, pending.id, with_for_update=True
        )
        now = datetime.now(UTC)
        if (
            pending is None
            or pending.expires_at <= now
            or pending.grant_id is not None
        ):
            raise InvalidCredentials
        pending.expires_at = now
        await session.commit()
        return pending

approve_oauth_authorization async

approve_oauth_authorization(
    user_id: UUID7, ticket: SecretStr
) -> OAuthAuthorization

Bind pending consent to the authenticated browser user, once only.

Source code in octomate/managers/auth.py
async def approve_oauth_authorization(
    self, user_id: UUID7, ticket: SecretStr
) -> OAuthAuthorization:
    """Bind pending consent to the authenticated browser user, once only."""
    ticket_hash = self.hash_token(ticket, self.config.access_token_salt)
    async with async_session() as session:
        pending = await session.one_or_none(
            OAuthAuthorization,
            expressions=[OAuthAuthorization["ticket_hash"] == ticket_hash],
        )
    if pending is None:
        raise InvalidCredentials
    async with self.lock(f"oauth-consent:{pending.id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            # SQLite has no row locks; reserve its writer before reading.
            await session.execute(text("BEGIN IMMEDIATE"))
        pending = await session.get(
            OAuthAuthorization, pending.id, with_for_update=True
        )
        now = datetime.now(UTC)
        if (
            pending is None
            or pending.ticket_hash != ticket_hash
            or pending.expires_at <= now
            or pending.grant_id is not None
        ):
            raise InvalidCredentials
        if await session.get(User, user_id) is None:
            raise InvalidCredentials
        client = await session.get(OAuthClient, pending.client_id)
        if client is None:
            raise InvalidCredentials
        if not pending.scopes or not set(pending.scopes) <= set(client.scopes):
            raise InvalidOAuthScopes
        grant = OAuthGrant(
            client_id=client.id,
            user_id=user_id,
            resource=pending.resource,
            scopes=sorted(set(pending.scopes)),
            expires_at=now + self.config.oauth_grant_idle_lifetime,
        )
        session.add(grant)
        await session.flush()
        code = SecretStr(secrets.token_urlsafe(32))
        pending.grant_id = grant.id
        pending.code_hash = self.hash_token(code, self.config.access_token_salt)
        pending.expires_at = min(
            grant.expires_at, now + self.config.oauth_authorization_lifetime
        )
        await session.commit()
        pending.code = code
        return pending

exchange_oauth_code async

exchange_oauth_code(
    client_id: UUID7, code: SecretStr, *, resource: str
) -> OAuthToken

Consume a code after the OAuth handler verifies PKCE and redirect binding.

The protocol handler owns request validation. Reload under the grant lock so expiry, replay, and revocation remain authoritative at issuance.

Source code in octomate/managers/auth.py
async def exchange_oauth_code(
    self, client_id: UUID7, code: SecretStr, *, resource: str
) -> OAuthToken:
    """Consume a code after the OAuth handler verifies PKCE and redirect binding.

    The protocol handler owns request validation. Reload under the grant lock
    so expiry, replay, and revocation remain authoritative at issuance.
    """
    code_hash = self.hash_token(code, self.config.access_token_salt)
    authorization = await self.get_oauth_code(code)
    if authorization is None or authorization.grant_id is None:
        raise InvalidCredentials
    async with (
        self.lock(f"oauth-grant:{authorization.grant_id}"),
        async_session() as session,
    ):
        if session.get_bind().dialect.name == "sqlite":
            await session.execute(text("BEGIN IMMEDIATE"))
        grant = await session.get(
            OAuthGrant, authorization.grant_id, with_for_update=True
        )
        authorization = await session.get(OAuthAuthorization, authorization.id)
        now = datetime.now(UTC)
        if (
            grant is None
            or grant.client_id != client_id
            or grant.resource != resource
            or grant.revoked_at is not None
            or grant.expires_at <= now
            or authorization is None
            or authorization.code_hash != code_hash
        ):
            raise InvalidCredentials
        if authorization.consumed_at is not None:
            grant.revoked_at = now
            await session.commit()
            raise InvalidCredentials
        if authorization.expires_at <= now:
            raise InvalidCredentials
        access = SecretStr(secrets.token_urlsafe(32))
        refresh = SecretStr(secrets.token_urlsafe(32))
        token = OAuthToken(
            grant_id=grant.id,
            access_token_hash=self.hash_token(
                access, self.config.access_token_salt
            ),
            refresh_token_hash=self.hash_token(
                refresh, self.config.refresh_token_salt
            ),
            scopes=grant.scopes,
            access_expires_at=min(
                grant.expires_at, now + self.config.access_token_lifetime
            ),
        )
        authorization.consumed_at = now
        session.add(token)
        await session.commit()
        token.access_token = access
        token.refresh_token = refresh
        return token

refresh_oauth_token async

refresh_oauth_token(
    client_id: UUID7,
    refresh_token: SecretStr,
    *,
    resource: str,
    scopes: list[ApiKeyScope] | None = None,
) -> OAuthToken

Rotate once; replay revokes the entire grant, including newer tokens.

Source code in octomate/managers/auth.py
async def refresh_oauth_token(
    self,
    client_id: UUID7,
    refresh_token: SecretStr,
    *,
    resource: str,
    scopes: list[ApiKeyScope] | None = None,
) -> OAuthToken:
    """Rotate once; replay revokes the entire grant, including newer tokens."""
    token_hash = self.hash_token(refresh_token, self.config.refresh_token_salt)
    async with async_session() as session:
        previous = await session.one_or_none(
            OAuthToken,
            expressions=[OAuthToken["refresh_token_hash"] == token_hash],
        )
    if previous is None:
        raise InvalidCredentials
    async with (
        self.lock(f"oauth-grant:{previous.grant_id}"),
        async_session() as session,
    ):
        if session.get_bind().dialect.name == "sqlite":
            await session.execute(text("BEGIN IMMEDIATE"))
        grant = await session.get(
            OAuthGrant, previous.grant_id, with_for_update=True
        )
        previous = await session.get(OAuthToken, previous.id)
        now = datetime.now(UTC)
        if (
            grant is None
            or grant.client_id != client_id
            or grant.resource != resource
            or grant.revoked_at is not None
            or grant.expires_at <= now
            or previous is None
            or previous.refresh_token_hash != token_hash
        ):
            raise InvalidCredentials
        if previous.refresh_used_at is not None:
            grant.revoked_at = now
            await session.commit()
            raise InvalidCredentials
        allowed = set(previous.scopes) & set(grant.scopes)
        requested = sorted(set(previous.scopes if scopes is None else scopes))
        if not requested or not set(requested) <= allowed:
            raise InvalidOAuthScopes
        grant.expires_at = now + self.config.oauth_grant_idle_lifetime
        access = SecretStr(secrets.token_urlsafe(32))
        refresh = SecretStr(secrets.token_urlsafe(32))
        token = OAuthToken(
            grant_id=grant.id,
            access_token_hash=self.hash_token(
                access, self.config.access_token_salt
            ),
            refresh_token_hash=self.hash_token(
                refresh, self.config.refresh_token_salt
            ),
            scopes=requested,
            access_expires_at=min(
                grant.expires_at, now + self.config.access_token_lifetime
            ),
        )
        previous.refresh_used_at = now
        session.add(token)
        await session.commit()
        token.access_token = access
        token.refresh_token = refresh
        return token

authenticate_oauth_token async

authenticate_oauth_token(
    access_token: SecretStr,
    *,
    resource: str,
    scope: ApiKeyScope,
) -> OAuthPrincipal | None

Check the token and its persisted grant on every resource request.

Source code in octomate/managers/auth.py
async def authenticate_oauth_token(
    self, access_token: SecretStr, *, resource: str, scope: ApiKeyScope
) -> OAuthPrincipal | None:
    """Check the token and its persisted grant on every resource request."""
    async with async_session() as session:
        token = await session.one_or_none(
            OAuthToken,
            expressions=[
                OAuthToken["access_token_hash"]
                == self.hash_token(access_token, self.config.access_token_salt)
            ],
        )
        if token is None:
            return None
        grant = await session.get(OAuthGrant, token.grant_id)
        now = datetime.now(UTC)
        if (
            grant is None
            or grant.resource != resource
            or grant.revoked_at is not None
            or grant.expires_at <= now
            or token.access_expires_at <= now
            or scope not in token.scopes
            or scope not in grant.scopes
        ):
            return None
        return OAuthPrincipal(
            grant_id=grant.id,
            user_id=grant.user_id,
            client_id=grant.client_id,
            resource=grant.resource,
            scopes=sorted(set(token.scopes) & set(grant.scopes)),
            expires_at=min(grant.expires_at, token.access_expires_at),
        )

revoke_oauth_grant async

revoke_oauth_grant(user_id: UUID7, grant_id: UUID7) -> None

Revoke one owned grant without affecting another installation's consent.

Source code in octomate/managers/auth.py
async def revoke_oauth_grant(self, user_id: UUID7, grant_id: UUID7) -> None:
    """Revoke one owned grant without affecting another installation's consent."""
    async with self.lock(f"oauth-grant:{grant_id}"), async_session() as session:
        if session.get_bind().dialect.name == "sqlite":
            await session.execute(text("BEGIN IMMEDIATE"))
        grant = await session.get(OAuthGrant, grant_id, with_for_update=True)
        if grant is None or grant.user_id != user_id:
            raise InvalidCredentials
        if grant.revoked_at is not None:
            return
        grant.revoked_at = datetime.now(UTC)
        await session.commit()