Skip to content
Merged
Show file tree
Hide file tree
Changes from 42 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
b798d57
New Site Toke Forms
gersona Nov 9, 2026
08dc9ba
add site wide token views
gersona Nov 9, 2026
b818227
unit tests
gersona Nov 9, 2026
8e8a26e
documentation update
gersona Nov 9, 2026
688cc5b
add missing title message in heading
gersona Nov 9, 2026
3d643c5
fix circular import
gersona Nov 9, 2026
a01860c
add hard gate to hosed weblate
gersona Nov 9, 2026
d4f6c7a
exclude workspace teams from manaing tokens by default
gersona Nov 9, 2026
6884e73
delete expired token user when expired
gersona Nov 9, 2026
8e730ea
check session validity for token mutation actions
gersona Nov 9, 2026
a542c55
truncate very long bot usernames to match username limit
gersona Nov 9, 2026
14fbf29
fix mypy errors
gersona Nov 9, 2026
e2c5d17
mypy fix
gersona Nov 10, 2026
2fb7f4d
revoke site token before repository cleanup
gersona Nov 10, 2026
ad4096f
exclude site tokens from project-account revocation
gersona Nov 10, 2026
b4af68f
update tests
gersona Nov 10, 2026
e54c53f
infer token prefix from student
gersona Nov 16, 2026
2fe981a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 16, 2026
6e0b392
harden token team edits/revocation
gersona Nov 16, 2026
58fe3e0
handle race condition for bot name uniqueness
gersona Nov 16, 2026
86bdfe2
update documentation
gersona Nov 16, 2026
e8d566e
minor improvements for review comments
gersona Nov 16, 2026
6018e4e
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 16, 2026
7f13ee0
Merge branch 'main' into 19951_site_wide_api
nijel Nov 19, 2026
d4f8266
prevent team admin from removing site token
gersona Nov 20, 2026
41e869c
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 20, 2026
508fd77
Merge branch 'main' into 19951_site_wide_api
nijel Nov 20, 2026
c099435
record team-assignment bot as actor of site removal
gersona Nov 22, 2026
f4e0913
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 22, 2026
8a3fa30
Apply suggestion from @nijel
nijel Nov 23, 2026
236882f
fix template filter
gersona Nov 25, 2026
47ba1a5
match case insensitively in is_site_api_token_bot
gersona Nov 25, 2026
9686a08
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 25, 2026
f54a279
serialize concurrent site token team edits
gersona Nov 25, 2026
de804a6
Merge branch 'main' into 19951_site_wide_api
nijel Nov 26, 2026
ab1ee72
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 26, 2026
3dcb106
mypy error fix
gersona Nov 26, 2026
256b838
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 26, 2026
b059255
Merge branch 'main' into 19951_site_wide_api
nijel Nov 26, 2026
f663017
resume create/delete/edit token actions after reauthentication
gersona Nov 26, 2026
9084e8f
reject api token at authentication time
gersona Nov 26, 2026
eac7dfa
only allow site api token changes from interface
gersona Nov 26, 2026
f00958b
minor test tweak
gersona Nov 27, 2026
4479939
Merge remote-tracking branch 'upstream/main' into 19951_site_wide_api
gersona Nov 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/admin/access.rst
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,42 @@ workspace owners.

* :ref:`api-tokens`
* :ref:`expiring-accounts`
* :ref:`site-api-tokens`

.. _site-api-tokens:

Site-wide API tokens
++++++++++++++++++++

.. versionadded:: 2026.12

.. note::

This feature is unavailable on Hosted Weblate.

Site administrators can create site-wide API tokens in the
:ref:`management-interface` under :guilabel:`API tokens`. These credentials are
intended for instance-level automation such as scraping
:http:get:`/api/metrics/`.

Every token must belong to at least one site-wide team, chosen when the token is
created and adjustable later from the pencil dialog. The built-in `Users` team
can act on public projects; it is not preselected. For metrics-only access,
create a site-wide team with no roles (for example `Monitoring`) and assign the
token to it. :http:get:`/api/metrics/` returns whole-server counts and is not
limited by team membership.

Token keys use the ``wls_`` prefix. The secret is shown once after creation. To
replace a leaked secret, delete the token and create another. Deleting the
underlying user account also revokes the token. Once the expiry date passes, the
scheduled background task removes the token the same way as deleting it from the
management interface.

.. seealso::

* :ref:`api-tokens`
* :ref:`project-api`
* :ref:`expiring-accounts`

.. _custom-acl:

Expand Down
10 changes: 10 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -145,16 +145,26 @@ Authentication tokens

Project scoped tokens were introduced in the 4.10 release.

.. versionchanged:: 2026.12

Site-wide API tokens were introduced in the 2026.12 release.

Each user has a personal access token which can be obtained in the user
profile. Newly generated user tokens have the ``wlu_`` prefix.

It is possible to create project scoped tokens for API access to given project
only. These tokens can be identified by the ``wlp_`` prefix.

Site administrators can create site-wide tokens in the management interface.
These tokens have the ``wls_`` prefix, must belong to at least one site-wide
team, and are unavailable on Hosted Weblate. For metrics-only monitoring, assign
the token to a site-wide team with no roles.

.. seealso::

* :doc:`/user/profile`
* :ref:`project-api`
* :ref:`site-api-tokens`
* :ref:`acl`

Authentication examples
Expand Down
1 change: 1 addition & 0 deletions docs/changes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Weblate 2026.12

.. rubric:: New features

* Added :ref:`site-wide API tokens <site-api-tokens>` in the management interface for instance-level automation such as :http:get:`/api/metrics/` scraping. Unavailable on Hosted Weblate.
* Added :ref:`ranked contributor lists <contributor-rankings>` for languages, workspaces, projects, categories, components, and translations.
* Added a :ref:`plain-text XLIFF download <download>` for editing markup in external translation tools.
* Added an option to sort languages by translation percentage in language bar chart widgets.
Expand Down
31 changes: 29 additions & 2 deletions docs/security/threat-model.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ feature inventory. *(maintainer)*
- Same application effects as the token permissions allow
- In scope as authenticated actors with delegated project scope.
*(documented)* (source: :doc:`/api`, :doc:`/admin/access`)
* - Site-wide API tokens
- Tokens created in management :guilabel:`API tokens`
- Same application effects as the token's site-wide team permissions allow.
:http:get:`/api/metrics/` returns whole-server counts for any authenticated token.
- In scope as authenticated actors with delegated site-wide team scope.
Unavailable on Hosted Weblate.
*(documented)* (source: :doc:`/api`, :doc:`/admin/access`)
* - Webhooks
- :ref:`hooks`, project :ref:`project-enable_hooks`,
:ref:`code-hosting-github-app-webhook`
Expand Down Expand Up @@ -701,6 +708,13 @@ Adversary model
:ref:`projectbackup`)
- Access projects, components, or site-wide functions outside its scope.
*(documented)* (source: :doc:`/admin/access`)
* - Site-wide API token holder
- Use API permissions assigned to its site-wide team memberships.
:http:get:`/api/metrics/` returns whole-server counts and is not limited
by team membership.
*(documented)* (source: :doc:`/api`, :ref:`site-api-tokens`)
- Act outside assigned team permissions without exploiting a Weblate flaw.
*(documented)* (source: :doc:`/admin/access`)
* - Webhook sender
- Send forged, replayed, malformed, or high-volume webhook requests to
enabled hook endpoints and observe documented matching diagnostics.
Expand Down Expand Up @@ -834,15 +848,28 @@ Security properties Weblate provides
- A scoped automatic assignment grants membership without acceptance.
- Security-critical. Pending invitations remain visible to team managers,
and matching rules can send unsolicited invitation e-mails.
* - Site-wide API tokens use assigned site-wide team permissions for scoped
API operations. :http:get:`/api/metrics/` returns whole-server counts
and is not limited by team membership. Tokens are managed only from the
management interface.
*(documented)* (source: :doc:`/api`, :ref:`site-api-tokens`)
- Token is created, revoked, or has team membership changed from the
browser by a site administrator with ``user.edit`` after recent
credential verification. Accounts with 2FA use a second factor; other
accounts confirm their password or an existing sign-in provider.
- Token can act outside assigned team scope, or tokens can be managed
without ``user.edit``, or a stale browser session can create, revoke, or
alter site-wide tokens without recent credential verification.
- Security-critical.
* - Authentication and session controls protect browser sessions when HTTPS
and proxy settings are correct. Pending second-factor sessions are bound
to the current password authentication state, and repeated rejected
second-factor submissions lock password sign-in according to
:setting:`AUTH_LOCK_ATTEMPTS`. Password and second-factor verification
for the same account are serialized so concurrent requests cannot
continue verifying against credentials or pending sessions invalidated
by the lockout. Access to personal API tokens and
changes to authentication credentials, access permissions, project
by the lockout. Access to personal API tokens, creation and revocation of site-wide API tokens, and changes to site-wide
token team membership, changes to authentication credentials, access permissions, project
and component visibility, account status, and bulk user-contribution
cleanup require recent credential verification for browser sessions.
Reading full translation service configurations and changing installations
Expand Down
14 changes: 10 additions & 4 deletions docs/specs/openapi.yaml

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

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2110,7 +2110,7 @@ max-complexity = 16 # TODO: should be lower
"missing-return-type-undocumented-public-function",
"missing-type-function-argument"
]
"weblate/wladmin/tests.py" = [
"weblate/wladmin/tests/*" = [
"missing-return-type-private-function",
"missing-return-type-undocumented-public-function",
"missing-type-function-argument",
Expand Down
76 changes: 72 additions & 4 deletions weblate/accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import json
import struct
from datetime import UTC, datetime, timedelta
from secrets import token_hex
from typing import TYPE_CHECKING, ClassVar, cast

from altcha import Payload, create_challenge, verify_solution
Expand All @@ -17,13 +18,14 @@
from django.contrib.auth import authenticate, password_validation
from django.contrib.auth.forms import SetPasswordForm as DjangoSetPasswordForm
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.db.models.fields import BLANK_CHOICE_DASH
from django.db import IntegrityError, transaction
from django.db.models import BLANK_CHOICE_DASH, Q
from django.forms import Script
from django.forms.utils import ErrorDict
from django.http import Http404
from django.middleware.csrf import rotate_token
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.html import escape, format_html
from django.utils.translation import (
Expand Down Expand Up @@ -54,28 +56,31 @@
from weblate.accounts.notifications import NOTIFICATIONS
from weblate.accounts.utils import (
adjust_session_expiry,
bound_bot_basename,
cycle_session_keys,
get_all_user_mails,
get_totp_device_label,
invalidate_reset_codes,
reset_api_token,
)
from weblate.auth.models import Group, User
from weblate.auth.models import BOT_NOREPLY_EMAIL_SUFFIX, Group, User
from weblate.lang.forms import LimitLanguagesField, get_language_code_choices
from weblate.lang.models import Language
from weblate.logger import LOGGER
from weblate.trans.defines import FULLNAME_LENGTH
from weblate.trans.forms import FieldDocsMixin
from weblate.trans.models import Category, Component, Project, Translation
from weblate.utils import messages
from weblate.utils.forms import (
ContextDiv,
EmailField,
FieldDocsMixin,
QueryField,
SearchableSelect,
SortedSelect,
SortedSelectMultiple,
UserField,
UsernameField,
WeblateDateInput,
)
from weblate.utils.ratelimit import (
check_rate_limit,
Expand Down Expand Up @@ -939,6 +944,16 @@ def save(self, request: AuthenticatedHttpRequest, delete_session=False) -> None:
messages.success(request, gettext("Your password has been changed."))


class UserManageForm(forms.Form):
user = UserField(
label=gettext_lazy("User to add"),
required=True,
help_text=gettext_lazy(
"Please type in an existing Weblate account name or e-mail address."
),
)


class EmptyConfirmForm(forms.Form):
def __init__(self, request: AuthenticatedHttpRequest, *args, **kwargs) -> None:
self.request = request
Expand Down Expand Up @@ -1604,3 +1619,56 @@ def clean_notification_target(self):
raise forms.ValidationError(
gettext("The target does not exist or you cannot access it.")
) from error


# A concurrent create can pass the availability check and then lose the insert.
BOT_USERNAME_ALLOCATION_ATTEMPTS = 5


class BaseTokenCreateForm(forms.ModelForm):
class Meta:
model = User
# ruff: ignore[mutable-class-default]
fields = ["full_name", "date_expires"]
# ruff: ignore[mutable-class-default]
widgets = {
"date_expires": WeblateDateInput(),
}

def clean_date_expires(self):
expires = self.cleaned_data["date_expires"]
if expires is None:
return expires
expires = expires.replace(hour=23, minute=59, second=59, microsecond=999999)
if expires < timezone.now():
raise ValidationError(gettext("Expiry cannot be in the past."))
return expires

def save(self, *args, acting_user: User | None = None, **kwargs):
self.instance.is_bot = True
base_name = bound_bot_basename(self.get_bot_basename())
name = base_name
error: IntegrityError | None = None
for _attempt in range(BOT_USERNAME_ALLOCATION_ATTEMPTS):
while User.objects.filter(
Q(username=name) | Q(email=f"{name}{BOT_NOREPLY_EMAIL_SUFFIX}")
).exists():
name = f"{base_name}-{token_hex(2)}"
self.instance.username = name
self.instance.email = f"{name}{BOT_NOREPLY_EMAIL_SUFFIX}"
try:
# Savepoint so a uniqueness conflict does not abort the caller.
with transaction.atomic():
return super().save(*args, **kwargs)
except IntegrityError as exc:
self.instance.pk = None
name = f"{base_name}-{token_hex(2)}"
error = exc
if error is not None:
raise error
msg = "Could not allocate a unique bot username"
raise IntegrityError(msg)

def get_bot_basename(self) -> str:
msg = "Subclasses must implement this method"
raise NotImplementedError(msg)
6 changes: 6 additions & 0 deletions weblate/accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,12 @@
# Translators: Audit log entry
"password": gettext_lazy("Password configured."),
},
"site": {
# Translators: Audit log entry
"token-created": gettext_lazy("Site-wide API token was created."),
# Translators: Audit log entry
"token-removed": gettext_lazy("Site-wide API token was removed."),
},
}

EXTRA_MESSAGES = {
Expand Down Expand Up @@ -1582,7 +1588,7 @@
):
email = self.get_site_commit_email()
if not email:
email = self.user.email

Check failure on line 1591 in weblate/accounts/models.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible types in assignment (expression has type "str | None", variable has type "str")
return email

def get_site_commit_email(self) -> str:
Expand Down Expand Up @@ -1618,7 +1624,7 @@
]
if site_name:
name_choices.append((Profile.CommitNameChoices.PRIVATE, site_name))
return name_choices

Check failure on line 1627 in weblate/accounts/models.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible return value type (got "list[tuple[CommitNameChoices, Reversible[Any]]]", expected "list[tuple[CommitNameChoices, str | _StrPromise]]")

def get_commit_email_choices(self) -> list[tuple[str, StrOrPromise]]:
# ruff: ignore[import-outside-top-level]
Expand All @@ -1632,7 +1638,7 @@

if site_commit_email := self.get_site_commit_email():
if not settings.PRIVATE_COMMIT_EMAIL_OPT_IN:
choices = [("", site_commit_email)]

Check failure on line 1641 in weblate/accounts/models.py

View workflow job for this annotation

GitHub Actions / mypy

List item 0 has incompatible type "tuple[str, str]"; expected "tuple[str, _StrPromise]"
else:
commit_emails.add(site_commit_email)

Expand Down
Loading
Loading