Compare commits

..
Author SHA1 Message Date
Jens Langhammer ceeb1c2273 migrate in job
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 14:01:43 +01:00
Jens Langhammer 1d1ec163d4 fixup
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 14:01:43 +01:00
Jens Langhammer 6e7f4b69cd fixup
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:35:24 +01:00
Jens Langhammer 167f4bb7ab same dockerfile as outposts
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:35:24 +01:00
Jens Langhammer ae07de82b6 cleanup
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:35:24 +01:00
Jens Langhammer dad20b3ceb remove header
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:35:24 +01:00
Jens Langhammer 0562956eb6 cleanup
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:35:24 +01:00
Jens Langhammer 7b1378fd91 snap
Signed-off-by: Jens Langhammer <[email protected]>

# Conflicts:
#	go.mod
#	go.sum
2026-09-15 13:35:24 +01:00
Jens Langhammer 2d2e59a6b9 add build and release
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 13:06:17 +01:00
Jens Langhammer 36ac41880d match helm version
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:48:08 +01:00
Jens Langhammer 55bfdeae89 trim newline in current ver
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:47:20 +01:00
Jens Langhammer 4f0f81cb21 helm bump
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:47:14 +01:00
Jens Langhammer 9c633e38ff testing
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:38:04 +01:00
Jens Langhammer 1b0067d916 no fetch depth
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:30:17 +01:00
Jens Langhammer e448c33987 add CI and license
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:29:02 +01:00
Jens Langhammer 81e4a02950 move config, etc
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:19:54 +01:00
Jens Langhammer 954175da17 lifecycle/charts: init
Signed-off-by: Jens Langhammer <[email protected]>
2026-09-15 12:14:15 +01:00
3391 changed files with 219662 additions and 77855 deletions

No files matched your search

@@ -0,0 +1,57 @@
name: "Comment usage instructions on PRs"
description: "Comment usage instructions on PRs"
inputs:
tag:
description: "Image tag to pull"
required: true
runs:
using: "composite"
steps:
- name: Find Comment
uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v2
id: fc
with:
issue-number: ${{ github.event.pull_request.number }}
comment-author: "github-actions[bot]"
body-includes: authentik PR Installation instructions
- name: Create or update comment
uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v2
with:
comment-id: ${{ steps.fc.outputs.comment-id }}
issue-number: ${{ github.event.pull_request.number }}
body: |
authentik PR Installation instructions
<details>
<summary>Instructions for docker-compose</summary>
Add the following block to your `.env` file:
```shell
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
AUTHENTIK_TAG=${{ inputs.tag }}
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
```
Afterwards, run the upgrade commands from the latest release notes.
</details>
<details>
<summary>Instructions for Kubernetes</summary>
Add the following block to your `values.yml` file:
```yaml
authentik:
outposts:
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
global:
image:
repository: ghcr.io/goauthentik/dev-server
tag: ${{ inputs.tag }}
```
Afterwards, run the upgrade commands from the latest release notes.
</details>
edit-mode: replace
-41
View File
@@ -1,41 +0,0 @@
---
name: "Comment on PR"
description: "Upserts one section of the shared CI comment on a pull request"
inputs:
section:
description: "Slug of the section to replace. Every other section is left alone."
required: true
body:
description: "Markdown for the section"
runs:
using: "composite"
steps:
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
env:
SECTION: "${{ inputs.section }}"
BODY: "${{ inputs.body }}"
with:
script: |
const marker = "<!-- ci-comment -->";
const { SECTION, BODY } = process.env;
const issue = { ...context.repo, issue_number: context.issue.number };
// Every CI job writes into the same comment, so find it by its marker and splice in
// only this job's section, leaving the sections other jobs own untouched.
// ponytail: read-modify-write, so two jobs finishing at the same instant can drop one
// section update; the next push rewrites it. Retry on a changed body if that bites.
const comments = await github.paginate(github.rest.issues.listComments, issue);
const existing = comments.find(({ body }) => body?.startsWith(marker));
const section = new RegExp(`<!-- section:${SECTION} -->[\\s\\S]*?<!-- /section:${SECTION} -->`);
const block = `<!-- section:${SECTION} -->\n${BODY.trim()}\n<!-- /section:${SECTION} -->`;
const previous = existing?.body?.trim() || marker;
const body = section.test(previous)
? previous.replace(section, () => block)
: `${previous}\n\n${block}`;
await (existing
? github.rest.issues.updateComment({ ...issue, comment_id: existing.id, body })
: github.rest.issues.createComment({ ...issue, body }));
@@ -35,7 +35,7 @@ runs:
branch_name = os.environ["GITHUB_REF"]
if os.environ.get("GITHUB_HEAD_REF", "") != "":
branch_name = os.environ["GITHUB_HEAD_REF"]
safe_branch_name = re.sub(r"[^a-zA-Z0-9-.]", "-", branch_name.replace("refs/heads/", ""))
safe_branch_name = re.sub(r"[^a-zA-Z0-9-]", "-", branch_name.replace("refs/heads/", ""))
tag_full = f"gh-{sha}"
tag_branch = f"gh-{safe_branch_name}"
+3 -6
View File
@@ -42,7 +42,7 @@ runs:
sudo rsync -a --delete /tmp/empty/ /usr/local/lib/android/
- name: Install uv
if: ${{ contains(inputs.dependencies, 'python') }}
uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v5
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v5
with:
enable-cache: true
- name: Setup python
@@ -69,7 +69,7 @@ runs:
rustflags: ""
- name: Setup rust dependencies
if: ${{ contains(inputs.dependencies, 'rust') }}
uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2
uses: taiki-e/install-action@3f74d7c16a4242f1c95561e98edc25d36adb4375 # v2
with:
tool: cargo-deny cargo-machete cargo-llvm-cov nextest
- name: Setup pnpm
@@ -85,7 +85,7 @@ runs:
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- name: Setup node (root, web)
if: ${{ contains(inputs.dependencies, 'node') }}
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: ${{ inputs.working-directory }}package.json
cache: pnpm
@@ -107,9 +107,6 @@ runs:
cache-dependency-path: "${{ inputs.working-directory }}go.mod"
- name: Setup docker cache
if: ${{ contains(inputs.dependencies, 'runtime') }}
# The post step `docker save`s every new image, but digest-pinned images (e2e,
# kind) list without a tag and fail. Jobs share the key, so another job saves it.
continue-on-error: true
uses: AndreKurait/docker-cache@7a3887908bdb97935395833df69b060cfcca0f7f
with:
key: docker-images-${{ runner.os }}-${{ hashFiles('.github/actions/setup/compose.yml', 'Makefile') }}-${{ inputs.postgresql_version }}
+2 -2
View File
@@ -10,12 +10,12 @@ inputs:
runs:
using: "composite"
steps:
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v5
with:
files: ${{ inputs.files }}
flags: ${{ inputs.flags }}
use_oidc: true
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v5
with:
files: ${{ inputs.files }}
flags: ${{ inputs.flags }}
+64 -56
View File
@@ -8,7 +8,7 @@ updates:
# Required to update composite actions
# https://github.com/dependabot/dependabot-core/issues/6704
- /.github/actions/setup
- /.github/actions/comment-pr
- /.github/actions/comment-pr-instructions
- /.github/actions/test-results
schedule:
interval: daily
@@ -95,17 +95,13 @@ updates:
#endregion
#region Web & Documentation
#region Web
# One entry for every workspace root that shares the pnpm catalog pins, so a
# group bump lands in all of them in a single PR. Groups don't span entries,
# and `scripts/node/lint-catalogs.ts` fails when the roots drift apart.
- package-ecosystem: npm
directories:
- "/"
- "/web"
- "/web/packages/*"
- "/website"
schedule:
interval: daily
time: "04:00"
@@ -126,20 +122,13 @@ updates:
patterns:
- "@babel/*"
- "babel-*"
oxc:
eslint:
patterns:
- "@oxc-project/*"
- "oxc-*"
- "oxfmt"
- "oxlint"
lint:
patterns:
# Rule sources for @goauthentik/oxlint-config; oxlint reads their rule
# definitions, so they move in lockstep with it.
- "eslint-plugin-lit"
- "eslint-plugin-wc"
- "stylelint"
- "stylelint-*"
- "@eslint/*"
- "@typescript-eslint/*"
- "eslint-*"
- "eslint"
- "typescript-eslint"
storybook:
patterns:
- "@storybook/*"
@@ -159,17 +148,6 @@ updates:
patterns:
- "@swc/*"
- "swc-*"
# Listed before `goauthentik` so the config package moves with Docusaurus.
docusaurus:
patterns:
- "@docusaurus/*"
- "@goauthentik/docusaurus-config"
- "docusaurus-plugin-openapi-docs"
- "docusaurus-theme-openapi-docs"
website-build:
patterns:
- "lightningcss*"
- "@rspack/binding*"
goauthentik:
patterns:
- "@goauthentik/*"
@@ -186,15 +164,12 @@ updates:
- package-ecosystem: npm
directories:
- "/packages/docusaurus-config"
- "/packages/esbuild-plugin-live-reload"
- "/packages/fonts"
- "/packages/geo"
- "/packages/logger-js"
- "/packages/oxfmt-config"
- "/packages/oxlint-config"
- "/packages/theme"
- "/packages/prettier-config"
- "/packages/tsconfig"
- "/packages/docusaurus-config"
- "/packages/eslint-config"
- "/packages/logger-js"
- "/packages/esbuild-plugin-live-reload"
schedule:
interval: daily
time: "04:00"
@@ -215,20 +190,13 @@ updates:
patterns:
- "@babel/*"
- "babel-*"
oxc:
eslint:
patterns:
- "@oxc-project/*"
- "oxc-*"
- "oxfmt"
- "oxlint"
lint:
patterns:
# Rule sources for @goauthentik/oxlint-config; oxlint reads their rule
# definitions, so they move in lockstep with it.
- "eslint-plugin-lit"
- "eslint-plugin-wc"
- "stylelint"
- "stylelint-*"
- "@eslint/*"
- "@typescript-eslint/*"
- "eslint-*"
- "eslint"
- "typescript-eslint"
storybook:
patterns:
- "@storybook/*"
@@ -260,7 +228,51 @@ updates:
#endregion
#region AWS Lifecycle
# #region Documentation
- package-ecosystem: npm
directory: "/website"
schedule:
interval: daily
time: "04:00"
open-pull-requests-limit: 10
commit-message:
prefix: "website:"
labels:
- dependencies
cooldown:
default-days: 7
semver-major-days: 14
semver-patch-days: 3
groups:
docusaurus:
patterns:
- "@docusaurus/*"
- "@goauthentik/docusaurus-config"
- "docusaurus-plugin-openapi-docs"
- "docusaurus-theme-openapi-docs"
build:
patterns:
- "@swc/*"
- "swc-*"
- "lightningcss*"
- "@rspack/binding*"
goauthentik:
patterns:
- "@goauthentik/eslint-config"
- "@goauthentik/prettier-config"
- "@goauthentik/tsconfig"
eslint:
patterns:
- "@eslint/*"
- "@typescript-eslint/*"
- "eslint-*"
- "eslint"
- "typescript-eslint"
#endregion
# AWS Lifecycle
- package-ecosystem: npm
directory: "/lifecycle/aws"
@@ -329,10 +341,6 @@ updates:
- dependencies
cooldown:
default-days: 3
groups:
pnpm:
patterns:
- "*pnpm/pnpm"
- package-ecosystem: docker-compose
directories:
- /packages/client-go
-5
View File
@@ -1,5 +0,0 @@
version: "2"
linters:
exclusions:
paths:
- '(^|/)node_modules/'
-42
View File
@@ -15,45 +15,3 @@ git:
source_file: locale/en/LC_MESSAGES/django.po
# path expression to translation files, must contain <lang> placeholder
translation_files_expression: "locale/<lang>/LC_MESSAGES/django.po"
settings:
# Generated from locales.yaml by `make gen-locales`. Do not edit by hand.
language_mapping:
ar_AA: ar
bg_BG: bg-BG
bn_BD: bn-BD
ca_ES: ca-ES
cs_CZ: cs-CZ
sk_SK: sk-SK
cy_GB: cy-GB
da_DK: da-DK
de_DE: de-DE
el_GR: el-GR
es_ES: es-ES
eu_ES: eu-ES
fa_IR: fa-IR
fi_FI: fi-FI
fr_FR: fr-FR
gl_ES: gl-ES
hr_HR: hr-HR
hu_HU: hu-HU
it_IT: it-IT
ja_JP: ja-JP
ka_GE: ka-GE
ko_KR: ko-KR
lt_LT: lt-LT
lv_LV: lv-LV
ms_MY: ms-MY
no_NO: nb-NO
nl_NL: nl-NL
pl_PL: pl-PL
pt_BR: pt-BR
pt_PT: pt-PT
ro_RO: ro-RO
ru_RU: ru-RU
sl_SI: sl-SI
sv_SE: sv-SE
th_TH: th-TH
tr_TR: tr-TR
uk_UA: uk-UA
vi_VN: vi-VN
@@ -60,8 +60,8 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
ref: "${{ inputs.ref }}"
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
- uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4.3.0
- uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- if: "${{ inputs.should-cache }}"
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
@@ -69,7 +69,7 @@ jobs:
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: build
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
# inputs
context: .
@@ -91,7 +91,7 @@ jobs:
# params
platforms: "linux/${{ inputs.image-arch }}"
- id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: "container-build-${{ inputs.image-name }}-${{ inputs.image-arch }}"
path: build/
@@ -34,7 +34,7 @@ jobs:
uses: ./.github/workflows/_reusable-container-build-single.yml
secrets: inherit
with:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
ref: "${{ inputs.ref }}"
image-name: "${{ inputs.image-name }}"
image-arch: amd64
@@ -47,7 +47,7 @@ jobs:
uses: ./.github/workflows/_reusable-container-build-single.yml
secrets: inherit
with:
runs-on: ubuntu-26.04-arm
runs-on: ubuntu-24.04-arm
ref: "${{ inputs.ref }}"
image-name: "${{ inputs.image-name }}"
image-arch: arm64
@@ -57,13 +57,13 @@ jobs:
cache-suffix: "${{ inputs.cache-suffix }}"
merge:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
needs:
- build-amd64
- build-arm64
steps:
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
- uses: regclient/actions/regctl-installer@bb562fac724b7b37c17f19671df07fe34fabc376
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
artifact-ids: "${{ needs.build-amd64.outputs.artifact-id }},${{ needs.build-arm64.outputs.artifact-id }}"
merge-multiple: true
@@ -229,10 +229,10 @@ jobs:
"${target}" \
"build/container/${image_name}.oci.tar"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: "container-build-${{ inputs.image-name }}"
path: build/
if-no-files-found: error
retention-days: 2
include-hidden-files: true
include-hidden-files: true
+9 -9
View File
@@ -18,12 +18,12 @@ concurrency:
jobs:
lint:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
command:
- check
- prettier-check
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
@@ -31,7 +31,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -45,7 +45,7 @@ jobs:
- name: Lint
run: pnpm --dir website run ${{ matrix.command }}
build:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -54,7 +54,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -79,19 +79,19 @@ jobs:
env:
NODE_ENV: production
run: pnpm run build:api
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: api-docs
path: website/api/build
retention-days: 7
deploy:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
needs:
- lint
- build
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
name: api-docs
path: website/api/build
@@ -100,7 +100,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
+3 -3
View File
@@ -23,7 +23,7 @@ env:
jobs:
check-changes-applied:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
@@ -33,7 +33,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -48,7 +48,7 @@ jobs:
if: always()
needs:
- check-changes-applied
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
+2 -2
View File
@@ -13,7 +13,7 @@ env:
jobs:
publish-source-docs:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -22,7 +22,7 @@ jobs:
- name: generate docs
run: |
uv run make migrate
uv run python -m manage build_source_docs
uv run ak build_source_docs
- uses: nwtgck/actions-netlify@d22a32a27c918fe470bbc562e984f80ec48c2668 # v4.0.0
id: netlify
with:
+12 -12
View File
@@ -18,14 +18,14 @@ concurrency:
jobs:
lint:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
env:
NODE_ENV: production
strategy:
fail-fast: false
matrix:
command:
- check
- prettier-check
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
@@ -33,7 +33,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -47,7 +47,7 @@ jobs:
- name: Lint
run: pnpm --dir website run ${{ matrix.command }}
build-docs:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
env:
NODE_ENV: production
steps:
@@ -57,7 +57,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
name: Setup Node.js
with:
node-version-file: package.json
@@ -72,7 +72,7 @@ jobs:
- name: Build Documentation via Docusaurus
run: pnpm --dir website run build
build-integrations:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
env:
NODE_ENV: production
steps:
@@ -82,7 +82,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -96,7 +96,7 @@ jobs:
- name: Build Integrations via Docusaurus
run: pnpm --dir website run build:integrations
build-container:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
# Needed to upload container images to ghcr.io
packages: write
@@ -111,9 +111,9 @@ jobs:
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Set up QEMU
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4.3.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- name: Login to Container Registry
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
@@ -122,7 +122,7 @@ jobs:
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build Docker Image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
file: website/Dockerfile
context: .
@@ -141,7 +141,7 @@ jobs:
- build-docs
- build-integrations
- build-container
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
+113
View File
@@ -0,0 +1,113 @@
---
name: CI - Lifecycle
on:
push:
branches:
- main
- next
- version-*
pull_request:
branches:
- main
- version-*
concurrency:
group: "${{ github.workflow }}-${{ github.ref }}"
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
jobs:
helm-linter-artifacthub:
runs-on: ubuntu-latest
container:
image: public.ecr.aws/artifacthub/ah:v1.23.0
options: --user 1001
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Run ah lint
working-directory: ./lifecycle/charts
run: ah lint
helm-lint-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
fetch-depth: 0
filter: blob:none
- name: Set up Helm
uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5
- uses: ./.github/actions/setup
with:
dependencies: "python"
- name: Setup Chart Linting
id: lint
uses: helm/chart-testing-action@6ec842c01de15ebb84c8627d2744a0c2f2755c9f # v2.8.0
- name: List changed charts
id: list-changed
run: |
changed=$(ct --config ./lifecycle/charts/ct-lint.yaml list-changed)
charts=$(echo "$changed" | tr '\n' ' ' | xargs)
if [[ -n "$changed" ]]; then
echo "changed=true" >> $GITHUB_OUTPUT
echo "changed_charts=$charts" >> $GITHUB_OUTPUT
fi
- name: Run chart-testing (lint)
run: ct lint --debug --config ./lifecycle/charts/ct-lint.yaml --lint-conf ./lifecycle/charts/lintconf.yaml
- name: Run docs-testing (helm-docs)
id: helm-docs
run: |
make helm-docs
if [[ $(git diff --stat) != '' ]]; then
echo -e '\033[0;31mDocumentation outdated!\033[0m ❌'
git diff --color
exit 1
else
echo -e '\033[0;32mDocumentation up to date\033[0m ✔'
fi
- name: Create kind cluster
uses: helm/kind-action@06c1ae10762d3b9c1644e7fe69596ae519e015a2 # v1.15.0
if: ${{ steps.list-changed.outputs.changed == 'true' }}
- name: Run chart-testing (install)
run: |
namespace=authentik-$(uuidgen)
kubectl create ns $namespace
kubectl apply -n $namespace -f lifecycle/charts/authentik/ci/manifests/
ct install --namespace=$namespace --config ./lifecycle/charts/ct-install.yaml
if: ${{ steps.list-changed.outputs.changed == 'true' }}
helm-build:
strategy:
fail-fast: false
matrix:
include:
- name: authentik
- name: authentik-remote-cluster
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Set up Helm
uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5
- env:
CHART_NAME: ${{ matrix.name }}
run: |
mkdir build
helm package -u "lifecycle/charts/${CHART_NAME}" -d build
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: "helm-build-${{ matrix.name }}"
path: build/
if-no-files-found: error
retention-days: 2
include-hidden-files: true
ci-lifecycle-mark:
if: always()
needs:
- helm-linter-artifacthub
- helm-lint-and-test
- helm-build
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
jobs: ${{ toJSON(needs) }}
+1 -1
View File
@@ -13,7 +13,7 @@ on:
jobs:
test-container:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
+25 -185
View File
@@ -29,7 +29,7 @@ permissions:
jobs:
build-compute-tags:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
outputs:
safe-branch-name: "${{ steps.compute-tags.outputs.safe-branch-name }}"
tag-full: "${{ steps.compute-tags.outputs.tag-full }}"
@@ -84,10 +84,6 @@ jobs:
deps: node
- job: catalogs
deps: node
- job: locales
deps: python
- job: oxlint-fixtures
deps: node
- job: pending-migrations
deps: python,runtime
- job: ruff
@@ -102,7 +98,7 @@ jobs:
deps: rust
- job: rustfmt
deps: rust-nightly
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
@@ -118,7 +114,7 @@ jobs:
- name: run job
run: make ci-lint-${{ matrix.job }}
test-gen:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
@@ -134,7 +130,7 @@ jobs:
- name: ensure schema is up-to-date
run: git diff --exit-code -- schema.yml blueprints/schema.json packages/client-go packages/client-rust packages/client-ts
test-migrations:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
@@ -142,7 +138,7 @@ jobs:
- name: run migrations
run: uv run python -m lifecycle.migrate
test-make-seed:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: seed
run: |
@@ -151,7 +147,7 @@ jobs:
seed: ${{ steps.seed.outputs.seed }}
test-migrations-from-stable:
name: test-migrations-from-stable - PostgreSQL ${{ matrix.psql }} - Run ${{ matrix.run_id }}/10
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
needs: test-make-seed
strategy:
@@ -234,7 +230,7 @@ jobs:
flags: unit-migrate
test-unittest:
name: test-unittest - PostgreSQL ${{ matrix.psql }} - Run ${{ matrix.run_id }}/10
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
needs: test-make-seed
strategy:
@@ -262,14 +258,14 @@ jobs:
with:
flags: unit
test-integration:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
uses: ./.github/actions/setup
- name: Create k8s Kind Cluster
uses: helm/kind-action@1544676c07bb3570fcb70166beaa07c4528fd4aa # v1.15.1
uses: helm/kind-action@06c1ae10762d3b9c1644e7fe69596ae519e015a2 # v1.15.0
- name: run integration
run: |
uv run coverage run manage.py test tests/integration
@@ -281,7 +277,7 @@ jobs:
flags: integration
test-e2e:
name: test-e2e (${{ matrix.job.name }})
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
needs:
- build-compute-tags
@@ -321,7 +317,7 @@ jobs:
glob: tests/e2e/test_endpoints_*
profiles: selenium
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
pattern: container-build-*-amd64
merge-multiple: true
@@ -345,7 +341,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -378,7 +374,7 @@ jobs:
flags: e2e
test-openid-conformance:
name: test-openid-conformance (${{ matrix.job.name }})
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
@@ -433,12 +429,12 @@ jobs:
with:
flags: conformance
- if: ${{ !cancelled() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: conformance-certification-${{ matrix.job.name }}
path: tests/openid_conformance/exports/
test-rust:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -465,134 +461,10 @@ jobs:
files: target/llvm-cov-target/rust.json
flags: rust
- if: ${{ !cancelled() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: test-rust
path: target/llvm-cov-target/rust.json
test-e2e-web:
name: test-e2e (web)
runs-on: ubuntu-26.04
timeout-minutes: 60
needs:
- build
permissions:
contents: read
# Required so the "Comment on PR" step can create and update the run's
# shared comment through the issues API.
pull-requests: write
# Required so the codecov upload below can mint an OIDC token.
id-token: write
services:
# setup-authentik brings authentik up through the published compose file,
# which pulls its image — a locally loaded tag is not pullable. Pushing the
# image built by `build` here first gives compose something to pull.
registry:
image: registry:2
ports:
- 5000:5000
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
uses: ./.github/actions/setup
with:
dependencies: node
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
with:
name: container-build-server-amd64
- name: Push the built server image to the local registry
run: | # shell
skopeo copy --dest-tls-verify=false \
"oci-archive:container/server-amd64.oci.tar" \
"docker://127.0.0.1:5000/server:e2e"
- name: Resolve Playwright version
id: playwright-version
working-directory: web
run: | # shell
version=$(node -p "require('@playwright/test/package.json').version")
if [ -z "$version" ]; then
echo "Failed to resolve @playwright/test version" >&2
exit 1
fi
echo "version=${version}" >> "$GITHUB_OUTPUT"
- name: Cache Playwright browsers
id: playwright-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }}
- name: Install Playwright browsers
working-directory: web
run: | # shell
if [ "${{ steps.playwright-cache.outputs.cache-hit }}" = "true" ]; then
pnpm exec playwright install-deps chromium
else
pnpm exec playwright install --with-deps chromium
fi
- name: Start authentik
id: authentik
uses: goauthentik/action-setup-authentik@d6c4c8f677abc2a9839b855100ab6c56eddacab5 # v3.4.0
with:
version: 127.0.0.1:5000/server:e2e
blueprints_path: web/test/blueprints
# The image tag is per-commit, so the cache key never hits and every run
# would `docker save` a gigabyte for nothing.
cache: false
wait: true
enterprise_license: true
- name: Run Playwright tests
working-directory: web
env:
AK_TEST_RUNNER_PAGE_URL: ${{ steps.authentik.outputs.http_url }}
run: pnpm run test:e2e
# Reporting / upload steps below intentionally use `!cancelled()` rather
# than `failure()`: a cancelled run (e.g. superseded by a newer push) is
# not a real result and shouldn't produce reviewer-facing artifacts or
# comments. `if-no-files-found: ignore` keeps the "passed" case quiet.
# Server logs need no step of their own: the action's post step dumps the
# logs of every compose service into the job log.
- name: Upload Playwright HTML report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: playwright-report
path: web/playwright-report/
retention-days: 14
if-no-files-found: ignore
- name: Upload Playwright traces and videos
if: ${{ !cancelled() }}
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: playwright-traces
path: web/test-results/
retention-days: 14
if-no-files-found: ignore
# Test analytics only — no coverage is collected for the browser suite.
- name: Upload Playwright results to codecov
if: ${{ !cancelled() }}
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
with:
files: web/playwright-report/results.xml
flags: e2e-web
use_oidc: true
report_type: test_results
# Pass or fail, the artifacts are only useful if a reviewer knows how to get
# them; the results themselves live in codecov. Skipped for pushes, and for
# fork pull requests: those run with a read-only GITHUB_TOKEN even after
# maintainer approval, so commenting would 403.
- name: Comment on PR
if: "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}"
uses: ./.github/actions/comment-pr
with:
section: playwright
body: |
## Playwright e2e
Download this run's HTML report and traces, then open the report:
```shell
gh run download ${{ github.run_id }} -D playwright-artifacts
npx playwright show-report playwright-artifacts/playwright-report
```
ci-core-mark:
if: always()
needs:
@@ -605,7 +477,7 @@ jobs:
- test-integration
- test-e2e
- test-rust
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
@@ -615,6 +487,7 @@ jobs:
needs:
- build-compute-tags
- build
- ci-core-mark
permissions:
# Needed to upload container images to ghcr.io
packages: write
@@ -624,7 +497,7 @@ jobs:
artifact-metadata: write
# Needed for checkout
contents: read
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
@@ -635,16 +508,16 @@ jobs:
- radius
- rac
steps:
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: regclient/actions/regctl-installer@bb562fac724b7b37c17f19671df07fe34fabc376
# logs in to ghcr.io by default
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: regclient/actions/regctl-login@bb562fac724b7b37c17f19671df07fe34fabc376
# Docker login is required for attestations
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
with:
registry: ghcr.io
username: "${{ github.actor }}"
password: "${{ secrets.GITHUB_TOKEN }}"
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
name: "container-build-${{ matrix.name }}"
- id: publish
@@ -665,7 +538,7 @@ jobs:
needs:
- build-compute-tags
- publish
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
# Needed to write comments on PRs
pull-requests: write
@@ -673,39 +546,6 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Comment on PR
uses: ./.github/actions/comment-pr
uses: ./.github/actions/comment-pr-instructions
with:
section: install
body: |
## Installation instructions
<details>
<summary>Instructions for docker-compose</summary>
Add the following block to your `.env` file:
```shell
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
AUTHENTIK_TAG=${{ needs.build-compute-tags.outputs.tag-full }}
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
```
Afterwards, run the upgrade commands from the latest release notes.
</details>
<details>
<summary>Instructions for Kubernetes</summary>
Add the following block to your `values.yml` file:
```yaml
authentik:
outposts:
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
global:
image:
repository: ghcr.io/goauthentik/dev-server
tag: ${{ needs.build-compute-tags.outputs.tag-full }}
```
Afterwards, run the upgrade commands from the latest release notes.
</details>
tag: "${{ needs.build-compute-tags.outputs.tag-full }}"
@@ -1,221 +0,0 @@
---
name: CI - Cross-branch migrations
on:
workflow_dispatch:
schedule:
- cron: "41 4 * * *"
pull_request:
paths:
- .github/workflows/ci-migrations-cross-branch.yml
jobs:
discover-release-branches:
name: Find the adjacent release branches
runs-on: ubuntu-26.04
outputs:
pairs: "${{ steps.pairs.outputs.pairs }}"
steps:
- id: pairs
# Release branches are named version-<family> and sort with `sort -V`,
# so the supported upgrade steps are derived here instead of being
# listed
env:
REPO_URL: "${{ github.server_url }}/${{ github.repository }}"
run: |
set -euo pipefail
mapfile -t branches < <(
git ls-remote --heads "${REPO_URL}" 'refs/heads/version-*' \
| sed 's#.*refs/heads/##' \
| sort -V
)
if [ "${#branches[@]}" -lt 2 ]; then
echo "::error::Found ${#branches[@]} release branches, need at least two"
exit 1
fi
newest="${branches[-1]}"
previous="${branches[-2]}"
echo "::notice::Checking ${previous} -> ${newest} and ${newest} -> main"
pairs="$(jq -nc --arg p "${previous}" --arg n "${newest}" \
'{include: [{old: $p, new: $n}, {old: $n, new: "main"}]}')"
echo "pairs=${pairs}" >> "$GITHUB_OUTPUT"
test-migrations-cross-branch:
name: Migrate ${{ matrix.old }} to ${{ matrix.new }}
needs: discover-release-branches
runs-on: ubuntu-26.04
timeout-minutes: 20
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.discover-release-branches.outputs.pairs) }}
env:
IMAGE_REPO: ghcr.io/goauthentik/dev-server
PG_IMAGE: postgres:16-alpine
PG_NAME: ak-migrate-postgres
PG_NETWORK: ak-migrate
steps:
- id: images
name: Resolve the branch images
env:
OLD_BRANCH: "${{ matrix.old }}"
NEW_BRANCH: "${{ matrix.new }}"
run: |
set -euo pipefail
resolve() {
local branch="$1" dashed dotted tag
# version-2026.8 and newer replace the dot with a dash in the tag.
# Remove once every branch uses compute-container-tags.
dashed="gh-$(printf '%s' "${branch}" | sed 's/[^a-zA-Z0-9-]/-/g')"
dotted="gh-${branch}"
for tag in "${dashed}" "${dotted}"; do
if docker manifest inspect "${IMAGE_REPO}:${tag}" >/dev/null 2>&1; then
printf '%s' "${IMAGE_REPO}:${tag}"
return 0
fi
done
return 1
}
missing=""
old_image="$(resolve "${OLD_BRANCH}")" || missing="${OLD_BRANCH}"
new_image="$(resolve "${NEW_BRANCH}")" || missing="${missing:+${missing} and }${NEW_BRANCH}"
if [ -n "${missing}" ]; then
# A branch has no image until its own ci-main publish job runs, so
# this is normal right after a branch-off and while that branch is
# red. It is not a migration problem, so the step exits zero and
# nothing is posted to Slack.
note="No published image for ${missing}, skipped ${OLD_BRANCH} -> ${NEW_BRANCH}."
echo "::warning::${note}"
echo "${note}" >> "$GITHUB_STEP_SUMMARY"
echo "ready=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "::notice::${old_image} -> ${new_image}"
{
echo "old-image=${old_image}"
echo "new-image=${new_image}"
echo "ready=true"
} >> "$GITHUB_OUTPUT"
- name: Start PostgreSQL
if: ${{ steps.images.outputs.ready == 'true' }}
run: |
set -euo pipefail
docker network create "${PG_NETWORK}"
docker run --detach --name "${PG_NAME}" --network "${PG_NETWORK}" \
-e POSTGRES_USER=authentik \
-e POSTGRES_PASSWORD=authentik \
-e POSTGRES_DB=authentik \
"${PG_IMAGE}"
ready=false
for _ in $(seq 1 60); do
if docker exec "${PG_NAME}" pg_isready -U authentik -d authentik >/dev/null 2>&1; then
ready=true
break
fi
sleep 1
done
if [ "${ready}" != "true" ]; then
docker logs "${PG_NAME}"
echo "::error::PostgreSQL did not become ready"
exit 1
fi
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -hex 32)" >> "$GITHUB_ENV"
- name: Migrate to ${{ matrix.old }}
if: ${{ steps.images.outputs.ready == 'true' }}
env:
IMAGE: "${{ steps.images.outputs.old-image }}"
run: |
set -euo pipefail
# lifecycle/ sits at /lifecycle and the working directory is /, so
# the entrypoint is overridden rather than using `ak migrate`, which
# would skip the lifecycle system migrations.
docker run --rm --network "${PG_NETWORK}" \
-e AUTHENTIK_POSTGRESQL__HOST="${PG_NAME}" \
-e AUTHENTIK_POSTGRESQL__USER=authentik \
-e AUTHENTIK_POSTGRESQL__NAME=authentik \
-e AUTHENTIK_POSTGRESQL__PASSWORD=authentik \
-e AUTHENTIK_SECRET_KEY="${AUTHENTIK_SECRET_KEY}" \
-e AUTHENTIK_AVATARS=none \
--entrypoint bash "${IMAGE}" \
-c 'cd / && python -m lifecycle.migrate'
- name: Migrate to ${{ matrix.new }}
if: ${{ steps.images.outputs.ready == 'true' }}
env:
IMAGE: "${{ steps.images.outputs.new-image }}"
run: |
set -euo pipefail
docker run --rm --network "${PG_NETWORK}" \
-e AUTHENTIK_POSTGRESQL__HOST="${PG_NAME}" \
-e AUTHENTIK_POSTGRESQL__USER=authentik \
-e AUTHENTIK_POSTGRESQL__NAME=authentik \
-e AUTHENTIK_POSTGRESQL__PASSWORD=authentik \
-e AUTHENTIK_SECRET_KEY="${AUTHENTIK_SECRET_KEY}" \
-e AUTHENTIK_AVATARS=none \
--entrypoint bash "${IMAGE}" \
-c 'cd / && python -m lifecycle.migrate'
notify-migration-divergence:
name: Notify migration divergence
# Only the nightly run posts to Slack when something failed.
# A manual run/PR show up in the Actions tab.
if: >-
${{ always() && github.event_name == 'schedule'
&& (needs.discover-release-branches.result != 'success'
|| needs.test-migrations-cross-branch.result != 'success') }}
needs:
- discover-release-branches
- test-migrations-cross-branch
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Build the Slack message
env:
DISCOVERY_RESULT: "${{ needs.discover-release-branches.result }}"
PAIRS: "${{ needs.discover-release-branches.outputs.pairs }}"
REPO: "${{ github.repository }}"
RUN_URL: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
run: |
set -euo pipefail
if [ "${DISCOVERY_RESULT}" = "success" ]; then
headline="Nightly cross-branch migration check failed"
intro="An upgrade between two release branches is broken. Django rejects the migration history, so the server crash-loops on start."
pairs_list="$(printf '%s' "${PAIRS:-}" \
| jq -r '.include[] | "• `\(.old)` -> `\(.new)`"' 2>/dev/null || true)"
[ -n "${pairs_list}" ] || pairs_list="• the checked pairs are unknown"
body="$(printf '%s\n\n%s' "${intro}" "${pairs_list}")"
link_text="Open the failing run to see which pair failed"
else
headline="Nightly cross-branch migration check could not run"
body="Branch discovery finished with \`${DISCOVERY_RESULT}\`, so no upgrade path was checked."
link_text="Open the failing run"
fi
jq -n \
--arg headline "${headline}" \
--arg body "${body}" \
--arg link_text "${link_text}" \
--arg repo "${REPO}" \
--arg run_url "${RUN_URL}" \
'{
text: $headline,
blocks: [
{type: "section", text: {type: "mrkdwn",
text: ("*" + $headline + "*\n" + $body)}},
{type: "context", elements: [
{type: "mrkdwn",
text: ("`" + $repo + "` · <" + $run_url + "|" + $link_text + ">")}
]}
]
}' > "${RUNNER_TEMP}/slack-payload.json"
- name: Post to Slack
uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
with:
webhook: "${{ secrets.RELEASE_SLACK_WEBHOOK_URL }}"
webhook-type: incoming-webhook
payload-file-path: "${{ runner.temp }}/slack-payload.json"
errors: "true"
+5 -5
View File
@@ -23,7 +23,7 @@ env:
jobs:
lint-golint:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -38,10 +38,10 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v8
with:
args: --timeout 5000s --verbose --config .github/golangci.yml
args: --timeout 5000s --verbose
skip-cache: true
test-unittest:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
@@ -60,7 +60,7 @@ jobs:
needs:
- lint-golint
- test-unittest
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
@@ -69,7 +69,7 @@ jobs:
timeout-minutes: 120
needs:
- ci-outpost-mark
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
+171 -9
View File
@@ -23,7 +23,7 @@ env:
jobs:
lint:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -32,7 +32,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -44,16 +44,16 @@ jobs:
pnpm install --frozen-lockfile
pnpm --dir web install --frozen-lockfile
- name: Lint
run: pnpm --dir web run lint:check
run: pnpm --dir web run lint-check
- name: Check types
run: pnpm --dir web run tsc
- name: Check formatting
run: pnpm --dir web run format:check
run: pnpm --dir web run prettier-check
- name: Lit analyse
run: pnpm --dir web run lit-analyse
build:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -62,7 +62,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -78,12 +78,174 @@ jobs:
NODE_ENV: "production"
working-directory: web/
run: pnpm run build
e2e:
name: e2e (playwright)
runs-on: ubuntu-latest
timeout-minutes: 60
permissions:
contents: read
# Required so the codecov upload below can mint an OIDC token.
id-token: write
env:
# Drives blueprints/system/bootstrap.yaml at startup: creates akadmin with
# these credentials, which are the ones SessionFixture logs in with. Without
# them the bootstrap blueprint leaves the user without a usable password and
# the root URL bounces through /setup.
AUTHENTIK_BOOTSTRAP_EMAIL: "[email protected]"
AUTHENTIK_BOOTSTRAP_PASSWORD: "test-runner"
# The embedded outpost wants to reconcile against Docker/Kubernetes, which
# isn't available here and only produces noise in the logs.
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST: "true"
# Both default to the container layout (`/blueprints`, `/certs`), which does
# not exist in a source checkout. Without these the bootstrap blueprint
# cannot be read, gunicorn's workers fail to boot, and :9000 never opens —
# the readiness gate then just times out with nothing useful on stdout.
AUTHENTIK_BLUEPRINTS_DIR: "./blueprints"
AUTHENTIK_CERT_DISCOVERY_DIR: "./certs"
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
uses: ./.github/actions/setup
with:
dependencies: system,python,node,rust,runtime
# The web build has to run before cargo: src/server/core.rs embeds
# web/dist/standalone/loading/startup.html with include_str!, so the Rust
# build fails to compile without it.
- name: Build web UI
env:
NODE_ENV: "production"
run: pnpm --dir web run build
- name: Build authentik
run: |
cargo build --release
sudo install -m 0755 ./target/release/authentik /usr/local/bin/authentik
- name: Apply migrations
run: uv run python -m lifecycle.migrate
- name: Resolve Playwright version
id: playwright-version
working-directory: web
run: | # shell
version=$(node -p "require('@playwright/test/package.json').version")
if [ -z "$version" ]; then
echo "Failed to resolve @playwright/test version" >&2
exit 1
fi
echo "version=${version}" >> "$GITHUB_OUTPUT"
- name: Cache Playwright browsers
id: playwright-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }}
- name: Install Playwright browsers
working-directory: web
run: | # shell
if [ "${{ steps.playwright-cache.outputs.cache-hit }}" = "true" ]; then
pnpm exec playwright install-deps chromium
else
pnpm exec playwright install --with-deps chromium
fi
# `ak allinone` runs the server and the worker in a single process, so
# there is only one listener on :9000 and no need to shuffle the worker's
# HTTP/metrics ports out of the way.
- name: Start authentik
run: | # shell
set -euo pipefail
mkdir -p /tmp/ak-logs
# The certificate discovery watcher inotify-watches this directory and
# raises if it is absent; a checkout has no `certs/`.
mkdir -p certs
uv run ak allinone > /tmp/ak-logs/authentik.log 2>&1 &
echo $! > /tmp/ak-logs/authentik.pid
- name: Wait for authentik to be ready
run: | # shell
set -uo pipefail
pid="$(cat /tmp/ak-logs/authentik.pid)"
# Poll until the URL answers, giving up when the deadline passes or the
# server process is gone. The liveness check matters: without it a boot
# failure is indistinguishable from a slow start and burns the whole
# timeout emitting connection-refused, with the real cause only in the
# uploaded log.
await() {
local url="$1"
local deadline=$(( SECONDS + $2 ))
until curl -fsS -o /dev/null "$url"; do
if ! kill -0 "$pid" 2>/dev/null; then
echo "authentik exited before ${url} became ready" >&2
return 1
fi
if (( SECONDS >= deadline )); then
echo "timed out after $2s waiting for ${url}" >&2
return 1
fi
sleep 2
done
}
# Readiness only covers the HTTP listener and the database. The default
# flows the tests drive arrive later, when the worker finishes applying
# blueprints/default/, so gate on the flow executor actually resolving
# `default-authentication-flow` rather than on the SPA shell rendering
# (which it does regardless of whether the flow exists).
if await "http://localhost:9000/-/health/ready/" 240 \
&& await "http://localhost:9000/api/v3/flows/executor/default-authentication-flow/?query=" 300; then
exit 0
fi
echo "::group::authentik.log (last 200 lines)"
tail -n 200 /tmp/ak-logs/authentik.log || true
echo "::endgroup::"
exit 1
- name: Run Playwright tests
working-directory: web
env:
AK_TEST_RUNNER_PAGE_URL: http://localhost:9000
run: pnpm run test:e2e
# Reporting / upload steps below intentionally use `!cancelled()` rather
# than `failure()`: a cancelled run (e.g. superseded by a newer push) is
# not a real result and shouldn't be reported. `if-no-files-found: ignore`
# keeps the "passed" case quiet.
- name: Upload Playwright HTML report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: playwright-report
path: web/playwright-report/
retention-days: 14
if-no-files-found: ignore
- name: Upload Playwright traces and videos
if: ${{ !cancelled() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: playwright-traces
path: web/test-results/
retention-days: 14
if-no-files-found: ignore
- name: Upload authentik logs
if: ${{ !cancelled() }}
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: authentik-logs
path: /tmp/ak-logs/
retention-days: 14
if-no-files-found: ignore
# Test analytics only — no coverage is collected for the browser suite.
- name: Upload Playwright results to codecov
if: ${{ !cancelled() }}
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v5
with:
files: web/playwright-report/results.xml
flags: e2e-web
use_oidc: true
report_type: test_results
ci-web-mark:
if: always()
needs:
- build
- lint
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
with:
@@ -91,7 +253,7 @@ jobs:
test:
needs:
- ci-web-mark
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -100,7 +262,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
cache: pnpm
+2 -2
View File
@@ -20,12 +20,12 @@ on:
jobs:
compress:
name: compress
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
# Don't run on forks. Token will not be available. Will run on main and open a PR anyway
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -13,10 +13,10 @@ env:
jobs:
build:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -25,7 +25,7 @@ jobs:
token: ${{ steps.generate_token.outputs.token }}
- name: Setup authentik env
uses: ./.github/actions/setup
- run: uv run python -m manage update_webauthn_mds
- run: uv run ak update_webauthn_mds
- uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
id: cpr
with:
+1 -1
View File
@@ -13,7 +13,7 @@ permissions:
jobs:
cleanup:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
+2 -2
View File
@@ -13,10 +13,10 @@ on:
jobs:
clean-ghcr:
name: Delete old unused container images
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
app-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
+7 -11
View File
@@ -6,10 +6,8 @@ on:
branches: [main]
paths:
- packages/tsconfig/**
- packages/oxlint-config/**
- packages/oxfmt-config/**
- packages/fonts/**
- packages/theme/**
- packages/eslint-config/**
- packages/prettier-config/**
- packages/docusaurus-config/**
- packages/logger-js/**
- packages/esbuild-plugin-live-reload/**
@@ -22,19 +20,17 @@ permissions:
jobs:
publish:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
package:
# The order of the `*config` packages should not be changed, as they depend on each other.
- packages/tsconfig
- packages/oxlint-config
- packages/oxfmt-config
- packages/fonts
- packages/logger-js
- packages/theme
- packages/eslint-config
- packages/prettier-config
- packages/docusaurus-config
- packages/logger-js
- packages/esbuild-plugin-live-reload
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
@@ -45,7 +41,7 @@ jobs:
run: |
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
+4 -4
View File
@@ -12,7 +12,7 @@ on:
jobs:
analyze:
name: Analyze
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
@@ -28,10 +28,10 @@ jobs:
- name: Setup authentik env
uses: ./.github/actions/setup
- name: Initialize CodeQL
uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
uses: github/codeql-action/autobuild@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
+1 -1
View File
@@ -17,7 +17,7 @@ permissions:
jobs:
dependency-review:
name: dependency-review
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
+1 -1
View File
@@ -17,7 +17,7 @@ on:
jobs:
semgrep:
name: semgrep/ci
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
contents: read
env:
+5 -5
View File
@@ -17,7 +17,7 @@ env:
jobs:
check-inputs:
name: Check inputs validity
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- run: |
echo "${{ inputs.next_version }}" | grep -E "^[0-9]{4}\.[0-9]{1,2}$"
@@ -25,11 +25,11 @@ jobs:
name: Branch-off
needs:
- check-inputs
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: app-token
name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -54,10 +54,10 @@ jobs:
name: Open version bump PR
needs:
- branch-off
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
+1 -1
View File
@@ -12,7 +12,7 @@ permissions:
jobs:
update-next:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
environment: internal-production
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
+91 -26
View File
@@ -7,7 +7,7 @@ on:
jobs:
metadata:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
outputs:
tag-name: "${{ steps.metadata.outputs.tag-name }}"
version: "${{ steps.metadata.outputs.version }}"
@@ -30,7 +30,7 @@ jobs:
echo "release-reason=$(jq -r '.release_reason' < metadata.json)" >> "$GITHUB_OUTPUT"
echo "changelog-url=$(jq -r '.changelog_url' < metadata.json)" >> "$GITHUB_OUTPUT"
publish-containers:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
contents: read
# Needed to upload container images to ghcr.io
@@ -53,10 +53,10 @@ jobs:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: regclient/actions/regctl-installer@bb562fac724b7b37c17f19671df07fe34fabc376
# logs in to ghcr.io by default
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
- uses: regclient/actions/regctl-login@bb562fac724b7b37c17f19671df07fe34fabc376
- uses: regclient/actions/regctl-login@bb562fac724b7b37c17f19671df07fe34fabc376
with:
registry: docker.io
username: "${{ secrets.DOCKER_CORP_USERNAME }}"
@@ -90,7 +90,7 @@ jobs:
publish-docs-container:
needs:
- metadata
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
# Needed to upload container images to ghcr.io
packages: write
@@ -102,9 +102,9 @@ jobs:
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Set up QEMU
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4.3.0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- name: Login to GitHub Container Registry
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
with:
@@ -113,7 +113,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }}
- id: build
name: Build Docker Image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
with:
tags: |
ghcr.io/goauthentik/docs:${{ needs.metadata.outputs.version }}
@@ -138,10 +138,10 @@ jobs:
env:
AWS_REGION: eu-central-1
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
- uses: aws-actions/configure-aws-credentials@cbe3b392738ccf3f987d68400dafcf4b0624a56c # v6.2.4
with:
role-to-assume: "arn:aws:iam::016170277896:role/github_goauthentik_authentik"
aws-region: ${{ env.AWS_REGION }}
@@ -149,14 +149,59 @@ jobs:
run: |
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ github.ref }}.yaml
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ needs.metadata.outputs.tag-name }}.yaml
if [ "$(gh release list --json tagName,isLatest --jq '.[] | select(.tagName=="${{ needs.metadata.outputs.tag-name }}") | .isLatest')" = "true" ]; then
if [ "$(gh release list --json tagName,isLatest --jq '.[] | select(.tagName=="${{ needs.metadata.outputs.tag-name }} ") | .isLatest')" = "true" ]; then
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.latest.yaml
fi
upload-helm-charts:
runs-on: ubuntu-latest
permissions:
contents: read
# Needed to upload container images to ghcr.io
packages: write
# Needed for attestation
id-token: write
attestations: write
strategy:
fail-fast: false
matrix:
name:
- name: authentik
- name: authentik-remote-cluster
needs:
- publish-containers
env:
AWS_REGION: eu-central-1
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Set up Helm
uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5
- uses: aws-actions/configure-aws-credentials@cbe3b392738ccf3f987d68400dafcf4b0624a56c # v6.2.4
with:
role-to-assume: "arn:aws:iam::016170277896:role/github_goauthentik_authentik"
aws-region: ${{ env.AWS_REGION }}
- uses: regclient/actions/regctl-installer@bb562fac724b7b37c17f19671df07fe34fabc376
# logs in to ghcr.io by default
- uses: regclient/actions/regctl-login@bb562fac724b7b37c17f19671df07fe34fabc376
- name: Download release container artifact
run: |
gh release download "helm-build-${{ matrix.name }}" --pattern "${{ matrix.name }}.tgz"
gh attestation verify "${{ matrix.name }}.tgz" --owner goauthentik
- id: publish-s3
name: Push to S3
run: |
helm plugin install https://github.com/hypnoglow/helm-s3.git
helm repo add goauthentik s3://TODO-NAME
helm s3 push ./${{ matrix.name }}*.tgz goauthentik
- id: publish-oci
name: Push to OCI
run: |
helm push "./${{ matrix.name }}*.tgz" oci://ghcr.io/${GITHUB_REPOSITORY_OWNER}/helm-charts
sentry-release:
needs:
- publish-containers
- metadata
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- name: Get static files from docker image
run: |
@@ -165,7 +210,7 @@ jobs:
container=$(docker container create "$image")
docker cp ${container}:web/ .
- name: Create a Sentry.io release
uses: getsentry/action-release@6fb9aeade7061441cf3864e34fbe11a1457ad7dc # v3
uses: getsentry/action-release@ff07929a6537bac57790c3451cf4d364aca38528 # v3
continue-on-error: true
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
@@ -181,35 +226,55 @@ jobs:
- metadata
- publish-containers
if: ${{ needs.metadata.outputs.release-reason != 'prerelease' }}
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: app-token
name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
repositories: version
- name: Bump version
uses: goauthentik/version@main
- id: get-user-id
name: Get GitHub app user ID
run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT"
env:
GH_TOKEN: "${{ steps.app-token.outputs.token }}"
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
product: authentik
new-version: ${{ needs.metadata.outputs.version }}
changelog-url: ${{ needs.metadata.outputs.changelog-url }}
reason: ${{ needs.metadata.outputs.release-reason }}
token: ${{ steps.app-token.outputs.token }}
github-app-slug: ${{ steps.app-token.outputs.app-slug }}
repository: "${{ github.repository_owner }}/version"
token: "${{ steps.app-token.outputs.token }}"
- name: Bump version
run: |
jq \
--arg version "${{ needs.metadata.outputs.version }}" \
--arg changelog "See ${{ needs.metadata.outputs.changelog-url }}" \
--arg changelog_url "${{ needs.metadata.outputs.changelog-url }}" \
--arg reason "${{ needs.metadata.outputs.release-reason }}" \
'.stable.version = $version | .stable.changelog = $changelog | .stable.changelog_url = $changelog_url | .stable.reason = $reason' version.json > version.new.json
mv version.new.json version.json
- name: Create pull request
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
with:
token: "${{ steps.app-token.outputs.token }}"
branch: bump-${{ needs.metadata.outputs.version }}
commit-message: "version: bump to ${{ needs.metadata.outputs.version }}"
title: "version: bump to ${{ needs.metadata.outputs.version }}"
body: "See ${{ needs.metadata.outputs.changelog-url }}"
delete-branch: true
signoff: true
author: "${{ steps.app-token.outputs.app-slug }}[bot] <${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>"
bump-helm:
name: Bump Helm version
needs:
- metadata
- publish-containers
if: ${{ needs.metadata.outputs.release-reason != 'prerelease' }}
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: app-token
name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
+14 -14
View File
@@ -27,7 +27,7 @@ env:
jobs:
check-inputs:
name: Check inputs validity
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: check
env:
@@ -63,13 +63,13 @@ jobs:
name: Bump authentik version
needs:
- check-inputs
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
outputs:
release-commit: "${{ steps.commit.outputs.release-commit }}"
steps:
- id: app-token
name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -138,7 +138,7 @@ jobs:
needs:
- bump-version
timeout-minutes: 120
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
# Needed for checkout
contents: read
@@ -165,7 +165,7 @@ jobs:
export GOARCH=${{ matrix.goarch }}
export CGO_ENABLED=0
go build -tags=outpost_static_embed -v -o ./build/binaries/authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: "binaries-build-${{ matrix.type }}-${{ matrix.goos }}-${{ matrix.goarch }}"
path: build/
@@ -186,9 +186,9 @@ jobs:
- proxy
target:
- triple: x86_64-unknown-linux-gnu
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
- triple: aarch64-unknown-linux-gnu
runs-on: ubuntu-26.04-arm
runs-on: ubuntu-24.04-arm
- triple: x86_64-apple-darwin
runs-on: macos-15-intel
- triple: aarch64-apple-darwin
@@ -214,7 +214,7 @@ jobs:
mkdir -p build/binaries/
cargo build --package authentik --no-default-features --features "${{ matrix.type }}" --locked --release --target "${{ matrix.target.triple }}"
cp "./target/${{ matrix.target.triple }}/release/authentik" "build/binaries/authentik-outpost-${{ matrix.type }}-${{ matrix.target.triple }}"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
with:
name: "binaries-build-${{ matrix.type }}-${{ matrix.target.triple }}"
path: build/
@@ -223,14 +223,14 @@ jobs:
include-hidden-files: true
test:
name: Pre-release test
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
needs:
- check-inputs
- bump-version
- build-container
steps:
- name: Fetch container images
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
name: container-build-server-amd64
- name: Load container images
@@ -255,7 +255,7 @@ jobs:
- build-go-binaries
- build-rust-binaries
- test
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
permissions:
id-token: write
attestations: write
@@ -263,7 +263,7 @@ jobs:
steps:
- id: app-token
name: Generate app token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -287,12 +287,12 @@ jobs:
run: |
echo '{"version": "${{ needs.check-inputs.outputs.version }}", "version_family": "${{ needs.check-inputs.outputs.version-family }}", "release_reason": "${{ inputs.release_reason }}", "changelog_url": "${{ needs.check-inputs.outputs.changelog-url }}"}' > metadata.json
- name: Fetch container images
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
pattern: container-build-*
merge-multiple: true
- name: Fetch binaries
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
with:
pattern: binaries-build-*
merge-multiple: true
+2 -2
View File
@@ -12,10 +12,10 @@ permissions:
jobs:
stale:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
+1 -1
View File
@@ -17,7 +17,7 @@ permissions:
jobs:
post-comment:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- name: Find Comment
uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v4
@@ -17,11 +17,11 @@ env:
jobs:
compile:
runs-on: ubuntu-26.04
runs-on: ubuntu-latest
steps:
- id: generate_token
if: ${{ github.event_name != 'pull_request' }}
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
@@ -38,7 +38,7 @@ jobs:
uv run make i18n-extract
- name: run compile
run: |
uv run python -m manage compilemessages
uv run ak compilemessages
make web-check-compile
- name: Create Pull Request
if: ${{ github.event_name != 'pull_request' }}
@@ -1,54 +0,0 @@
---
name: Translation - Normalize locale paths
# Moves catalogs in Transifex pull requests to the paths listed in locales.yaml,
# then pushes the result back to the pull request.
# `make ci-lint-locales` in ci-main checks the outcome.
on:
pull_request:
branches:
- main
paths:
- "locale/**"
- "web/xliff/**"
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
normalize:
if: ${{ github.event.pull_request.user.login == 'transifex-integration[bot]' && github.event.pull_request.head.repo.full_name == github.repository }}
runs-on: ubuntu-26.04
steps:
- id: generate_token
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
with:
client-id: ${{ secrets.GH_APP_ID }}
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
ref: ${{ github.event.pull_request.head.ref }}
token: ${{ steps.generate_token.outputs.token }}
- name: Setup authentik env
uses: ./.github/actions/setup
with:
dependencies: python
- name: Normalize
run: make locales-normalize gen-locales
- name: Push corrections
run: |
if [ -z "$(git status --porcelain)" ]; then
echo "Nothing to normalize."
exit 0
fi
git config user.name "authentik-automation[bot]"
# ID from https://api.github.com/users/authentik-automation[bot]
git config user.email "135050075+authentik-automation[bot]@users.noreply.github.com"
git add -A locale web/xliff web/lit-localize.json web/src/common/ui/locale/definitions.ts .github/transifex.yml
git commit --signoff -m "translate: normalize locale paths"
git push
-3
View File
@@ -247,6 +247,3 @@ compose.override.yml
# Claude Local Instructions
# https://code.claude.com/docs/en/memory#choose-where-to-put-claude-md-files
CLAUDE.local.md
# Generated by `packages/oxlint-config/scripts/verify-fixtures.mjs`.
.oxlintrc.generated.json
+56
View File
@@ -0,0 +1,56 @@
# Prettier Ignorefile
## Static Files
CODEOWNERS
**/LICENSE
authentik/stages/**/*
## Build asset directories
coverage
dist
out
.docusaurus
# TODO Replace after moving website to docs
website/api/reference
## Environment
*.env
## Secrets
*.secrets
## Yarn
.yarn/**/*
# PNPM
pnpm-workspace.yaml
pnpm-lock.yaml
## Node
node_modules
coverage
## Vendored files
vendored
*.min.js
## Configs
*.log
*.yaml
*.yml
# Templates
# TODO: Rename affected files to *.template.* or similar.
*.html
*.mdx
*.md
## Import order matters
poly.ts
src/locale-codes.ts
src/locales/
# Storybook
storybook-static/
.storybook/css-import-maps*
+5 -3
View File
@@ -3,19 +3,21 @@
"bashmish.es6-string-css",
"bpruitt-goddard.mermaid-markdown-syntax-highlighting",
"charliermarsh.ruff",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"esbenp.prettier-vscode",
"github.vscode-github-actions",
"golang.go",
"Gruntfuggly.todo-tree",
"mechatroner.rainbow-csv",
"ms-python.black-formatter",
"ms-python.black-formatter",
"ms-python.debugpy",
"ms-python.python",
"ms-python.vscode-pylance",
"oxc.oxc-vscode",
"redhat.vscode-yaml",
"rust-lang.rust-analyzer",
"Tobermory.es6-string-html",
"unifiedjs.vscode-mdx"
"unifiedjs.vscode-mdx",
"Tim-Koehler.helm-intellisense"
]
}
+4 -26
View File
@@ -1,28 +1,7 @@
{
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.oxc": "explicit"
},
"[css]": {
"editor.minimap.markSectionHeaderRegex": "#\\bregion\\s*(?<separator>-?)\\s*(?<label>.*)\\*/$"
},
"[markdown]": {
"editor.colorDecorators": false
},
"[yaml]": {
"editor.autoIndent": "advanced",
"editor.insertSpaces": true,
"editor.tabSize": 2
},
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
"[go]": {
"editor.defaultFormatter": "golang.go"
},
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer"
},
"[makefile]": {
"editor.minimap.markSectionHeaderRegex": "^#{25}\n##\\s\\s*(?<separator>-?)\\s*(?<label>[^\n]*)\n#{25}$"
},
@@ -30,7 +9,6 @@
"editor.minimap.markSectionHeaderRegex": "\\bStage\\s*\\d:(?<separator>-?)\\s*(?<label>.*)$"
},
"[jsonc]": {
"editor.defaultFormatter": "oxc.oxc-vscode",
"editor.minimap.markSectionHeaderRegex": "#\\bregion\\s*(?<separator>-?)\\s*(?<label>.*)$"
},
"[xml]": {
@@ -40,9 +18,11 @@
// The built-in "ignore" language gives us enough syntax highlighting to make these files readable.
"**/dictionaries/*.txt": "ignore"
},
"oxc.fixKind": "safe_fix_or_suggestion",
"todo-tree.tree.showCountsInTree": true,
"todo-tree.tree.showBadges": true,
"yaml.format.printWidth": 200,
"yaml.format.singleQuote": true,
"yaml.format.bracketSpacing": false,
"yaml.customTags": [
"!Condition sequence",
"!Context scalar",
@@ -80,9 +60,7 @@
"go.testEnvVars": {
"WORKSPACE_DIR": "${workspaceFolder}"
},
"github-actions.workflows.pinned.workflows": [
".github/workflows/ci-main.yml"
],
"github-actions.workflows.pinned.workflows": [".github/workflows/ci-main.yml"],
"search.exclude": {
"**/*.code-search": true,
"**/bower_components": true,
+9 -6
View File
@@ -11,6 +11,7 @@ It is a **polyglot monorepo**. Most work lands in one of the subtrees below; whe
| **Rust** | `src/`, `packages/ak-*` | Newer server/worker/proxy outpost components and shared crates (`ak-axum`, `ak-common`, `ak-guardian`). | — |
| **TypeScript** | `web/` | The web UI — three Lit + PatternFly apps (Admin, User, Flow). | [`web/AGENTS.md`](web/AGENTS.md) |
| **Docs** | `website/` | The documentation, integrations, and API sites (Docusaurus). | [`website/AGENTS.md`](website/AGENTS.md) |
| **Go (operator)** | `lifecycle/operator/` | The Kubernetes operator (kubebuilder) that deploys authentik. A port of the Helm chart's templates. | [`lifecycle/operator/AGENTS.md`](lifecycle/operator/AGENTS.md) |
The Python core and the web UI talk through a **generated OpenAPI client** — never hand-roll HTTP calls in either direction (see [API schema & clients](#api-schema--clients)).
@@ -18,7 +19,9 @@ The Python core and the web UI talk through a **generated OpenAPI client** — n
```
authentik/ # Django core — the IdP itself (see "The authentik Django package" below)
lifecycle/ # Boot/runtime: migrations, the prefork Python server, the `ak` CLI, container + AWS entrypoints
lifecycle/ # Boot/runtime: migrations, gunicorn config, the `ak` CLI, container + AWS entrypoints
# charts/ — the authentik Helm chart (+ authentik-remote-cluster)
# operator/ — kubebuilder operator, a port of that chart (own AGENTS.md)
cmd/ # Go entrypoints: ldap/ rac/ radius/ outposts
internal/ # Shared Go: outpost implementations, config
src/ # Rust server/worker (ak-axum based; gated behind cargo features)
@@ -26,7 +29,7 @@ packages/ # Shared workspace packages, polyglot:
# client-go / client-rust / client-ts — GENERATED API clients (do not hand-edit)
# ak-axum / ak-common / ak-guardian — Rust crates
# django-* — reusable Django apps (channels, dramatiq, cache)
# oxlint-config / oxfmt-config / tsconfig / theme / docusaurus-config — shared JS config
# eslint-config / prettier-config / tsconfig / theme / docusaurus-config — shared JS config
web/ # TypeScript web UI (own AGENTS.md)
website/ # Docs / integrations / API sites (own AGENTS.md)
blueprints/ # YAML declarative config (default/ system/ example/) applied at startup
@@ -52,7 +55,7 @@ go.mod # Go module (module path: goauthentik.io)
- **`sources/`** — inbound identity (LDAP, OAuth, SAML, SCIM, Kerberos source).
- **`providers/`** — outbound protocols authentik exposes (SAML, OAuth2/OIDC, Proxy, LDAP, RADIUS, SCIM, RAC).
- **`outposts/`** — management/coordination of the Go outposts.
- **`brands/`** — branding/theming per domain.
- **`brands/`** + **`tenants/`** — branding/theming and multi-tenancy (`django-tenants`).
- **`blueprints/`** — the engine that applies the YAML under the top-level `blueprints/` directory.
- **`rbac/`**, **`crypto/`**, **`events/`** (audit log), **`enterprise/`** (EE-licensed features), **`api/`** - **`admin/`** (REST surfaces), **`root/`** (Django project: settings, URLs, ASGI/WSGI).
@@ -64,11 +67,12 @@ Most tasks land in one subtree and have one follow-up step. Find the row, then r
| ------------------------------------------------------------------ | ------------------------------ | ------------------------------------------------------------------------------------ |
| Add or change a REST endpoint, model field, or serializer | `authentik/` (Python) | `make gen` to refresh `schema.yml` + clients, and commit the generated migration |
| Change UI behavior, a flow screen, or an admin page | `web/` | [`web/AGENTS.md`](web/AGENTS.md) — call the API only through `@goauthentik/api` |
| Write or edit docs or an integration guide | `website/` | [`website/AGENTS.md`](website/AGENTS.md), then `make docs` / `make integrations` |
| Write or edit docs, an integration guide, or a glossary term | `website/` | [`website/AGENTS.md`](website/AGENTS.md), then `make docs` / `make integrations` |
| Change an outpost (LDAP, proxy, RAC, RADIUS) or the front proxy | `cmd/` + `internal/` (Go) | `make go-test` |
| Change a native server/worker component or shared crate | `src/` + `packages/ak-*` (Rust)| `make rust-test` |
| Seed or reconcile a managed object (flow, stage, policy, brand) | `blueprints/` (YAML) | prefer a blueprint over an ad-hoc data migration |
| Change boot, migration wiring, the `ak` CLI, or a container entry | `lifecycle/` | `make run` to confirm the server still boots |
| Change the Helm chart or the Kubernetes operator | `lifecycle/charts/`, `lifecycle/operator/` | [`lifecycle/operator/AGENTS.md`](lifecycle/operator/AGENTS.md). A chart template change usually needs the matching operator builder updating too; `make test` in `lifecycle/operator` compares the two. |
A change that touches more than one row usually wants more than one PR — see [Conventions](#conventions) on splitting by `CODEOWNERS`.
@@ -108,7 +112,6 @@ make lint-fix # Auto-fix: black + ruff (Python) and rustfmt (Rust)
make lint # Check: bandit, mypy --strict, golangci-lint, cargo deny/machete
make lint-spellcheck # cspell across the repo (typo-only mode: reports known misspellings and forbidden British spellings, not unknown words)
make lint-catalogs # pnpm catalog pins in sync across the root/web/website workspaces
make lint-locales # translation files + generated locale lists match locales.yaml (`make gen-locales` regenerates)
```
CI mirrors these as `ci-lint-*` / `ci-test` targets. Run the matching `make lint` / `make test` (plus `make web` / `make docs` for those subtrees) before pushing — CI runs the same checks.
@@ -155,7 +158,7 @@ Authoritative contributor docs live under `website/docs/developer-docs/` and are
| --------------- | ------------------------------------------------------------------------ |
| Core server | Python 3.14, Django 5.2 + Django REST Framework, Channels (ASGI) |
| Background work | Dramatiq (Postgres broker) |
| Datastore | PostgreSQL |
| Datastore | PostgreSQL (multi-tenant via `django-tenants`) |
| Outposts | Go 1.26 (`goauthentik.io` module) — LDAP, proxy, RAC, RADIUS |
| Native services | Rust (2024 edition, `axum`) — server/worker components + shared crates |
| Web UI | TypeScript, Lit 3, PatternFly 4 (see `web/`) |
+3 -2
View File
@@ -23,6 +23,7 @@ rust-toolchain.toml @goauthentik/backend
.github/ @goauthentik/infrastructure
/lifecycle/aws/ @goauthentik/infrastructure
/lifecycle/container/ @goauthentik/infrastructure
/lifecycle/charts/ @goauthentik/infrastructure
.dockerignore @goauthentik/infrastructure
Makefile @goauthentik/infrastructure
.editorconfig @goauthentik/infrastructure
@@ -44,9 +45,9 @@ pnpm-workspace.yaml @goauthentik/frontend
/packages/client-ts @goauthentik/frontend
/packages/docusaurus-config @goauthentik/frontend
/packages/esbuild-plugin-live-reload @goauthentik/frontend
/packages/oxlint-config @goauthentik/frontend
/packages/oxfmt-config @goauthentik/frontend
/packages/eslint-config @goauthentik/frontend
/packages/fonts @goauthentik/frontend
/packages/prettier-config @goauthentik/frontend
/packages/logger-js @goauthentik/frontend
/packages/theme @goauthentik/frontend
/packages/tsconfig @goauthentik/frontend
Generated
+104 -105
View File
@@ -223,7 +223,7 @@ dependencies = [
"nom",
"num-traits",
"rusticata-macros",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
]
@@ -331,8 +331,7 @@ dependencies = [
"percent-encoding",
"pyo3",
"pyo3-build-config",
"rand 0.10.3",
"rcgen",
"rand 0.10.2",
"regex",
"reqwest",
"reqwest-middleware",
@@ -342,7 +341,7 @@ dependencies = [
"serde_repr",
"sqlx",
"tempfile",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
"tokio",
"tokio-retry2",
@@ -417,7 +416,7 @@ dependencies = [
"serde_json",
"sqlx",
"tempfile",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
"tokio",
"tokio-retry2",
@@ -452,9 +451,9 @@ dependencies = [
[[package]]
name = "aws-lc-rs"
version = "1.18.2"
version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13"
checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
dependencies = [
"aws-lc-fips-sys",
"aws-lc-sys",
@@ -464,9 +463,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.46.0"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc"
checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
dependencies = [
"cc",
"cmake",
@@ -786,9 +785,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chacha20"
version = "0.10.2"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
@@ -822,9 +821,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.6.7"
version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
dependencies = [
"clap_builder",
"clap_derive",
@@ -832,9 +831,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.6.7"
version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
dependencies = [
"anstream",
"anstyle",
@@ -844,9 +843,9 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.6.7"
version = "4.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
dependencies = [
"heck",
"proc-macro2",
@@ -1205,7 +1204,7 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
dependencies = [
"thiserror 2.0.21",
"thiserror 2.0.20",
]
[[package]]
@@ -1297,11 +1296,11 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "durstr"
version = "0.6.0"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50749d4bad9666ddc255e232e25e98ab2dcc09854d107ebc6a6d5974f0e54428"
checksum = "10f06c73c39c1530f8356f1da74713d41cfada2c59a042cfcb675ba33de396da"
dependencies = [
"thiserror 2.0.21",
"thiserror 2.0.20",
]
[[package]]
@@ -1868,9 +1867,9 @@ dependencies = [
[[package]]
name = "hyper"
version = "1.12.0"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
dependencies = [
"atomic-waker",
"bytes",
@@ -1890,9 +1889,9 @@ dependencies = [
[[package]]
name = "hyper-rustls"
version = "0.27.10"
version = "0.27.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
"http",
"hyper",
@@ -1919,10 +1918,11 @@ dependencies = [
[[package]]
name = "hyper-unix-socket"
version = "0.7.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57d9d6b7df434b566b1bbfb464633e7ae23f93fc218afb38f3b8906a95535592"
checksum = "88978f1d73da0eb87d86555fcc40cbdd87bc86eb6525710b89db8c9278ec6a59"
dependencies = [
"bytes",
"hyper",
"hyper-util",
"pin-project-lite",
@@ -1932,17 +1932,16 @@ dependencies = [
[[package]]
name = "hyper-util"
version = "0.1.21"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64 0.23.1",
"base64 0.22.1",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"httparse",
"hyper",
"ipnet",
"libc",
@@ -2257,9 +2256,9 @@ dependencies = [
[[package]]
name = "json-subscriber"
version = "0.3.1"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7450152f0f81b8a1ad51e69fcc114ef6155d1a4efa076697471c4f572067de15"
checksum = "b1a3442048fd2d18bf39b182881bea8de640062f86cbacf6d949478af61651d6"
dependencies = [
"serde",
"serde_json",
@@ -2272,9 +2271,9 @@ dependencies = [
[[package]]
name = "jsonwebtoken"
version = "11.1.0"
version = "11.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e75fe14a82d81e5f5af639997db37d8b96045938a7ac6ab18cdbe1c7467e05e1"
checksum = "881733cbc631fc9e472e24447ce32a64bedf2da498d6d8570b08edc87de71f65"
dependencies = [
"aws-lc-rs",
"base64 0.22.1",
@@ -2456,7 +2455,7 @@ dependencies = [
"metrics",
"metrics-util",
"quanta",
"thiserror 2.0.21",
"thiserror 2.0.20",
]
[[package]]
@@ -3054,9 +3053,9 @@ dependencies = [
[[package]]
name = "pyo3"
version = "0.29.1"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc153f5fd745cc038b5eed86622125969f8a39834a57bc96beaaf2512b1da729"
checksum = "cd274650b21d4bfc26a0a47587962c1edb425f69287324355cd040c3ea66071c"
dependencies = [
"libc",
"once_cell",
@@ -3068,18 +3067,18 @@ dependencies = [
[[package]]
name = "pyo3-build-config"
version = "0.29.1"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb77d9aa6d647507b55c69ee714d266d84c526c78ff0bc6dd8757f58591e64d1"
checksum = "c5e2a7d2f0d013342f295c048ad19237add5154a55b1c5a254c0ec93d4109078"
dependencies = [
"target-lexicon",
]
[[package]]
name = "pyo3-ffi"
version = "0.29.1"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3160087aa5733bce7d9a729f8c55f85a2a53b74742a09613178eeebff0722253"
checksum = "ca85c467da1bbc8d866eea5deff9cf29ea5f7785054a17da36e65bda9c05845b"
dependencies = [
"libc",
"pyo3-build-config",
@@ -3087,9 +3086,9 @@ dependencies = [
[[package]]
name = "pyo3-macros"
version = "0.29.1"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91f9d455db760a9a0b0ddeaac25f1390b8a36ba73dfbda9f127cac6fc340d4d5"
checksum = "9ac53762fd065daa3194dd09337a38bd793a188100fd1a9304c4ab312d901771"
dependencies = [
"proc-macro2",
"pyo3-macros-backend",
@@ -3099,9 +3098,9 @@ dependencies = [
[[package]]
name = "pyo3-macros-backend"
version = "0.29.1"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e343bcec300ff262f5806a33a4e51b6d097a8a46435f512fcb83e95592581625"
checksum = "4ca3a1557399783172dc5bf39cfca835157732532cba56b71d2292161e53b362"
dependencies = [
"heck",
"proc-macro2",
@@ -3138,7 +3137,7 @@ dependencies = [
"rustc-hash",
"rustls",
"socket2",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tokio",
"tracing",
"web-time",
@@ -3154,14 +3153,14 @@ dependencies = [
"bytes",
"getrandom 0.4.2",
"lru-slab",
"rand 0.10.3",
"rand 0.10.2",
"rand_pcg",
"ring",
"rustc-hash",
"rustls",
"rustls-pki-types",
"slab",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tinyvec",
"tracing",
"web-time",
@@ -3225,9 +3224,9 @@ dependencies = [
[[package]]
name = "rand"
version = "0.10.3"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
"chacha20",
"getrandom 0.4.2",
@@ -3422,7 +3421,7 @@ dependencies = [
"http",
"reqwest",
"serde",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tower-service",
]
@@ -3485,9 +3484,9 @@ dependencies = [
[[package]]
name = "rustls"
version = "0.23.46"
version = "0.23.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
dependencies = [
"aws-lc-rs",
"log",
@@ -3633,9 +3632,9 @@ checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "sentry"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa951f4e644464ebfd2347a7ab03b0828c512d2448a76262cad2607b343dff4"
checksum = "76a88b65feb368d9dde5d531a2b59b25016e36fd6e4978432371a3ee77746ca2"
dependencies = [
"cfg_aliases",
"httpdate",
@@ -3654,9 +3653,9 @@ dependencies = [
[[package]]
name = "sentry-backtrace"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4f27cf048aa63ccd5bc94c29989133eabb82e9c6bf7441b58e9d4a95837a105"
checksum = "2c51511d67ed670266a93afeaa26a08019b04ad1420cb9191da30f2338d22c48"
dependencies = [
"backtrace",
"regex",
@@ -3665,9 +3664,9 @@ dependencies = [
[[package]]
name = "sentry-contexts"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5ed680585dbdacdf9859c2b4dc53358ff02bd256766882e22e343836db36b22"
checksum = "4b757ac1f335856e8d7f5062a1fd9bc07a05a7eb3cc48247db79bf2618a490bd"
dependencies = [
"hostname",
"libc",
@@ -3679,11 +3678,11 @@ dependencies = [
[[package]]
name = "sentry-core"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3ed398494bb8fc412a11a182c1883a10ae147587b8f6314abd222d1d626f31b"
checksum = "d889520a375e5b93efb0a66def1630d21d168b0251eb55b286b03fa940ccfc84"
dependencies = [
"rand 0.10.3",
"rand 0.9.4",
"sentry-types",
"serde",
"serde_json",
@@ -3692,9 +3691,9 @@ dependencies = [
[[package]]
name = "sentry-debug-images"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55854bb40681e84ffd2a69578ad4ef9bfaf5bf2bf1380a745578b591fa24af22"
checksum = "656487fd5f7b7c0105b2e82171982aac64489e0cb679436038febf070f2f76d6"
dependencies = [
"findshlibs",
"sentry-core",
@@ -3702,9 +3701,9 @@ dependencies = [
[[package]]
name = "sentry-panic"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7153e68642b761ed3aa62c022795c11b2facc728b2db7484084492373c944f9"
checksum = "5e0fe456a7380e9df875a1ef4df1e468d35b19b9051599845fab9d8f0c71c4ae"
dependencies = [
"sentry-backtrace",
"sentry-core",
@@ -3712,9 +3711,9 @@ dependencies = [
[[package]]
name = "sentry-tower"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "624ee2c60caf72fa2cd6be00334b3a3ce0c6df3b1f01941ea62e3d244492d334"
checksum = "d3481bd6aabb99f331e5f32c0fba7c2c22f41282219e7011e100263cb47e335f"
dependencies = [
"sentry-core",
"tower-layer",
@@ -3723,9 +3722,9 @@ dependencies = [
[[package]]
name = "sentry-tracing"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e7db1aefdf623f4e48e21ec9e4af535024187aeafb2a4cc7e29d035def5a13"
checksum = "77796d14eedbef22c2fe78e9c69fb09f14c7ad607e624d48dce92eedc17a136e"
dependencies = [
"bitflags 2.11.0",
"sentry-backtrace",
@@ -3736,16 +3735,16 @@ dependencies = [
[[package]]
name = "sentry-types"
version = "0.49.3"
version = "0.49.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c18bf7b159bdfc7c8f97816f476b4947a1937fb6bea9d38d3479e58631614ac"
checksum = "fc71f5ca55942d9b2901af95d5df5c5d65c164134c22a83682cac3d0b6c7ef2d"
dependencies = [
"debugid",
"hex",
"rand 0.10.3",
"rand 0.9.4",
"serde",
"serde_json",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
"url",
"uuid",
@@ -3783,9 +3782,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.154"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
@@ -3830,9 +3829,9 @@ dependencies = [
[[package]]
name = "serde_with"
version = "3.24.0"
version = "3.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f"
checksum = "935177bb8c0cd8ca1a4e6d1a2ac8988bea69cab4f9d3a31311e012ad27868ea4"
dependencies = [
"base64 0.23.1",
"bs58",
@@ -3936,7 +3935,7 @@ checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"
dependencies = [
"num-bigint",
"num-traits",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
]
@@ -4023,7 +4022,7 @@ dependencies = [
"serde_json",
"sha2 0.10.9",
"smallvec",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tokio",
"tokio-stream",
"tracing",
@@ -4066,7 +4065,7 @@ dependencies = [
"sqlx-postgres",
"sqlx-sqlite",
"syn 2.0.117",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tokio",
"url",
]
@@ -4094,7 +4093,7 @@ dependencies = [
"sha1 0.11.0",
"sha2 0.11.0",
"sqlx-core",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tracing",
"uuid",
]
@@ -4124,14 +4123,14 @@ dependencies = [
"log",
"md-5",
"memchr",
"rand 0.10.3",
"rand 0.10.2",
"serde",
"serde_json",
"sha2 0.11.0",
"smallvec",
"sqlx-core",
"stringprep",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tracing",
"uuid",
"whoami",
@@ -4157,7 +4156,7 @@ dependencies = [
"percent-encoding",
"serde",
"sqlx-core",
"thiserror 2.0.21",
"thiserror 2.0.20",
"tracing",
"url",
"uuid",
@@ -4291,11 +4290,11 @@ dependencies = [
[[package]]
name = "thiserror"
version = "2.0.21"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl 2.0.21",
"thiserror-impl 2.0.20",
]
[[package]]
@@ -4311,9 +4310,9 @@ dependencies = [
[[package]]
name = "thiserror-impl"
version = "2.0.21"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
dependencies = [
"proc-macro2",
"quote",
@@ -4388,9 +4387,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.53.3"
version = "1.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
dependencies = [
"bytes",
"libc",
@@ -4427,9 +4426,9 @@ dependencies = [
[[package]]
name = "tokio-rustls"
version = "0.26.6"
version = "0.26.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67"
dependencies = [
"rustls",
"tokio",
@@ -4476,9 +4475,9 @@ dependencies = [
[[package]]
name = "tokio-util"
version = "0.7.20"
version = "0.7.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"
checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
dependencies = [
"bytes",
"futures-core",
@@ -4712,7 +4711,7 @@ dependencies = [
"log",
"rand 0.9.4",
"sha1 0.10.6",
"thiserror 2.0.21",
"thiserror 2.0.20",
]
[[package]]
@@ -4726,11 +4725,11 @@ dependencies = [
"http",
"httparse",
"log",
"rand 0.10.3",
"rand 0.10.2",
"rustls",
"rustls-pki-types",
"sha1 0.11.0",
"thiserror 2.0.21",
"thiserror 2.0.20",
"url",
]
@@ -4861,9 +4860,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.28.0"
version = "1.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce"
dependencies = [
"getrandom 0.4.2",
"js-sys",
@@ -4901,9 +4900,9 @@ dependencies = [
[[package]]
name = "want"
version = "0.3.2"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"try-lock",
]
@@ -5531,7 +5530,7 @@ dependencies = [
"nom",
"oid-registry",
"rusticata-macros",
"thiserror 2.0.21",
"thiserror 2.0.20",
"time",
]
+22 -29
View File
@@ -23,14 +23,14 @@ arc-swap = "= 1.9.2"
argh = "= 0.1.19"
askama = "= 0.16.1"
axum-server = { version = "= 0.8.0", features = ["tls-rustls-no-provider"] }
aws-lc-rs = { version = "= 1.18.2", features = ["fips"] }
aws-lc-rs = { version = "= 1.18.1", features = ["fips"] }
axum = { version = "= 0.8.9", features = ["http2", "macros", "ws"] }
axum-extra = { version = "= 0.12.6", default-features = false, features = [
"cookie-signed",
"cookie-key-expansion",
] }
base64 = "= 0.23.1"
clap = { version = "= 4.6.7", features = ["derive", "env"] }
clap = { version = "= 4.6.6", features = ["derive", "env"] }
chrono = { version = "0.4.45", features = ["serde"] }
color-eyre = "= 0.6.5"
colored = "= 3.1.1"
@@ -40,48 +40,42 @@ config-rs = { package = "config", version = "= 0.15.22", default-features = fals
] }
console-subscriber = "= 0.5.0"
dotenvy = "= 0.15.7"
durstr = "= 0.6.0"
durstr = "= 0.5.1"
eyre = "= 0.6.14"
futures = "= 0.3.34"
glob = "= 0.3.4"
http-body-util = "= 0.1.5"
hyper = { version = "= 1.12.0", features = ["client", "http1", "http2"] }
hyper-rustls = { version = "= 0.27.10", default-features = false, features = [
hyper = { version = "= 1.11.1", features = ["client", "http1", "http2"] }
hyper-rustls = { version = "= 0.27.9", default-features = false, features = [
"aws-lc-rs",
"http1",
"http2",
"native-tokio",
"tls12",
] }
hyper-unix-socket = "= 0.7.0"
hyper-util = { version = "= 0.1.21", features = [
hyper-unix-socket = "= 0.6.1"
hyper-util = { version = "= 0.1.20", features = [
"client-legacy",
"http1",
"http2",
"tokio",
] }
ipnet = { version = "= 2.12.2", features = ["serde"] }
json-subscriber = "= 0.3.1"
jsonwebtoken = { version = "= 11.1.0", features = ["aws_lc_rs"] }
json-subscriber = "= 0.3.0"
jsonwebtoken = { version = "= 11.0.0", features = ["aws_lc_rs"] }
metrics = "= 0.24.6"
metrics-exporter-prometheus = { version = "= 0.18.3", default-features = false }
moka = { version = "= 0.12.16", default-features = false, features = [
"future",
] }
nix = { version = "= 0.31.3", features = [
"fs",
"hostname",
"process",
"signal",
"user",
] }
nix = { version = "= 0.31.3", features = ["hostname", "signal"] }
notify = "= 8.2.0"
pem = "= 4.0.0"
percent-encoding = "= 2.3.2"
pin-project-lite = "= 0.2.17"
pyo3 = "= 0.29.1"
pyo3-build-config = "= 0.29.1"
rand = "= 0.10.3"
pyo3 = "= 0.29.0"
pyo3-build-config = "= 0.29.0"
rand = "= 0.10.2"
rcgen = { version = "= 0.14.10", default-features = false, features = [
"aws_lc_rs",
"fips",
@@ -102,8 +96,8 @@ reqwest-middleware = { version = "= 0.5.2", features = [
"query",
"rustls",
] }
rustls = { version = "= 0.23.46", features = ["fips"] }
sentry = { version = "= 0.49.3", default-features = false, features = [
rustls = { version = "= 0.23.45", features = ["fips"] }
sentry = { version = "= 0.49.2", default-features = false, features = [
"backtrace",
"contexts",
"debug-images",
@@ -114,9 +108,9 @@ sentry = { version = "= 0.49.3", default-features = false, features = [
"tracing",
] }
serde = { version = "= 1.0.229", features = ["derive"] }
serde_json = "= 1.0.154"
serde_json = "= 1.0.151"
serde_repr = "= 0.1.21"
serde_with = { version = "= 3.24.0", default-features = false, features = [
serde_with = { version = "= 3.23.0", default-features = false, features = [
"base64",
] }
sqlx = { version = "= 0.9.0", default-features = false, features = [
@@ -131,16 +125,16 @@ sqlx = { version = "= 0.9.0", default-features = false, features = [
"json",
] }
tempfile = "= 3.27.0"
thiserror = "= 2.0.21"
thiserror = "= 2.0.20"
time = { version = "= 0.3.55", features = ["macros"] }
tokio = { version = "= 1.53.3", features = ["full", "tracing"] }
tokio = { version = "= 1.53.1", features = ["full", "tracing"] }
tokio-retry2 = "= 0.9.1"
tokio-rustls = "= 0.26.6"
tokio-rustls = "= 0.26.5"
tokio-tungstenite = { version = "= 0.30.0", features = [
"rustls-tls-webpki-roots",
"url",
] }
tokio-util = { version = "= 0.7.20", features = ["full"] }
tokio-util = { version = "= 0.7.19", features = ["full"] }
tower = "= 0.5.3"
tower-http = { version = "= 0.7.1", features = [
"compression-full",
@@ -157,7 +151,7 @@ tracing-subscriber = { version = "= 0.3.23", features = [
"tracing-log",
] }
url = "= 2.5.8"
uuid = { version = "= 1.28.0", features = ["serde", "v4"] }
uuid = { version = "= 1.26.1", features = ["serde", "v4"] }
ak-axum = { package = "authentik-axum", version = "2026.11.0-rc1", path = "./packages/ak-axum" }
ak-client = { package = "authentik-client", version = "2026.11.0-rc1", path = "./packages/client-rust" }
@@ -366,7 +360,6 @@ url.workspace = true
uuid.workspace = true
[dev-dependencies]
rcgen.workspace = true
tempfile.workspace = true
[lints]
+68 -84
View File
@@ -1,4 +1,4 @@
.PHONY: gen dev-reset all test web docs core-install i18n-extract gen-locales locales-normalize install bump gen-changelog integrations
.PHONY: gen dev-reset all clean test web docs
SHELL := /usr/bin/env bash
.SHELLFLAGS += ${SHELLFLAGS} -e -o pipefail
@@ -54,7 +54,7 @@ else
NPM_VERSION = $(shell python -m scripts.generate_semver)
endif
all: lint-fix lint gen web test ## Lint-fix, lint, generate the schema, generate the client libraries, lint the front end, run the python tests
all: lint-fix lint gen web test ## Lint, build, and test everything
HELP_WIDTH := $(shell grep -h '^[a-z][^ ]*:.*\#\#' $(MAKEFILE_LIST) 2>/dev/null | \
cut -d':' -f1 | awk '{printf "%d\n", length}' | sort -rn | head -1)
@@ -72,16 +72,16 @@ go-test: ## Run the golang tests
rust-test: ## Run the Rust tests
$(CARGO) nextest run --workspace
test: ## Run the server tests and produce a coverage report (locally). Usage: make test [path]
test: ## Run the server tests and produce a coverage report (locally)
$(UV) run coverage run manage.py test --keepdb $(or $(filter-out $@ all,$(MAKECMDGOALS)),authentik)
$(UV) run coverage combine
$(UV) run coverage html
$(UV) run coverage report
lint-fix-rust: ## Format Rust sources (rustfmt)
lint-fix-rust:
$(CARGO) +nightly fmt --all -- --config-path "${PWD}/.cargo/rustfmt.toml"
lint-fix: lint-fix-rust ## Format and automatically fix Python (black, ruff) and Rust (rustfmt) sources
lint-fix: lint-fix-rust ## Lint and automatically fix errors in the python source code. Reports spelling errors.
$(UV) run black $(PY_SOURCES)
$(UV) run ruff check --fix $(PY_SOURCES)
@@ -91,17 +91,14 @@ lint-spellcheck: ## Reports spelling errors.
lint-catalogs: ## Reports pnpm catalog pins, and pnpm's own version pin, that drifted between workspaces.
node ./scripts/node/lint-catalogs.ts
lint-locales: ## Reports translation files and generated locale lists that drifted from locales.yaml.
$(UV) run python scripts/locales.py check
lint-check-types: ## Type-check the repository's Node.js scripts.
pnpm run build:types
pnpm run check-types
lint: ci-lint-bandit ci-lint-mypy ci-lint-cargo-deny ci-lint-cargo-machete ## Check Python (bandit, mypy), Go (golangci) and Rust dependencies (cargo deny, machete)
golangci-lint run -v --config .github/golangci.yml
lint: ci-lint-bandit ci-lint-mypy ci-lint-cargo-deny ci-lint-cargo-machete ## Lint the python and golang sources
golangci-lint run -v
core-install:
ifneq ($(BREW_EXISTS),)
ifdef ($(BREW_EXISTS))
# Clear cache to ensure fresh compilation
$(UV) cache clean
# Force compilation from source for lxml and xmlsec with correct environment
@@ -110,18 +107,12 @@ else
$(UV) sync --frozen
endif
migrate: ## Apply and check system and Django migrations
migrate: ## Run the Authentik Django server's migrations
$(UV) run python -m lifecycle.migrate
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
gen-locales: ## Regenerate lit-localize.json, the web locale loaders, and the Transifex language mapping from locales.yaml
$(UV) run python scripts/locales.py gen
locales-normalize: ## Move translation files that Transifex wrote under non-canonical names to their canonical paths
$(UV) run python scripts/locales.py normalize
aws-cfn: node-install ## Generate the AWS Cloudformation template
aws-cfn: node-install
pnpm --dir lifecycle/aws install
$(UV) run pnpm --dir lifecycle/aws run aws-cfn
@@ -132,7 +123,7 @@ run-watch: ## Run the authentik server and worker, with auto reloading
watchexec --on-busy-update=restart --stop-signal=SIGINT --exts py,rs --no-meta --notify -- $(UV) run ak allinone
core-i18n-extract:
$(UV) run python -m manage makemessages \
$(UV) run ak makemessages \
--add-location file \
--no-obsolete \
--ignore web \
@@ -141,7 +132,7 @@ core-i18n-extract:
--ignore website \
-l en
install: node-install web-install core-install ## Install all required dependencies for `node`, `web` and `core`
install: node-install web-install core-install ## Install all requires dependencies for `node`, `web` and `core`
dev-drop-db:
$(eval pg_user := $(shell $(UV) run python -m authentik.lib.config postgresql.user 2>/dev/null))
@@ -157,10 +148,7 @@ dev-create-db:
$(eval pg_name := $(shell $(UV) run python -m authentik.lib.config postgresql.name 2>/dev/null))
createdb -U ${pg_user} -h ${pg_host} ${pg_name}
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the authentik PostgreSQL instance to a "fresh install" state.
make-migrations: ## Create Django migrations for model changes (pgtrigger-aware)
$(UV) run ak makemigrations
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
update-test-mmdb: ## Update test GeoIP and ASN Databases
curl \
@@ -176,22 +164,29 @@ bump: ## Bump authentik version. Usage: make bump version=20xx.xx.xx
ifndef version
$(error Usage: make bump version=20xx.xx.xx )
endif
$(eval current_version := $(shell cat ${PWD}/internal/constants/VERSION))
$(eval current_version := $(shell cat ${PWD}/internal/constants/VERSION | tr -d '\n'))
$(SED_INPLACE) 's/^version = ".*"/version = "$(version)"/' ${PWD}/pyproject.toml
$(SED_INPLACE) 's/^VERSION = ".*"/VERSION = "$(version)"/' ${PWD}/authentik/__init__.py
$(SED_INPLACE) "s/version = \"${current_version}\"/version = \"$(version)\"/" ${PWD}/Cargo.toml ${PWD}/Cargo.lock
$(MAKE) gen-build gen-compose aws-cfn
$(SED_INPLACE) "s/\"${current_version}\"/\"$(version)\"/" ${PWD}/package.json ${PWD}/web/package.json
echo -n $(version) > ${PWD}/internal/constants/VERSION
# Helm
$(SED_INPLACE) "s/^version: ${current_version}/version: $(version)/" ${PWD}/lifecycle/charts/authentik/Chart.yaml
$(SED_INPLACE) "s/^appVersion: ${current_version}/appVersion: $(version)/" ${PWD}/lifecycle/charts/authentik/Chart.yaml
$(SED_INPLACE) "s/upgrade to authentik ${current_version}/upgrade to authentik $(version)/" ${PWD}/lifecycle/charts/authentik/Chart.yaml
$(SED_INPLACE) "s/${current_version}/$(version)/" ${PWD}/lifecycle/charts/authentik/Chart.yaml
$(MAKE) helm-docs
#########################
## API Schema
#########################
gen-build: ## Generate schema.yml and blueprints/schema.json from Django model definitions
gen-build: ## Extract the schema from the database
AUTHENTIK_DEBUG=true \
AUTHENTIK_TENANTS__ENABLED=true \
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
$(UV) run python -m manage build_schema
$(UV) run ak build_schema
gen-compose:
$(UV) run scripts/generate_compose.py
@@ -207,7 +202,7 @@ gen-changelog: ## (Release) generate the changelog based from the commits since
rm merged_to_current
rm merged_to_last
rm cherry_picked_to_last
pnpm exec oxfmt --write changelog.md
npx prettier --write changelog.md
gen-diff: ## (Release) generate the changelog diff between the current schema and the last version
$(eval last_version := $(shell git tag --list 'version/*' --sort 'version:refname' | grep -vE 'rc[0-9]+$$' | tail -1))
@@ -220,7 +215,7 @@ gen-diff: ## (Release) generate the changelog diff between the current schema a
rm schema-old.yml
$(SED_INPLACE) 's/{/\&#123;/g' diff.md
$(SED_INPLACE) 's/}/\&#125;/g' diff.md
pnpm exec oxfmt --write diff.md
npx prettier --write diff.md
gen-client-go: ## Build and install the authentik API for Golang
$(UV) run make -C "${PWD}/packages/client-go" build
@@ -253,52 +248,37 @@ gen-dev-config: ## Generate a local development config file
node-preinstall: ## Verify the active Node.js and pnpm versions match what's in package.json.
node ./scripts/node/lint-runtime.ts
node-install: node-preinstall ## Install the necessary libraries to build Node.js packages and build the shared lint configs
node-install: node-preinstall ## Install the necessary libraries to build Node.js packages
pnpm install --frozen-lockfile
pnpm run build:lint-config
#########################
## Web
#########################
web-install: ## Install the necessary libraries to build the authentik front end
web-install: ## Install the necessary libraries to build the Authentik UI
pnpm --dir web install --frozen-lockfile
web-build: node-install ## Build the authentik front end
web-build: node-install ## Build the Authentik UI
pnpm --dir web run build
web: web-lint-fix web-lint web-check-compile ## Format and lint the front-end, run lit-analyzer and type-check
web: web-lint-fix web-lint web-check-compile ## Automatically fix formatting issues in the Authentik UI source code, lint the code, and compile it
web-check: ## Run front-end lint and format checks (does no modifications)
pnpm --dir web lint:check
pnpm --dir web format:check
web-test-unit: ## Run web front-end tests once
pnpm --dir web run test:unit
web-test: ## Run tests for the authentik front end in watch mode
web-test: ## Run tests for the Authentik UI
pnpm --dir web run test
web-test-e2e: ## Run front end Playwright end-to-end tests
pnpm --dir web run test:e2e
web-test-visual: ## Run visual regression tests for the front-end
pnpm --dir web run test:visual
web-watch: ## Build and watch the authentik front end for changes, updating automatically
web-watch: ## Build and watch the Authentik UI for changes, updating automatically
pnpm --dir web run watch
web-storybook-watch: ## Build and run the storybook documentation server
pnpm --dir web run storybook
web-lint-fix: ## Format the front end source (oxfmt)
pnpm --dir web run format
web-lint-fix:
pnpm --dir web run prettier
web-lint: ## Lint the front end (oxfmt) and run lit-analyzer
web-lint:
pnpm --dir web run lint
pnpm --dir web run lit-analyse
web-check-compile: ## Type-check the front end
web-check-compile:
pnpm --dir web run tsc
web-i18n-extract:
@@ -308,39 +288,30 @@ web-i18n-extract:
## Docs
#########################
docs: docs-lint-fix docs-build ## Spellcheck, format, and build the docs website
docs: docs-lint-fix docs-build ## Automatically fix formatting issues in the Authentik docs source code, lint the code, and compile it
docs-install: node-install ## Install the necessary libraries to build the authentik documentation
docs-install: node-install ## Install the necessary libraries to build the Authentik documentation
pnpm --dir website install --frozen-lockfile
docs-lint-fix: lint-spellcheck ## Spellcheck and format the documentation site
pnpm --dir website run lint
pnpm --dir website run format
docs-lint-fix: lint-spellcheck
pnpm --dir website run prettier
docs-build: ## Build the docs website
docs-build:
node ./scripts/node/lint-runtime.ts website
pnpm --dir website run build
docs-watch: ## Build and watch the topics documentation
pnpm --dir website run start
docs-test: ## Run the documentation website tests
pnpm --dir website run test
integrations: docs-lint-fix integrations-build ## Fix formatting issues in the integrations source code, lint the code, and compile it
docs-check: ## Run documentation lint, typecheck, and format (does no modifications)
pnpm --dir website run lint:check
pnpm --dir website run build:types
pnpm --dir website run format:check
integrations: docs-lint-fix integrations-build ## Spellcheck, format, and build the integrations website
integrations-build: ## Build the integrations website
integrations-build:
pnpm --dir website run build:integrations
integrations-watch: ## Build and watch the Integrations documentation
pnpm --dir website/integrations run start
docs-api-build: ## Build the API reference site
docs-api-build:
pnpm --dir website run build:api
docs-api-watch: ## Build and watch the API documentation
@@ -351,15 +322,35 @@ docs-api-clean: ## Clean generated API documentation
pnpm --dir website/api run clean
#########################
## Docker
## Lifecycle
#########################
docker: ## Build a docker image of the current source tree
DOCKER_BUILDKIT=1 docker build . -f lifecycle/container/Dockerfile --progress plain --tag ${DOCKER_IMAGE}
test-docker: ## Build docker image and run full test suite in the container compose stack
test-docker:
BUILD=true ${PWD}/scripts/test_docker.sh
helm-docs:
docker run \
--rm \
-v "${PWD}:/helm-docs" \
-u $(UID) \
docker.io/jnorwood/helm-docs:v1.12.0 \
-c /helm-docs/lifecycle/charts
helm-lint:
docker run \
--rm \
-v "${PWD}:/workdir" \
--entrypoint /bin/sh \
quay.io/helmpack/chart-testing:v3.10.1 \
-c cd /workdir/lifecycle/chart \
ct lint \
--config /workdir/lifecycle/chart/ct-lint.yaml \
--lint-conf /workdir/lifecycle/chart/lintconf.yaml \
--debug
#########################
## CI
#########################
@@ -387,7 +378,7 @@ ci-lint-bandit: ci--meta-debug
$(UV) run bandit -c pyproject.toml -r $(PY_SOURCES) -iii
ci-lint-pending-migrations: ci--meta-debug
$(UV) run python -m manage makemigrations --check
$(UV) run ak makemigrations --check
ci-lint-cargo-deny: ci--meta-debug
$(CARGO) deny --config "${PWD}/.cargo/deny.toml" --locked --workspace check
@@ -404,15 +395,8 @@ ci-lint-clippy: ci--meta-debug
ci-lint-catalogs: ci--meta-debug
node ./scripts/node/lint-catalogs.ts
ci-lint-locales: ci--meta-debug
$(UV) run python scripts/locales.py check
ci-lint-oxlint-fixtures: ci--meta-debug
pnpm --filter @goauthentik/oxlint-config run build
pnpm --filter @goauthentik/oxlint-config run verify
ci-lint-check-types: ci--meta-debug
pnpm run build:types
pnpm run check-types
ci-test: ci--meta-debug
$(UV) run coverage run manage.py test --keepdb --parallel auto authentik
+1 -1
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://docs.goauthentik.io/img/icon_top_brand_colour.svg" height="150" alt="authentik logo">
<img src="https://goauthentik.io/img/icon_top_brand_colour.svg" height="150" alt="authentik logo">
</p>
---
+2 -2
View File
@@ -17,13 +17,13 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from authentik import authentik_full_version
from authentik.admin.utils import get_system_settings
from authentik.core.api.utils import PassiveSerializer
from authentik.lib.config import CONFIG
from authentik.lib.utils.reflection import get_env
from authentik.outposts.apps import MANAGED_OUTPOST
from authentik.outposts.models import Outpost
from authentik.rbac.permissions import HasPermission
from authentik.tenants.utils import get_current_tenant
def fips_enabled():
@@ -118,7 +118,7 @@ class SystemInfoSerializer(PassiveSerializer):
def get_base_url(self, request: Request) -> str:
"""Configured external base URL. Can be empty"""
return get_system_settings().base_url
return get_current_tenant().base_url
class SystemView(APIView):
+18 -7
View File
@@ -1,5 +1,7 @@
"""authentik administration overview"""
from django.core.cache import cache
from django_tenants.utils import get_public_schema_name
from drf_spectacular.utils import extend_schema
from packaging.version import parse
from rest_framework.fields import SerializerMethodField
@@ -9,9 +11,10 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from authentik import authentik_build_hash, authentik_version
from authentik.admin.tasks import UpdateVersionInfo
from authentik.admin.tasks import VERSION_CACHE_KEY, VERSION_NULL, update_latest_version
from authentik.core.api.utils import PassiveSerializer
from authentik.outposts.models import Outpost
from authentik.tenants.utils import get_current_tenant
class VersionSerializer(PassiveSerializer):
@@ -19,6 +22,7 @@ class VersionSerializer(PassiveSerializer):
version_current = SerializerMethodField()
version_latest = SerializerMethodField()
version_latest_valid = SerializerMethodField()
build_hash = SerializerMethodField()
outdated = SerializerMethodField()
outpost_outdated = SerializerMethodField()
@@ -31,16 +35,23 @@ class VersionSerializer(PassiveSerializer):
"""Get current version"""
return authentik_version()
def get_version_latest(self, _) -> UpdateVersionInfo:
def get_version_latest(self, _) -> str:
"""Get latest version from cache"""
return UpdateVersionInfo.get_cached().model_dump(mode="json")
if get_current_tenant().schema_name != get_public_schema_name():
return authentik_version()
version_in_cache = cache.get(VERSION_CACHE_KEY)
if not version_in_cache: # pragma: no cover
update_latest_version.send()
return authentik_version()
return version_in_cache
def get_version_latest_valid(self, _) -> bool:
"""Check if latest version is valid"""
return cache.get(VERSION_CACHE_KEY) != VERSION_NULL
def get_outdated(self, instance) -> bool:
"""Check if we're running the latest version"""
cached = UpdateVersionInfo.get_cached()
if not cached:
return False
return parse(self.get_version_current(instance)) < parse(cached.version)
return parse(self.get_version_current(instance)) < parse(self.get_version_latest(instance))
def get_outpost_outdated(self, _) -> bool:
"""Check if any outpost is outdated/has a version mismatch"""
+2 -47
View File
@@ -1,25 +1,15 @@
"""authentik admin app config"""
from django.db import DEFAULT_DB_ALIAS
from django.db.models.signals import post_migrate
from prometheus_client import Info
from authentik.blueprints.apps import ManagedAppConfig
from authentik.lib.config import CONFIG
from authentik.lib.utils.time import fqdn_rand
from authentik.outposts.apps import MANAGED_OUTPOST
from authentik.tasks.schedules.common import ScheduleSpec
PROM_INFO = Info("authentik_version", "Currently running authentik version")
def ensure_system_settings(*args, using=DEFAULT_DB_ALIAS, **kwargs):
"""Make sure the system settings exist"""
from authentik.admin.models import SystemSettings
SystemSettings.objects.using(using).get_or_create(pk=True)
class AuthentikAdminConfig(ManagedAppConfig):
"""authentik admin app config"""
@@ -28,42 +18,7 @@ class AuthentikAdminConfig(ManagedAppConfig):
verbose_name = "authentik Admin"
default = True
@ManagedAppConfig.reconcile
def system_settings(self):
"""Make sure the system settings exist, especially after a migration"""
post_migrate.connect(ensure_system_settings)
ensure_system_settings()
self._backfill_base_url()
def _backfill_base_url(self):
"""Backfill base_url when it hasn't been set yet. Sources: AUTHENTIK_WEB__BASE_URL config
value, then the embedded outpost's configured host."""
from django.core.exceptions import ValidationError
from authentik.admin.models import SystemSettings
from authentik.admin.utils import get_system_settings, normalize_base_url
from authentik.outposts.models import Outpost
settings = get_system_settings()
if settings.base_url:
return # Already set
base_url = normalize_base_url(CONFIG.get("web.base_url", ""))
if not base_url:
outpost = Outpost.objects.filter(managed=MANAGED_OUTPOST).first()
if outpost:
base_url = normalize_base_url(outpost.config.authentik_host)
if base_url:
try:
SystemSettings._meta.get_field("base_url").run_validators(base_url)
except ValidationError:
self.logger.warning("Discarding invalid base_url", base_url=base_url)
base_url = ""
if not base_url: # No source available
return
SystemSettings.objects.filter(pk=settings.pk).update(base_url=base_url)
self.logger.info("Backfilled base_url", base_url=base_url)
@ManagedAppConfig.reconcile
@ManagedAppConfig.reconcile_global
def clear_update_notifications(self):
"""Clear update notifications on startup if the notification was for the version
we're running now."""
@@ -80,7 +35,7 @@ class AuthentikAdminConfig(ManagedAppConfig):
notification.delete()
@property
def schedule_specs(self) -> list[ScheduleSpec]:
def global_schedule_specs(self) -> list[ScheduleSpec]:
from authentik.admin.tasks import update_latest_version
return [
-18
View File
@@ -1,18 +0,0 @@
from collections.abc import Callable
from django.http import HttpRequest, HttpResponse
from authentik.admin.utils import system_settings_cache
class SystemSettingsMiddleware:
"""Read the system settings at most once per request"""
get_response: Callable[[HttpRequest], HttpResponse]
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
self.get_response = get_response
def __call__(self, request: HttpRequest) -> HttpResponse:
with system_settings_cache():
return self.get_response(request)
-220
View File
@@ -1,220 +0,0 @@
# Generated by Django 5.2.17 on 2026-09-15 08:23
from json import loads
import authentik.lib.models
import authentik.lib.utils.time
import django.core.validators
from authentik.lib.config import CONFIG
from django.db import connections, migrations, models
JSON_FIELDS = ("footer_links", "flags")
FIELDS = [
"avatars",
"base_url",
"default_user_change_name",
"default_user_change_email",
"default_user_change_username",
"event_retention",
"reputation_lower_limit",
"reputation_upper_limit",
"footer_links",
"gdpr_compliance",
"impersonation",
"impersonation_require_reason",
"default_token_duration",
"default_token_length",
"pagination_default_page_size",
"pagination_max_page_size",
"flags",
]
def create_system_settings(apps, schema_editor):
db_alias = schema_editor.connection.alias
SystemSettings = apps.get_model("authentik_admin", "SystemSettings")
if SystemSettings.objects.using(db_alias).exists():
return
settings = {}
with connections[db_alias].cursor() as cursor:
cursor.execute(
"SELECT 1 FROM information_schema.tables WHERE table_name = 'authentik_tenants_tenant'"
)
if cursor.fetchone() is not None:
cursor.execute(
f"SELECT {', '.join(FIELDS)} FROM authentik_tenants_tenant WHERE schema_name = %s", # nosec
[CONFIG.get("postgresql.default_schema")],
)
tenant = cursor.fetchone()
if tenant is not None:
settings = dict(zip(FIELDS, tenant, strict=True))
# The raw cursor returns jsonb as str, which JSONField would encode again
for field in JSON_FIELDS:
if isinstance(settings[field], str):
settings[field] = loads(settings[field])
SystemSettings.objects.using(db_alias).create(**settings)
class Migration(migrations.Migration):
initial = True
dependencies = [
("authentik_tenants", "0009_alter_tenant_base_url"),
]
operations = [
migrations.CreateModel(
name="VersionHistory",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("timestamp", models.DateTimeField()),
("version", models.TextField()),
("build", models.TextField()),
],
options={
"verbose_name": "Version history",
"verbose_name_plural": "Version history",
"db_table": "authentik_version_history",
"ordering": ("-timestamp",),
"managed": False,
"default_permissions": [],
},
),
migrations.CreateModel(
name="SystemSettings",
fields=[
("id", models.BooleanField(default=True, primary_key=True, serialize=False)),
(
"avatars",
models.TextField(
default="gravatar,initials",
help_text="Configure how authentik should show avatars for users.",
),
),
(
"base_url",
models.TextField(
blank=True,
default="",
help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
validators=[
authentik.lib.models.DomainlessURLValidator(
message="Enter a valid URL, for example https://authentik.company",
schemes=("http", "https"),
)
],
),
),
(
"default_user_change_name",
models.BooleanField(
default=True, help_text="Enable the ability for users to change their name."
),
),
(
"default_user_change_email",
models.BooleanField(
default=False,
help_text="Enable the ability for users to change their email address.",
),
),
(
"default_user_change_username",
models.BooleanField(
default=False,
help_text="Enable the ability for users to change their username.",
),
),
(
"event_retention",
models.TextField(
default="days=365",
help_text="Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3,seconds=2).",
validators=[authentik.lib.utils.time.timedelta_string_validator],
),
),
(
"reputation_lower_limit",
models.IntegerField(
default=-5,
help_text="Reputation cannot decrease lower than this value. Zero or negative.",
validators=[django.core.validators.MaxValueValidator(0)],
),
),
(
"reputation_upper_limit",
models.IntegerField(
default=5,
help_text="Reputation cannot increase higher than this value. Zero or positive.",
validators=[django.core.validators.MinValueValidator(0)],
),
),
(
"footer_links",
models.JSONField(
blank=True,
default=list,
help_text="The option configures the footer links on the flow executor pages.",
),
),
(
"gdpr_compliance",
models.BooleanField(
default=True,
help_text="When enabled, all the events caused by a user will be deleted upon the user's deletion.",
),
),
(
"impersonation",
models.BooleanField(
default=True, help_text="Globally enable/disable impersonation."
),
),
(
"impersonation_require_reason",
models.BooleanField(
default=True,
help_text="Require administrators to provide a reason for impersonating a user.",
),
),
(
"default_token_duration",
models.TextField(
default="days=1",
help_text="Default token duration",
validators=[authentik.lib.utils.time.timedelta_string_validator],
),
),
(
"default_token_length",
models.PositiveIntegerField(
default=60,
help_text="Default token length",
validators=[django.core.validators.MinValueValidator(1)],
),
),
(
"pagination_default_page_size",
models.PositiveIntegerField(
default=20,
help_text="Default page size for API responses, if no size was requested.",
),
),
(
"pagination_max_page_size",
models.PositiveIntegerField(default=100, help_text="Maximum page size"),
),
("flags", models.JSONField(default=dict)),
],
options={
"verbose_name": "System settings",
"verbose_name_plural": "System settings",
"default_permissions": [],
},
bases=(authentik.lib.models.InternallyManagedMixin, models.Model),
),
migrations.RunPython(code=create_system_settings, reverse_code=migrations.RunPython.noop),
]
@@ -1,28 +0,0 @@
# Generated by Django 5.2.17 on 2026-09-30 08:15
import authentik.lib.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("authentik_admin", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="systemsettings",
name="base_url",
field=models.TextField(
default="",
help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
validators=[
authentik.lib.models.DomainlessURLValidator(
message="Enter a valid URL, for example https://authentik.company",
schemes=("http", "https"),
)
],
),
),
]
+1 -124
View File
@@ -1,130 +1,7 @@
"""authentik admin models"""
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import IntegrityError, models
from django.db import models
from django.utils.translation import gettext_lazy as _
from rest_framework.serializers import Serializer
from authentik.lib.models import (
DomainlessURLValidator,
InternallyManagedMixin,
SerializerModel,
)
from authentik.lib.utils.time import timedelta_string_validator
DEFAULT_TOKEN_DURATION = "days=1" # nosec
DEFAULT_TOKEN_LENGTH = 60
DEFAULT_REPUTATION_LOWER_LIMIT = -5
DEFAULT_REPUTATION_UPPER_LIMIT = 5
class SystemSettings(InternallyManagedMixin, SerializerModel):
"""Global settings for this authentik instance"""
id = models.BooleanField(primary_key=True, default=True)
avatars = models.TextField(
help_text=_("Configure how authentik should show avatars for users."),
default="gravatar,initials",
)
base_url = models.TextField(
default="",
validators=[
DomainlessURLValidator(
schemes=("http", "https"),
message=_("Enter a valid URL, for example https://authentik.company"),
)
],
help_text=_(
"Configure the base URL under which this authentik instance is "
"reachable, e.g. https://authentik.company"
),
)
default_user_change_name = models.BooleanField(
help_text=_("Enable the ability for users to change their name."), default=True
)
default_user_change_email = models.BooleanField(
help_text=_("Enable the ability for users to change their email address."), default=False
)
default_user_change_username = models.BooleanField(
help_text=_("Enable the ability for users to change their username."), default=False
)
event_retention = models.TextField(
default="days=365",
validators=[timedelta_string_validator],
help_text=_(
"Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3,seconds=2)."
),
)
reputation_lower_limit = models.IntegerField(
help_text=_("Reputation cannot decrease lower than this value. Zero or negative."),
default=DEFAULT_REPUTATION_LOWER_LIMIT,
validators=[MaxValueValidator(0)],
)
reputation_upper_limit = models.IntegerField(
help_text=_("Reputation cannot increase higher than this value. Zero or positive."),
default=DEFAULT_REPUTATION_UPPER_LIMIT,
validators=[MinValueValidator(0)],
)
footer_links = models.JSONField(
help_text=_("The option configures the footer links on the flow executor pages."),
default=list,
blank=True,
)
gdpr_compliance = models.BooleanField(
help_text=_(
"When enabled, all the events caused by a user "
"will be deleted upon the user's deletion."
),
default=True,
)
impersonation = models.BooleanField(
help_text=_("Globally enable/disable impersonation."), default=True
)
impersonation_require_reason = models.BooleanField(
help_text=_("Require administrators to provide a reason for impersonating a user."),
default=True,
)
default_token_duration = models.TextField(
help_text=_("Default token duration"),
default=DEFAULT_TOKEN_DURATION,
validators=[timedelta_string_validator],
)
default_token_length = models.PositiveIntegerField(
help_text=_("Default token length"),
default=DEFAULT_TOKEN_LENGTH,
validators=[MinValueValidator(1)],
)
pagination_default_page_size = models.PositiveIntegerField(
help_text=_("Default page size for API responses, if no size was requested."),
default=20,
)
pagination_max_page_size = models.PositiveIntegerField(
help_text=_("Maximum page size"),
default=100,
)
flags = models.JSONField(default=dict)
def save(self, *args, **kwargs):
if not self.pk:
raise IntegrityError("Only one instance of system settings is allowed")
super().save(*args, **kwargs)
@property
def serializer(self) -> Serializer:
from authentik.admin.api.settings import SettingsSerializer
return SettingsSerializer
def __str__(self) -> str:
return "System settings"
class Meta:
verbose_name = _("System settings")
verbose_name_plural = _("System settings")
default_permissions = []
class VersionHistory(models.Model):
-8
View File
@@ -1,17 +1,9 @@
from django.db.models.signals import post_save
from django.dispatch import receiver
from authentik.admin.models import SystemSettings
from authentik.admin.tasks import _set_prom_info
from authentik.admin.utils import clear_system_settings_cache
from authentik.root.signals import post_startup
@receiver(post_startup)
def post_startup_admin_metrics(sender, **_):
_set_prom_info()
@receiver(post_save, sender=SystemSettings)
def system_settings_saved(**_):
clear_system_settings_cache()
+17 -62
View File
@@ -1,12 +1,9 @@
"""authentik admin tasks"""
from enum import StrEnum
from django.core.cache import cache
from django.utils.translation import gettext_lazy as _
from dramatiq import actor
from packaging.version import parse
from pydantic import BaseModel, Field, HttpUrl, ValidationError
from requests import RequestException
from structlog.stdlib import get_logger
@@ -18,10 +15,10 @@ from authentik.lib.utils.http import get_http_session
from authentik.tasks.middleware import CurrentTask
LOGGER = get_logger()
VERSION_CACHE_KEY = "goauthentik.io/admin/latest_version"
VERSION_NULL = "0.0.0"
VERSION_CACHE_KEY = "authentik_latest_version"
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
LOCAL_VERSION = parse(authentik_version())
VERSION_URL = "https://version.goauthentik.io/versions/authentik/latest.json"
def _set_prom_info():
@@ -29,90 +26,48 @@ def _set_prom_info():
PROM_INFO.info(
{
"version": authentik_version(),
"latest": UpdateVersionInfo.get_cached().version,
"latest": cache.get(VERSION_CACHE_KEY, ""),
"build_hash": authentik_build_hash(),
}
)
class UpdateVersionReason(StrEnum):
"""Reason why an authentik update was released"""
bugfix = "bugfix"
feature = "feature"
security = "security"
other = "other"
class UpdateVersionInfo(BaseModel):
version: str
changelog: str
changelog_url: HttpUrl
reason: UpdateVersionReason
valid: bool = Field(default=True)
@staticmethod
def get_invalid() -> UpdateVersionInfo:
return UpdateVersionInfo(
version="0.0.0",
changelog="",
changelog_url="https://docs.goauthentik.io",
reason=UpdateVersionReason.other,
valid=False,
)
@staticmethod
def get_cached() -> UpdateVersionInfo:
return cache.get(VERSION_CACHE_KEY, UpdateVersionInfo.get_invalid())
@staticmethod
def cache_invalid():
cache.set(
VERSION_CACHE_KEY,
UpdateVersionInfo(
version="0.0.0",
changelog="",
changelog_url="",
reason=UpdateVersionReason.other,
valid=False,
),
VERSION_CACHE_TIMEOUT,
)
@actor(description=_("Update latest version info."))
def update_latest_version():
self = CurrentTask.get_task()
if CONFIG.get_bool("disable_update_check"):
UpdateVersionInfo.cache_invalid()
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
self.info("Version check disabled.")
return
try:
response = get_http_session().get(VERSION_URL)
response = get_http_session().get(
"https://version.goauthentik.io/version.json",
)
response.raise_for_status()
data = response.json()
upstream_version = UpdateVersionInfo.model_validate(data.get("stable", {}))
upstream_version = data.get("stable", {}).get("version")
cache.set(VERSION_CACHE_KEY, upstream_version, VERSION_CACHE_TIMEOUT)
self.info("Successfully updated latest Version")
_set_prom_info()
# Check if upstream version is newer than what we're running,
# and if no event exists yet, create one.
if LOCAL_VERSION < parse(upstream_version.version):
if LOCAL_VERSION < parse(upstream_version):
# Event has already been created, don't create duplicate
if Event.objects.filter(
action=EventAction.UPDATE_AVAILABLE,
context__new_version=upstream_version.version,
context__new_version=upstream_version,
).exists():
return
Event.new(
EventAction.UPDATE_AVAILABLE,
message=_(
"New version {version} available!".format(version=upstream_version.version)
"New version {version} available!".format(
version=upstream_version,
)
),
new_version=upstream_version.version,
changelog=upstream_version.changelog_url,
reason=upstream_version.reason,
new_version=upstream_version,
changelog=data.get("stable", {}).get("changelog_url"),
).save()
except (RequestException, IndexError, ValidationError) as exc:
UpdateVersionInfo.cache_invalid()
except (RequestException, IndexError) as exc:
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
raise exc
@@ -1,74 +0,0 @@
"""Tests for backfilling base_url during the system settings reconcile"""
from django.apps import apps
from django.test import TestCase
from authentik.admin.utils import get_system_settings
from authentik.blueprints.tests import reconcile_app
from authentik.events.logs import capture_logs
from authentik.lib.config import CONFIG
from authentik.outposts.apps import MANAGED_OUTPOST
from authentik.outposts.models import Outpost, OutpostConfig
class TestBaseURLBackfill(TestCase):
"""The system settings reconcile seeds base_url from the config value or the embedded
outpost host"""
def setUp(self):
super().setUp()
self.settings = get_system_settings()
self.settings.base_url = ""
self.settings.save()
@reconcile_app("authentik_outposts")
def test_backfill_from_outpost(self):
"""base_url is backfilled from the embedded outpost host, without a trailing slash"""
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
outpost.config = OutpostConfig(authentik_host="https://outpost.example.com/")
outpost.save()
with CONFIG.patch("web.base_url", ""):
apps.get_app_config("authentik_admin").system_settings()
self.settings.refresh_from_db()
self.assertEqual(self.settings.base_url, "https://outpost.example.com")
@reconcile_app("authentik_outposts")
def test_backfill_from_config(self):
"""The AUTHENTIK_WEB__BASE_URL config value takes precedence over the outpost host"""
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
outpost.config = OutpostConfig(authentik_host="https://outpost.example.com")
outpost.save()
with CONFIG.patch("web.base_url", "https://config.example.com"):
apps.get_app_config("authentik_admin").system_settings()
self.settings.refresh_from_db()
self.assertEqual(self.settings.base_url, "https://config.example.com")
def test_backfill_does_not_overwrite(self):
"""A configured base_url is never overwritten by the backfill"""
self.settings.base_url = "https://set.example.com"
self.settings.save()
with CONFIG.patch("web.base_url", "https://config.example.com"):
apps.get_app_config("authentik_admin").system_settings()
self.settings.refresh_from_db()
self.assertEqual(self.settings.base_url, "https://set.example.com")
@reconcile_app("authentik_outposts")
def test_backfill_discards_invalid_outpost_host(self):
"""An outpost host the settings API would reject is discarded rather than written,
since the backfill's `.update()` skips field validation"""
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
outpost.config = OutpostConfig(authentik_host="outpost.example.com")
outpost.save()
with CONFIG.patch("web.base_url", ""), capture_logs() as logs:
apps.get_app_config("authentik_admin").system_settings()
self.settings.refresh_from_db()
self.assertEqual(self.settings.base_url, "")
self.assertTrue(any("Discarding invalid base_url" in log.event for log in logs))
def test_backfill_no_outpost(self):
"""With no embedded outpost and no config value, base_url stays empty"""
Outpost.objects.filter(managed=MANAGED_OUTPOST).delete()
with CONFIG.patch("web.base_url", ""):
apps.get_app_config("authentik_admin").system_settings()
self.settings.refresh_from_db()
self.assertEqual(self.settings.base_url, "")
@@ -1,32 +0,0 @@
from django.http import HttpRequest, HttpResponse
from django.test import RequestFactory, TestCase
from authentik.admin.middleware import SystemSettingsMiddleware
from authentik.admin.models import SystemSettings
from authentik.admin.utils import get_system_settings
class TestSystemSettingsCache(TestCase):
def test_scoped_to_request(self):
"""Settings are only cached within a single request"""
seen = []
def view(request: HttpRequest) -> HttpResponse:
seen.extend([get_system_settings(), get_system_settings()])
return HttpResponse()
middleware = SystemSettingsMiddleware(view)
middleware(RequestFactory().get("/"))
middleware(RequestFactory().get("/"))
self.assertIs(seen[0], seen[1])
self.assertIsNot(seen[1], seen[2])
self.assertIs(seen[2], seen[3])
self.assertIsNot(get_system_settings(), get_system_settings())
def test_fresh_outside_requests(self):
"""System settings cache is not used outside of a request"""
first = get_system_settings()
SystemSettings.objects.filter(pk=True).update(avatars="none")
second = get_system_settings()
self.assertIsNot(first, second)
self.assertEqual(second.avatars, "none")
+7 -7
View File
@@ -1,12 +1,12 @@
"""test admin tasks"""
from django.apps import apps
from django.core.cache import cache
from django.test import TestCase
from requests_mock import Mocker
from authentik.admin.tasks import (
VERSION_URL,
UpdateVersionInfo,
VERSION_CACHE_KEY,
update_latest_version,
)
from authentik.events.models import Event, EventAction
@@ -29,9 +29,9 @@ class TestAdminTasks(TestCase):
def test_version_valid_response(self):
"""Test Update checker with valid response"""
with Mocker() as mocker, CONFIG.patch("disable_update_check", False):
mocker.get(VERSION_URL, json=RESPONSE_VALID)
mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
update_latest_version.send()
self.assertEqual(UpdateVersionInfo.get_cached().version, "99999999.9999999")
self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
self.assertTrue(
Event.objects.filter(
action=EventAction.UPDATE_AVAILABLE,
@@ -55,9 +55,9 @@ class TestAdminTasks(TestCase):
def test_version_error(self):
"""Test Update checker with invalid response"""
with Mocker() as mocker:
mocker.get(VERSION_URL, status_code=400)
mocker.get("https://version.goauthentik.io/version.json", status_code=400)
update_latest_version.send()
self.assertFalse(UpdateVersionInfo.get_cached().valid)
self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
self.assertFalse(
Event.objects.filter(
action=EventAction.UPDATE_AVAILABLE, context__new_version="0.0.0"
@@ -68,7 +68,7 @@ class TestAdminTasks(TestCase):
"""Test Update checker while its disabled"""
with CONFIG.patch("disable_update_check", True):
update_latest_version.send()
self.assertFalse(UpdateVersionInfo.get_cached().valid)
self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
def test_clear_update_notifications(self):
"""Test clear of previous notification"""
-2
View File
@@ -3,7 +3,6 @@
from django.urls import path
from authentik.admin.api.meta import AppsViewSet, ModelViewSet
from authentik.admin.api.settings import SettingsView
from authentik.admin.api.system import SystemView
from authentik.admin.api.version import VersionView
from authentik.admin.api.version_history import VersionHistoryViewSet
@@ -11,7 +10,6 @@ from authentik.admin.api.version_history import VersionHistoryViewSet
api_urlpatterns = [
("admin/apps", AppsViewSet, "apps"),
("admin/models", ModelViewSet, "models"),
path("admin/settings/", SettingsView.as_view(), name="system_settings"),
path("admin/version/", VersionView.as_view(), name="admin_version"),
("admin/version/history", VersionHistoryViewSet, "version_history"),
path("admin/system/", SystemView.as_view(), name="admin_system"),
-39
View File
@@ -1,39 +0,0 @@
"""authentik admin utils"""
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from authentik.admin.models import SystemSettings
_CTX_SYSTEM_SETTINGS = ContextVar[dict[str, SystemSettings] | None](
"authentik_system_settings", default=None
)
def get_system_settings() -> SystemSettings:
cache = _CTX_SYSTEM_SETTINGS.get()
if cache is None:
return SystemSettings.objects.get(pk=True)
if "settings" not in cache:
cache["settings"] = SystemSettings.objects.get(pk=True)
return cache["settings"]
@contextmanager
def system_settings_cache() -> Iterator[None]:
token = _CTX_SYSTEM_SETTINGS.set({})
try:
yield
finally:
_CTX_SYSTEM_SETTINGS.reset(token)
def clear_system_settings_cache() -> None:
if (cache := _CTX_SYSTEM_SETTINGS.get()) is not None:
cache.clear()
def normalize_base_url(value: str | None) -> str:
"""Normalize a configured base URL: strip whitespace and trailing slashes."""
return (value or "").strip().rstrip("/")
+2 -4
View File
@@ -6,7 +6,6 @@ from drf_spectacular.plumbing import build_object_type
from rest_framework import pagination
from rest_framework.response import Response
from authentik.admin.utils import get_system_settings
from authentik.api.search.ql import QLSearch
from authentik.api.v3.schema.pagination import PAGINATION
from authentik.api.v3.schema.search import AUTOCOMPLETE_SCHEMA
@@ -23,12 +22,11 @@ class Pagination(pagination.PageNumberPagination):
page_size_query_param = "page_size"
def get_page_size(self, request: Request) -> int:
settings = get_system_settings()
if self.page_size_query_param in request.query_params:
page_size = super().get_page_size(request)
if page_size is not None:
return min(page_size, settings.pagination_max_page_size)
return settings.pagination_default_page_size
return min(super().get_page_size(request), request.tenant.pagination_max_page_size)
return request.tenant.pagination_default_page_size
def get_paginated_response(self, data) -> Response:
previous_page_number = 0
-2
View File
@@ -11,8 +11,6 @@ class AKQLSchemaSerializer(DjangoQLSchemaSerializer):
if not isinstance(field, JSONSearchField):
continue
serialization["models"].update(field.get_nested_options(self))
# Ensure the related model exists, even with no suggested keys
serialization["models"].setdefault(field.relation(), {})
return serialization
def serialize_field(self, field):
-11
View File
@@ -96,14 +96,3 @@ class QLTest(APITestCase):
content = loads(res.content)
self.assertEqual(content["pagination"]["count"], 1)
self.assertEqual(content["results"][0]["username"], self.user.username)
def test_autocomplete_json_relation(self):
"""Test that the autocomplete schema includes the model a JSON field relates to,
even when no nested keys are suggested"""
self.client.force_login(self.user)
res = self.client.get(reverse("authentik_api:user-list"))
self.assertEqual(res.status_code, 200)
autocomplete = loads(res.content)["autocomplete"]
attributes = autocomplete["models"]["authentik_core.user"]["attributes"]
self.assertEqual(attributes["type"], "relation")
self.assertIn(attributes["relation"], autocomplete["models"])
+6 -1
View File
@@ -10,6 +10,9 @@ from authentik.admin.api.version_history import VersionHistoryViewSet
from authentik.api.v3.urls import router
from authentik.core.tests.utils import RequestFactory, create_test_admin_user
from authentik.lib.generators import generate_id
from authentik.tenants.api.domains import DomainViewSet
from authentik.tenants.api.tenants import TenantViewSet
from authentik.tenants.utils import get_current_tenant
class TestModelViewSets(TestCase):
@@ -39,6 +42,7 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
req = self.factory.get(
f"/?{urlencode({'ordering': ordering_field}, doseq=True)}", user=self.user
)
req.tenant = get_current_tenant()
res = view(req)
self.assertEqual(res.status_code, 200)
@@ -48,6 +52,7 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
req = self.factory.get(
f"/?{urlencode({'search': generate_id()}, doseq=True)}", user=self.user
)
req.tenant = get_current_tenant()
res = view(req)
self.assertEqual(res.status_code, 200)
@@ -63,6 +68,6 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
for _, viewset, _ in router.registry:
if not issubclass(viewset, ModelViewSet | ReadOnlyModelViewSet):
continue
full = viewset not in [VersionHistoryViewSet]
full = viewset not in [VersionHistoryViewSet, DomainViewSet, TenantViewSet]
for test, case in viewset_tester_factory(viewset, full=full).items():
setattr(TestModelViewSets, f"test_viewset_{viewset.__name__}_{test}", case)
+1 -1
View File
@@ -13,7 +13,7 @@ class LocalAnonRateThrottle(AnonRateThrottle):
protective layer amplifies DB load under flood.
Points the throttle's cache at the ``throttle`` LocMemCache alias instead.
Counters are per-process (per server worker)
Counters are per-process (per gunicorn worker)
"""
cache = caches["throttle"]
+1 -2
View File
@@ -20,7 +20,6 @@ from rest_framework.views import APIView
from authentik.admin.files.manager import get_file_manager
from authentik.admin.files.usage import FileUsage
from authentik.admin.utils import get_system_settings
from authentik.core.api.utils import PassiveSerializer
from authentik.events.context_processors.base import get_context_processors
from authentik.lib.config import CONFIG
@@ -79,7 +78,7 @@ class ConfigView(APIView):
for processor in get_context_processors():
if cap := processor.capability():
caps.append(cap)
if get_system_settings().impersonation:
if request.tenant.impersonation:
caps.append(Capabilities.CAN_IMPERSONATE)
if settings.DEBUG: # pragma: no cover
caps.append(Capabilities.CAN_DEBUG)
+58 -14
View File
@@ -20,6 +20,9 @@ class ManagedAppConfig(AppConfig):
logger: BoundLogger
RECONCILE_GLOBAL_CATEGORY: str = "global"
RECONCILE_TENANT_CATEGORY: str = "tenant"
def __init__(self, app_name: str, *args, **kwargs) -> None:
super().__init__(app_name, *args, **kwargs)
self.logger = get_logger().bind(app_name=app_name)
@@ -30,7 +33,8 @@ class ManagedAppConfig(AppConfig):
return super().ready()
def _on_startup_callback(self, sender, **_):
self._reconcile()
self._reconcile_global()
self._reconcile_tenant()
def import_related(self):
"""Automatically import related modules which rely on just being imported
@@ -65,20 +69,22 @@ class ManagedAppConfig(AppConfig):
"""Load module"""
import_module(path)
def _reconcile(self) -> None:
for name in dir(self):
def _reconcile(self, prefix: str) -> None:
for meth_name in dir(self):
# Check the attribute on the class to avoid evaluating @property descriptors.
# Using getattr(self, ...) on a @property would evaluate it, which can trigger
# expensive side effects (e.g. schedule_specs iterating all providers
# expensive side effects (e.g. tenant_schedule_specs iterating all providers
# and running PolicyEngine queries for every user).
class_attr = getattr(type(self), name, None)
class_attr = getattr(type(self), meth_name, None)
if class_attr is None or isinstance(class_attr, property):
continue
if not callable(class_attr):
continue
if not getattr(class_attr, "_authentik_managed_reconcile", False):
category = getattr(class_attr, "_authentik_managed_reconcile", None)
if category != prefix:
continue
meth = getattr(self, name)
meth = getattr(self, meth_name)
name = meth_name.replace(prefix, "")
try:
self.logger.debug("Starting reconciler", name=name)
meth()
@@ -87,16 +93,54 @@ class ManagedAppConfig(AppConfig):
self.logger.warning("Failed to run reconcile", name=name, exc=exc)
@staticmethod
def reconcile(func: Callable):
"""Mark a function to be called on startup"""
func._authentik_managed_reconcile = True
def reconcile_tenant(func: Callable):
"""Mark a function to be called on startup (for each tenant)"""
func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_TENANT_CATEGORY
return func
@staticmethod
def reconcile_global(func: Callable):
"""Mark a function to be called on startup (globally)"""
func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_GLOBAL_CATEGORY
return func
@property
def schedule_specs(self) -> list[ScheduleSpec]:
"""Get a list of schedule specs that must exist"""
def tenant_schedule_specs(self) -> list[ScheduleSpec]:
"""Get a list of schedule specs that must exist in each tenant"""
return []
@property
def global_schedule_specs(self) -> list[ScheduleSpec]:
"""Get a list of schedule specs that must exist in the default tenant"""
return []
def _reconcile_tenant(self) -> None:
"""reconcile ourselves for tenanted methods"""
from authentik.tenants.models import Tenant
try:
tenants = list(Tenant.objects.filter(ready=True))
except (DatabaseError, ProgrammingError, InternalError) as exc:
self.logger.debug("Failed to get tenants to run reconcile", exc=exc)
return
for tenant in tenants:
with tenant:
self._reconcile(self.RECONCILE_TENANT_CATEGORY)
def _reconcile_global(self) -> None:
"""
reconcile ourselves for global methods.
Used for signals, tasks, etc. Database queries should not be made in here.
"""
from django_tenants.utils import get_public_schema_name, schema_context
try:
with schema_context(get_public_schema_name()):
self._reconcile(self.RECONCILE_GLOBAL_CATEGORY)
except (DatabaseError, ProgrammingError, InternalError) as exc:
self.logger.debug("Failed to access database to run reconcile", exc=exc)
return
class AuthentikBlueprintsConfig(ManagedAppConfig):
"""authentik Blueprints app"""
@@ -110,14 +154,14 @@ class AuthentikBlueprintsConfig(ManagedAppConfig):
super().import_models()
self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
@ManagedAppConfig.reconcile
@ManagedAppConfig.reconcile_global
def tasks_middlewares(self):
from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
get_broker().add_middleware(BlueprintWatcherMiddleware())
@property
def schedule_specs(self) -> list[ScheduleSpec]:
def tenant_schedule_specs(self) -> list[ScheduleSpec]:
from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
return [
@@ -8,6 +8,7 @@ from structlog.stdlib import get_logger
from authentik.blueprints.models import BlueprintInstance
from authentik.blueprints.v1.importer import Importer
from authentik.tenants.models import Tenant
LOGGER = get_logger()
@@ -18,19 +19,21 @@ class Command(BaseCommand):
@no_translations
def handle(self, *args, blueprints: list[str], dry_run: bool, **options):
"""Apply all blueprints in order, abort when one fails to import"""
for blueprint_path in blueprints:
content = BlueprintInstance(path=blueprint_path).retrieve()
importer = Importer.from_string(content)
valid, logs = importer.validate()
if not valid:
self.stderr.write("Blueprint invalid")
for log in logs:
self.stderr.write(f"\t{log.logger}: {log.event}: {log.attributes}")
sys_exit(1)
if not dry_run:
importer.apply()
else:
LOGGER.info("Dry-run enabled, not applying blueprint")
for tenant in Tenant.objects.filter(ready=True):
with tenant:
for blueprint_path in blueprints:
content = BlueprintInstance(path=blueprint_path).retrieve()
importer = Importer.from_string(content)
valid, logs = importer.validate()
if not valid:
self.stderr.write("Blueprint invalid")
for log in logs:
self.stderr.write(f"\t{log.logger}: {log.event}: {log.attributes}")
sys_exit(1)
if not dry_run:
importer.apply()
else:
LOGGER.info("Dry-run enabled, not applying blueprint")
def add_arguments(self, parser: ArgumentParser):
parser.add_argument("--dry-run", action="store_true", default=False)
@@ -1,18 +1,19 @@
"""Export blueprint of current authentik install"""
from django.core.management.base import BaseCommand, no_translations
from django.core.management.base import no_translations
from structlog.stdlib import get_logger
from authentik.blueprints.v1.exporter import Exporter
from authentik.tenants.management import TenantCommand
LOGGER = get_logger()
class Command(BaseCommand):
class Command(TenantCommand):
"""Export blueprint of current authentik install"""
@no_translations
def handle(self, *args, **options):
def handle_per_tenant(self, *args, **options):
"""Export blueprint of current authentik install"""
exporter = Exporter()
self.stdout.write(exporter.export_to_string())
+3 -109
View File
@@ -1,19 +1,14 @@
"""Test blueprints v1"""
from os import chmod, environ, unlink, write
from pathlib import Path
from tempfile import mkstemp
from uuid import UUID
from django.db.models.signals import post_save
from django.test import TransactionTestCase
from django.utils.text import slugify
from yaml import load
from authentik.blueprints.models import BlueprintInstance
from authentik.blueprints.tests import apply_blueprint
from authentik.blueprints.v1.common import BlueprintLoader, KeyOf
from authentik.blueprints.v1.exporter import Exporter, FlowExporter
from authentik.blueprints.v1.common import BlueprintLoader
from authentik.blueprints.v1.exporter import FlowExporter
from authentik.blueprints.v1.importer import Importer, transaction_rollback
from authentik.core.models import Group
from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding
@@ -328,113 +323,12 @@ class TestBlueprintsV1(TransactionTestCase):
exporter = FlowExporter(flow)
export_yaml = exporter.export_to_string()
binding_pks = []
def capture_binding_pk(sender, instance, **kwargs):
binding_pks.append(instance.policy_binding_uuid)
# Inspect the signal instance: reloading from the database would hide a string UUID.
post_save.connect(capture_binding_pk, sender=PolicyBinding)
try:
importer = Importer.from_string(export_yaml)
self.assertTrue(importer.validate()[0])
self.assertTrue(importer.apply())
finally:
post_save.disconnect(capture_binding_pk, sender=PolicyBinding)
self.assertTrue(binding_pks)
for binding_pk in binding_pks:
self.assertIsInstance(binding_pk, UUID)
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
def test_export_uses_keyof_references(self):
"""Test that exporting a flow rewrites references between exported objects
as !KeyOf tags instead of raw primary keys"""
flow_slug = generate_id()
stage_name = generate_id()
policy_name = generate_id()
with transaction_rollback():
flow_policy = ExpressionPolicy.objects.create(
name=policy_name,
expression="return True",
)
flow = Flow.objects.create(
slug=flow_slug,
designation=FlowDesignation.AUTHENTICATION,
name=generate_id(),
title=generate_id(),
)
PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
user_login = UserLoginStage.objects.create(name=stage_name)
fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
exporter = FlowExporter(flow)
export = exporter.export()
export_yaml = exporter.export_to_string()
entries_by_model = {}
for entry in export.entries:
entries_by_model.setdefault(entry.model, []).append(entry)
flow_entry = entries_by_model["authentik_flows.flow"][0]
stage_entry = entries_by_model["authentik_stages_user_login.userloginstage"][0]
stage_binding_entry = entries_by_model["authentik_flows.flowstagebinding"][0]
policy_entry = entries_by_model["authentik_policies_expression.expressionpolicy"][0]
policy_binding_entries = entries_by_model["authentik_policies.policybinding"]
self.assertIsNotNone(flow_entry.id)
self.assertIsNotNone(stage_entry.id)
# ids are derived from a readable, unique, non-UUID field (slug/name) when available,
# rather than an opaque counter
self.assertEqual(flow_entry.id, f"flow-{slugify(flow_slug)}")
self.assertEqual(stage_entry.id, f"userloginstage-{slugify(stage_name)}")
# Policy is exported without any explicit extra identifiers, but its unique,
# non-UUID `name` field is still picked up automatically as a stable identifier
self.assertEqual(policy_entry.identifiers.get("name"), policy_name)
# The primary key is instance-local and not portable, so it must not be used as
# an identifier whenever a stable identifier could be found instead
for entry in (flow_entry, stage_entry, policy_entry):
self.assertNotIn("pk", entry.identifiers)
self.assertIsInstance(stage_binding_entry.identifiers["target"], KeyOf)
self.assertEqual(stage_binding_entry.identifiers["target"].id_from, flow_entry.id)
self.assertIsInstance(stage_binding_entry.identifiers["stage"], KeyOf)
self.assertEqual(stage_binding_entry.identifiers["stage"].id_from, stage_entry.id)
binding_targets = {pb.identifiers["target"].id_from for pb in policy_binding_entries}
self.assertIn(flow_entry.id, binding_targets)
self.assertIn(stage_binding_entry.id, binding_targets)
for policy_binding_entry in policy_binding_entries:
self.assertIsInstance(policy_binding_entry.identifiers["policy"], KeyOf)
self.assertEqual(policy_binding_entry.identifiers["policy"].id_from, policy_entry.id)
self.assertIn("!KeyOf", export_yaml)
importer = Importer.from_string(export_yaml)
self.assertTrue(importer.validate()[0])
self.assertTrue(importer.apply())
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
def test_export_default_blueprints_no_static_identifiers(self):
"""Test that exporting a full instance after applying all default blueprints
never falls back to an opaque, non-portable `pk` identifier, e.g. for models
such as FlowStageBinding that have no unique text field of their own"""
for blueprint_file in sorted(Path("blueprints/default").glob("*.yaml")):
rel_path = str(blueprint_file.relative_to("blueprints"))
importer = Importer.from_string(BlueprintInstance(path=rel_path).retrieve())
self.assertTrue(importer.validate()[0])
self.assertTrue(importer.apply())
export = Exporter().export()
for entry in export.entries:
self.assertNotIn(
"pk", entry.identifiers, f"{entry.model} entry has a static pk identifier"
)
def test_export_validate_import_prompt(self):
"""Test export and validate it"""
with transaction_rollback():
-214
View File
@@ -1,7 +1,6 @@
"""Test blueprints v1 tasks"""
from hashlib import sha512
from pathlib import Path
from tempfile import NamedTemporaryFile, mkdtemp
from django.test import TransactionTestCase
@@ -157,216 +156,3 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
instance.status,
BlueprintInstanceStatus.UNKNOWN,
)
@CONFIG.patch("blueprints_dir", TMP)
def test_valid_crlf(self):
"""Test discovered hash matches the applied hash for a file with CRLF line endings"""
blueprint_id = generate_id()
with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
file.write(
f"version: 1\r\nentries: []\r\nmetadata:\r\n name: {blueprint_id}\r\n".encode()
)
file.flush()
file_hash = sha512(Path(file.name).read_text(encoding="utf-8").encode()).hexdigest()
for _ in range(2):
blueprints_discovery.send()
instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
found = next(
found for found in blueprints_find() if found.path == Path(file.name).name
)
self.assertEqual(found.hash, file_hash)
self.assertEqual(instance.last_applied_hash, found.hash)
file.seek(0)
self.assertIn(b"\r\n", file.read())
def write_blueprint(self, file, value: str):
file.seek(0)
file.truncate()
file.write(f"version: 1\nentries: []\ncontext:\n secret: {value}\n")
file.flush()
return next(found for found in blueprints_find() if found.path == Path(file.name).name).hash
def write_secret(self, file, value: str):
file.seek(0)
file.truncate()
file.write(value)
file.flush()
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_content_changed(self):
"""Test hash changes when the contents of a referenced `!File` change"""
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
for label, reference in (
("direct", f"!File {secret.name}"),
("argument of another tag", f'!Format ["client-%s", !File {secret.name}]'),
("reached through a cycle", f"&anchor [*anchor, !File {secret.name}]"),
("reached through an alias", f"&anchor [!File {secret.name}]\n other: *anchor"),
):
with (
self.subTest(label),
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
):
self.write_secret(secret, "initial")
before = self.write_blueprint(file, reference)
self.write_secret(secret, "rotated")
self.assertNotEqual(before, self.write_blueprint(file, reference))
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_created(self):
"""Test hash changes when a referenced `!File` that was missing appears"""
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
secret_path = Path(TMP) / generate_id()
reference = f"!File {secret_path}"
before = self.write_blueprint(file, reference)
secret_path.write_text("created")
try:
after = self.write_blueprint(file, reference)
finally:
secret_path.unlink()
self.assertNotEqual(before, after)
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_removed(self):
"""Test hash changes when a referenced `!File` that existed disappears"""
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
secret_path = Path(TMP) / generate_id()
secret_path.write_text("present")
reference = f"!File {secret_path}"
try:
before = self.write_blueprint(file, reference)
finally:
secret_path.unlink()
self.assertNotEqual(before, self.write_blueprint(file, reference))
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_contents_swapped(self):
"""Test hash changes when two referenced `!File`s exchange their contents"""
with (
NamedTemporaryFile(mode="w+", dir=TMP) as first,
NamedTemporaryFile(mode="w+", dir=TMP) as second,
):
self.write_secret(first, "alpha")
self.write_secret(second, "beta")
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
reference = f"[!File {first.name}, !File {second.name}]"
before = self.write_blueprint(file, reference)
self.write_secret(first, "beta")
self.write_secret(second, "alpha")
self.assertNotEqual(before, self.write_blueprint(file, reference))
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_missing_and_readable_swapped(self):
"""Test hash changes when one referenced `!File` disappears as another appears
with the same contents"""
first = Path(TMP) / generate_id()
second = Path(TMP) / generate_id()
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
reference = f"[!File {first}, !File {second}]"
second.write_text("shared")
try:
before = self.write_blueprint(file, reference)
finally:
second.unlink()
first.write_text("shared")
try:
after = self.write_blueprint(file, reference)
finally:
first.unlink()
self.assertNotEqual(before, after)
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_hashed_once_per_route(self):
"""Test a referenced `!File` is folded into the hash once for each route to it"""
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
self.write_secret(secret, "initial")
for label, reference, routes in (
("cycle", f"&anchor [*anchor, !File {secret.name}]", 1),
("alias", f"&anchor [!File {secret.name}]\n other: *anchor", 2),
):
with (
self.subTest(label),
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
):
content = f"version: 1\nentries: []\ncontext:\n secret: {reference}\n"
expected = sha512(content.encode())
for _ in range(routes):
expected.update(sha512(b"initial").digest())
self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_content_unchanged(self):
"""Test hash is stable when a referenced `!File` does not change"""
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
self.write_secret(secret, "initial")
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
reference = f"!File {secret.name}"
self.assertEqual(
self.write_blueprint(file, reference),
self.write_blueprint(file, reference),
)
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_unreadable_hash_stable(self):
"""Test hash is stable when a referenced `!File` cannot be read"""
for label, reference in (
("missing file", f"!File {Path(TMP) / generate_id()}"),
("path from a tag", f'!File [!Env [{generate_id()}, "{TMP}/fallback"], "default"]'),
("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
("path no syscall can take", '!File "\\0"'),
("deeply nested", "[" * 50 + f'!File "{TMP}/fallback"' + "]" * 50),
):
with (
self.subTest(label),
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
):
self.assertEqual(
self.write_blueprint(file, reference),
self.write_blueprint(file, reference),
)
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_unreadable_discovery_continues(self):
"""Test a blueprint that cannot be hashed does not stop others being discovered"""
for label, reference in (
("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
("path no syscall can take", '!File "\\0"'),
("path outside the filesystem encoding", '!File "\\ud800"'),
("sequence containing itself", "&anchor [*anchor]"),
("mapping containing itself", "&anchor {key: *anchor}"),
("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
):
with (
self.subTest(label),
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as broken,
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as healthy,
):
broken.write(f"version: 1\nentries: []\ncontext:\n secret: {reference}\n")
broken.flush()
healthy.write(f"version: 1\nentries: []\nmetadata:\n name: {generate_id()}\n")
healthy.flush()
found = [blueprint.path for blueprint in blueprints_find()]
self.assertIn(Path(healthy.name).name, found)
self.assertIn(Path(broken.name).name, found)
@CONFIG.patch("blueprints_dir", TMP)
def test_file_tag_applied_on_change(self):
"""Test blueprint is re-applied when the contents of a referenced `!File` change"""
blueprint_id = generate_id()
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
self.write_secret(secret, "initial")
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
file.write(
f"version: 1\nentries: []\n"
f"metadata:\n name: {blueprint_id}\n"
f"context:\n secret: !File {secret.name}\n"
)
file.flush()
blueprints_discovery.send()
instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
before = instance.last_applied_hash
self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
self.write_secret(secret, "rotated")
blueprints_discovery.send()
instance.refresh_from_db()
self.assertNotEqual(instance.last_applied_hash, before)
+13 -187
View File
@@ -6,7 +6,6 @@ from copy import copy
from dataclasses import asdict, dataclass, field, is_dataclass
from enum import Enum
from functools import reduce
from itertools import count
from json import JSONDecodeError, loads
from operator import ixor
from os import getenv
@@ -15,11 +14,9 @@ from uuid import UUID
from deepmerge import always_merger
from django.apps import apps
from django.db.models import CharField, Model, Q, TextField, UniqueConstraint
from django.utils.text import slugify
from django.db.models import Model, Q
from rest_framework.exceptions import ValidationError
from rest_framework.fields import Field
from rest_framework.relations import ManyRelatedField, PrimaryKeyRelatedField
from rest_framework.serializers import Serializer
from structlog.stdlib import get_logger
from yaml import SafeDumper, SafeLoader, ScalarNode, SequenceNode
@@ -35,7 +32,7 @@ class UNSET:
"""Used to test whether a key has not been set."""
def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]:
def get_attrs(obj: SerializerModel) -> dict[str, Any]:
"""Get object's attributes via their serializer, and convert it to a normal dict"""
serializer: Serializer = obj.serializer(obj)
data = dict(serializer.data)
@@ -48,151 +45,7 @@ def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]:
data.pop(field_name, None)
if field_name.endswith("_set"):
data.pop(field_name, None)
return data, serializer.fields
def _relation_target_model(ser_field: Field) -> type[Model] | None:
"""Get the model a relational serializer field points to, if any"""
if isinstance(ser_field, ManyRelatedField):
ser_field = ser_field.child_relation
if isinstance(ser_field, PrimaryKeyRelatedField) and ser_field.queryset is not None:
return ser_field.queryset.model
return None
def resolve_references(
attrs: dict[str, Any], fields: dict[str, Field], reference_index: ReferenceIndex
) -> dict[str, Any]:
"""Replace any attrs value that references another exported object with a `KeyOf` tag"""
for name, _field in fields.items():
if name not in attrs or attrs[name] is None:
continue
target_model = _relation_target_model(_field)
if target_model is None:
continue
if isinstance(_field, ManyRelatedField):
attrs[name] = [
(
KeyOf(id_from=entry_id)
if (entry_id := reference_index.lookup(value, target_model))
else value
)
for value in attrs[name]
]
else:
entry_id = reference_index.lookup(attrs[name], target_model)
if entry_id:
attrs[name] = KeyOf(id_from=entry_id)
return attrs
def _stable_identifier_fields(model_class: type[Model]) -> list[str]:
"""List the names of unique, non-relational text fields on a model (other than its
primary key) that could serve as stable identifiers, portable across authentik instances"""
return [
model_field.attname
for model_field in model_class._meta.fields
if not model_field.primary_key
and isinstance(model_field, CharField | TextField)
and model_field.unique
]
def _is_stable_value(value: Any) -> bool:
"""A value is considered stable (portable across instances) if it's a non-empty
string that isn't a UUID, which is almost always instance-local (e.g. a random default)"""
if not value or not isinstance(value, str):
return False
try:
UUID(value)
return False
except ValueError:
return True
def _readable_key(obj: Model) -> str | None:
"""Find a unique, human-readable text field on `obj` (not a UUID) to make
a !KeyOf id easier to read than a bare counter, e.g. a slug or name."""
for field_name in _stable_identifier_fields(type(obj)):
value = getattr(obj, field_name, None)
if not _is_stable_value(value):
continue
slug = slugify(value)
if slug:
return slug
return None
def _unique_together_groups(model_class: type[Model]) -> Iterable[tuple[str, ...]]:
"""Field-name groups declared unique together on a model, via either the legacy
Meta.unique_together or a plain (unconditional) Meta.constraints UniqueConstraint"""
yield from model_class._meta.unique_together
for constraint in model_class._meta.constraints:
if not isinstance(constraint, UniqueConstraint):
continue
if not constraint.condition and constraint.fields:
yield constraint.fields
def _composite_identifier_fields(
model_class: type[Model], all_attrs: dict[str, Any], fields: dict[str, Field]
) -> list[str]:
"""When no single field can serve as a stable identifier, fall back to a composite
of fields that together identify the instance: a declared unique-together group if
one is fully known, otherwise every populated relation to another exported object
(e.g. a binding's target and policy), mirroring how such join objects are naturally
keyed. Portable across instances, as relations are resolved to !KeyOf tags."""
for group in _unique_together_groups(model_class):
if all(name in all_attrs and all_attrs[name] is not None for name in group):
return list(group)
return [
name
for name, ser_field in fields.items()
if name in all_attrs
and all_attrs[name] is not None
and _relation_target_model(ser_field) is not None
]
class ReferenceIndex:
"""Tracks exported model instances so relations between them can be
rewritten as !KeyOf references instead of raw primary keys."""
def __init__(self):
self._entries: dict[Any, tuple[type[Model], str]] = {}
self._used: set[str] = set()
self._seen_ids: set[str] = set()
self._counter = count(1)
def register(self, obj: Model) -> str:
"""Register an exported model instance, returning the id assigned to it"""
readable_key = _readable_key(obj)
entry_id = f"{obj._meta.model_name}-{readable_key or next(self._counter)}"
if entry_id in self._seen_ids:
entry_id = f"{entry_id}-{next(self._counter)}"
self._seen_ids.add(entry_id)
self._entries[obj.pk] = (type(obj), entry_id)
return entry_id
def id_for(self, obj: Model) -> str | None:
"""Get the id assigned to a previously registered model instance, if any"""
entry = self._entries.get(obj.pk)
return entry[1] if entry else None
def lookup(self, value: Any, target_model: type[Model]) -> str | None:
"""Look up the id of a registered model instance by its primary key,
provided it is an instance of `target_model`"""
entry = self._entries.get(value)
if entry and issubclass(entry[0], target_model):
self._used.add(entry[1])
return entry[1]
return None
def clear_unused_ids(self, entries: Iterable[BlueprintEntry], objects: Iterable[Model]) -> None:
"""Strip the id from any entry that is never referenced by a !KeyOf tag"""
for entry, obj in zip(entries, objects, strict=True):
if self.id_for(obj) not in self._used:
entry.id = None
return data
@dataclass
@@ -239,39 +92,20 @@ class BlueprintEntry:
self.__tag_contexts: list[YAMLTagContext] = []
@staticmethod
def from_model(
model: SerializerModel,
reference_index: ReferenceIndex | None = None,
) -> BlueprintEntry:
def from_model(model: SerializerModel, *extra_identifier_names: str) -> BlueprintEntry:
"""Convert a SerializerModel instance to a blueprint Entry"""
all_attrs, fields = get_attrs(model)
if reference_index is not None:
all_attrs = resolve_references(all_attrs, fields, reference_index)
identifiers = {
"pk": model.pk,
}
all_attrs = get_attrs(model)
identifier_names = [
field_name
for field_name in _stable_identifier_fields(type(model))
if field_name in all_attrs and _is_stable_value(all_attrs[field_name])
]
if not identifier_names:
identifier_names = _composite_identifier_fields(type(model), all_attrs, fields)
identifiers = {}
for identifier_name in identifier_names:
identifiers[identifier_name] = all_attrs.pop(identifier_name, None)
# Only fall back to the (instance-local, non-portable) primary key when no other
# stable identifier could be found
if not identifiers:
identifiers["pk"] = model.pk
entry = BlueprintEntry(
for extra_identifier_name in extra_identifier_names:
identifiers[extra_identifier_name] = all_attrs.pop(extra_identifier_name, None)
return BlueprintEntry(
identifiers=identifiers,
model=f"{model._meta.app_label}.{model._meta.model_name}",
attrs=all_attrs,
)
if reference_index is not None:
entry.id = reference_index.id_for(model)
return entry
def get_tag_context(
self,
@@ -398,14 +232,9 @@ class KeyOf(YAMLTag):
id_from: str
def __init__(
self,
loader: BlueprintLoader | None = None,
node: ScalarNode | None = None,
id_from: str | None = None,
) -> None:
def __init__(self, loader: BlueprintLoader, node: ScalarNode) -> None:
super().__init__()
self.id_from = node.value if node is not None else id_from
self.id_from = node.value
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
for _entry in blueprint.iter_entries():
@@ -904,9 +733,6 @@ class BlueprintDumper(SafeDumper):
self.add_representer(
BlueprintEntryDesiredState, lambda self, data: self.represent_str(data.value)
)
self.add_representer(
KeyOf, lambda self, data: self.represent_scalar("!KeyOf", data.id_from)
)
self.add_representer(None, lambda self, data: self.represent_str(str(data)))
def ignore_aliases(self, data):
+37 -67
View File
@@ -1,7 +1,6 @@
"""Blueprint exporter"""
from collections.abc import Iterable
from typing import Any
from uuid import UUID
from django.apps import apps
@@ -16,14 +15,13 @@ from authentik.blueprints.v1.common import (
BlueprintDumper,
BlueprintEntry,
BlueprintMetadata,
ReferenceIndex,
)
from authentik.blueprints.v1.importer import is_model_allowed
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_GENERATED
from authentik.events.models import Event
from authentik.flows.models import Flow, FlowStageBinding, Stage
from authentik.policies.models import Policy, PolicyBinding
from authentik.stages.prompt.models import Prompt, PromptStage
from authentik.stages.prompt.models import PromptStage
class Exporter:
@@ -38,21 +36,13 @@ class Exporter:
def get_entries(self) -> Iterable[BlueprintEntry]:
"""Get blueprint entries"""
reference_index = ReferenceIndex()
instances: list[Model] = []
for model in apps.get_models():
if not is_model_allowed(model):
continue
if model in self.excluded_models:
continue
for obj in self.get_model_instances(model):
instances.append(obj)
reference_index.register(obj)
entries = [
BlueprintEntry.from_model(obj, reference_index=reference_index) for obj in instances
]
reference_index.clear_unused_ids(entries, instances)
return entries
yield BlueprintEntry.from_model(obj)
def get_model_instances(self, model: type[Model]) -> QuerySet:
"""Return a queryset for `model`. Can be used to filter some
@@ -106,74 +96,54 @@ class FlowExporter(Exporter):
"pbm_uuid", flat=True
)
def _stages(self) -> Iterable[Stage]:
"""Get all stages attached to self.flow"""
return Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
def walk_stages(self) -> Iterable[BlueprintEntry]:
"""Convert all stages attached to self.flow into BlueprintEntry objects"""
stages = Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
for stage in stages:
if isinstance(stage, PromptStage):
pass
yield BlueprintEntry.from_model(stage, "name")
def _stage_bindings(self) -> Iterable[FlowStageBinding]:
"""Get all bindings attached to self.flow"""
return FlowStageBinding.objects.filter(target=self.flow).select_related()
def walk_stage_bindings(self) -> Iterable[BlueprintEntry]:
"""Convert all bindings attached to self.flow into BlueprintEntry objects"""
bindings = FlowStageBinding.objects.filter(target=self.flow).select_related()
for binding in bindings:
yield BlueprintEntry.from_model(binding, "target", "stage", "order")
def _policies(self) -> Iterable[Policy]:
"""Get all policies. This is done at the beginning of the export for stages that have
def walk_policies(self) -> Iterable[BlueprintEntry]:
"""Walk over all policies. This is done at the beginning of the export for stages that have
a direct foreign key to a policy."""
# Special case for PromptStage as that has a direct M2M to policy, we have to ensure
# all policies referenced in there we also include here
prompt_stages = PromptStage.objects.filter(flow=self.flow).values_list("pk", flat=True)
query = Q(bindings__in=self.pbm_uuids) | Q(promptstage__in=prompt_stages)
return Policy.objects.filter(query).select_related()
policies = Policy.objects.filter(query).select_related()
for policy in policies:
yield BlueprintEntry.from_model(policy)
def _policy_bindings(self) -> Iterable[PolicyBinding]:
"""Get all policybindings relative to us. This is run at the end of the export, as
def walk_policy_bindings(self) -> Iterable[BlueprintEntry]:
"""Walk over all policybindings relative to us. This is run at the end of the export, as
we are sure all objects exist now."""
return PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
bindings = PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
for binding in bindings:
yield BlueprintEntry.from_model(binding, "policy", "target", "order")
def _stage_prompts(self) -> Iterable[Prompt]:
"""Get all prompts associated with any PromptStages, deduplicated as multiple stages
may share the same prompt"""
def walk_stage_prompts(self) -> Iterable[BlueprintEntry]:
"""Walk over all prompts associated with any PromptStages"""
prompt_stages = PromptStage.objects.filter(flow=self.flow)
prompts: dict[Any, Prompt] = {}
for stage in prompt_stages:
for prompt in stage.fields.all():
prompts[prompt.pk] = prompt
return prompts.values()
yield BlueprintEntry.from_model(prompt)
def get_entries(self) -> Iterable[BlueprintEntry]:
reference_index = ReferenceIndex()
reference_index.register(self.flow)
prompts = list(self._stage_prompts()) if self.with_stage_prompts else []
policies = list(self._policies()) if self.with_policies else []
stages = list(self._stages())
stage_bindings = list(self._stage_bindings())
policy_bindings = list(self._policy_bindings()) if self.with_policies else []
for obj in (*prompts, *policies, *stages, *stage_bindings, *policy_bindings):
reference_index.register(obj)
objects = [self.flow, *prompts, *policies, *stages, *stage_bindings, *policy_bindings]
entries = [
BlueprintEntry.from_model(self.flow, reference_index=reference_index),
*(
BlueprintEntry.from_model(prompt, reference_index=reference_index)
for prompt in prompts
),
*(
BlueprintEntry.from_model(policy, reference_index=reference_index)
for policy in policies
),
*(
BlueprintEntry.from_model(stage, reference_index=reference_index)
for stage in stages
),
*(
BlueprintEntry.from_model(binding, reference_index=reference_index)
for binding in stage_bindings
),
*(
BlueprintEntry.from_model(binding, reference_index=reference_index)
for binding in policy_bindings
),
]
reference_index.clear_unused_ids(entries, objects)
entries = []
entries.append(BlueprintEntry.from_model(self.flow, "slug"))
if self.with_stage_prompts:
entries.extend(self.walk_stage_prompts())
if self.with_policies:
entries.extend(self.walk_policies())
entries.extend(self.walk_stages())
entries.extend(self.walk_stage_bindings())
if self.with_policies:
entries.extend(self.walk_policy_bindings())
return entries
-60
View File
@@ -1,60 +0,0 @@
"""Blueprint hashing"""
from collections.abc import Generator
from hashlib import sha512
from pathlib import Path
from typing import Any
from yaml import load
from yaml.error import YAMLError
from authentik.blueprints.v1.common import BlueprintLoader, File, YAMLTag
def iter_file_tags(value: Any, ancestors: frozenset[int] = frozenset()) -> Generator[File]:
"""Find all `!File` tags in a loaded blueprint, including tags used as arguments
of other tags. A node is not descended into again below itself; a node reached by
several routes is visited once per route."""
if id(value) in ancestors:
return
ancestors = ancestors | {id(value)}
if isinstance(value, File):
yield value
if isinstance(value, dict):
children = value.values()
elif isinstance(value, list | tuple):
children = value
elif isinstance(value, YAMLTag):
children = vars(value).values()
else:
return
for child in children:
yield from iter_file_tags(child, ancestors)
# One byte where a readable reference contributes a 64-byte digest
MISSING_FILE_MARKER = b"\0"
def blueprint_hash(content: str) -> str:
"""Hash a blueprint's content and the contents of the files it references with
`!File` tags"""
hasher = sha512(content.encode())
try:
raw_blueprint = load(content, BlueprintLoader)
except YAMLError:
return hasher.hexdigest()
for tag in iter_file_tags(raw_blueprint):
# Mapping-node tags have no path; nested tags cannot be resolved here
path = getattr(tag, "path", None)
if not isinstance(path, str):
continue
try:
referenced = Path(path).read_bytes()
except OSError, ValueError:
# An unreadable reference still takes its place in the sequence, so a file
# that goes missing while another appears cannot leave the hash unchanged
hasher.update(MISSING_FILE_MARKER)
continue
hasher.update(sha512(referenced).digest())
return hasher.hexdigest()
+1 -1
View File
@@ -323,7 +323,7 @@ class Importer:
model_instance = model()
# pk needs to be set on the model instance otherwise a new one will be generated
if "pk" in updated_identifiers:
model_instance.pk = model._meta.pk.to_python(updated_identifiers["pk"])
model_instance.pk = updated_identifiers["pk"]
serializer.instance = model_instance
return serializer
+1 -1
View File
@@ -44,7 +44,7 @@ class MetaModelRegistry:
def get_models(self):
"""Wrapper for django's `get_models` to list all models"""
models = list(apps.get_models())
models = apps.get_models()
for _, value in self.models.items():
models.append(value)
return sorted(models, key=str)
+13 -9
View File
@@ -1,6 +1,7 @@
"""v1 blueprints tasks"""
from dataclasses import asdict, dataclass, field
from hashlib import sha512
from pathlib import Path
from sys import platform
from uuid import UUID
@@ -30,7 +31,6 @@ from authentik.blueprints.models import (
BlueprintRetrievalFailed,
)
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, EntryInvalidError
from authentik.blueprints.v1.hash import blueprint_hash
from authentik.blueprints.v1.importer import Importer
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
from authentik.blueprints.v1.oci import OCI_PREFIX
@@ -40,6 +40,7 @@ from authentik.lib.config import CONFIG
from authentik.tasks.apps import PRIORITY_HIGH
from authentik.tasks.middleware import CurrentTask
from authentik.tasks.schedules.models import Schedule
from authentik.tenants.models import Tenant
LOGGER = get_logger()
@@ -91,16 +92,20 @@ class BlueprintEventHandler(FileSystemEventHandler):
def on_created(self, event: FileSystemEvent):
"""Process file creation"""
LOGGER.debug("new blueprint file created, starting discovery")
Schedule.dispatch_by_actor(blueprints_discovery)
for tenant in Tenant.objects.filter(ready=True):
with tenant:
Schedule.dispatch_by_actor(blueprints_discovery)
def on_modified(self, event: FileSystemEvent):
"""Process file modification"""
path = Path(event.src_path)
root = Path(CONFIG.get("blueprints_dir")).absolute()
rel_path = str(path.relative_to(root))
for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
LOGGER.debug("modified blueprint file, starting apply", instance=instance)
apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
for tenant in Tenant.objects.filter(ready=True):
with tenant:
for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
LOGGER.debug("modified blueprint file, starting apply", instance=instance)
apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
@actor(
@@ -124,9 +129,8 @@ def blueprints_find() -> list[BlueprintFile]:
if any(part for part in rel_path.parts if part.startswith(".")):
continue
with open(path, encoding="utf-8") as blueprint_file:
content = blueprint_file.read()
try:
raw_blueprint = load(content, BlueprintLoader)
raw_blueprint = load(blueprint_file.read(), BlueprintLoader)
except YAMLError as exc:
raw_blueprint = None
LOGGER.warning("failed to parse blueprint", exc=exc, path=str(rel_path))
@@ -137,7 +141,7 @@ def blueprints_find() -> list[BlueprintFile]:
if version != 1:
LOGGER.warning("invalid blueprint version", version=version, path=str(rel_path))
continue
file_hash = blueprint_hash(content)
file_hash = sha512(path.read_bytes()).hexdigest()
blueprint = BlueprintFile(str(rel_path), version, file_hash, int(path.stat().st_mtime))
blueprint.meta = from_dict(BlueprintMetadata, metadata) if metadata else None
blueprints.append(blueprint)
@@ -198,7 +202,7 @@ def apply_blueprint(instance_pk: UUID):
self.info(f"Blueprint {instance.name} is disabled, skipping")
return
blueprint_content = instance.retrieve()
file_hash = blueprint_hash(blueprint_content)
file_hash = sha512(blueprint_content.encode()).hexdigest()
importer = Importer.from_string(blueprint_content, instance.context)
if importer.blueprint.metadata:
instance.metadata = asdict(importer.blueprint.metadata)
+5 -5
View File
@@ -21,15 +21,15 @@ from rest_framework.response import Response
from rest_framework.validators import UniqueValidator
from rest_framework.viewsets import ModelViewSet
from authentik.admin.api.settings import FlagJSONField
from authentik.admin.flags import Flag
from authentik.admin.utils import get_system_settings
from authentik.brands.models import Brand
from authentik.brands.utils import session_safe_mode
from authentik.core.api.used_by import UsedByMixin
from authentik.core.api.utils import ModelSerializer, PassiveSerializer, ThemedUrlsSerializer
from authentik.crypto.validators import TLS_KEY_TYPES, KeyTypeValidator
from authentik.rbac.filters import SecretKeyFilter
from authentik.tenants.api.settings import FlagJSONField
from authentik.tenants.flags import Flag
from authentik.tenants.utils import get_current_tenant
class FooterLinkSerializer(PassiveSerializer):
@@ -95,8 +95,8 @@ class Themes(models.TextChoices):
def get_default_ui_footer_links():
"""Get default UI footer links based on current system settings"""
return get_system_settings().footer_links
"""Get default UI footer links based on current tenant settings"""
return get_current_tenant().footer_links
class PublicFlagsField(FlagJSONField):
+1 -2
View File
@@ -7,10 +7,9 @@ from django.http.response import HttpResponse
from django.utils.translation import override
from authentik.brands.utils import get_brand_for_request
from authentik.lib.tracing.otel_django_middleware import TracedMiddleware
class BrandMiddleware(TracedMiddleware):
class BrandMiddleware:
"""Add current brand to http request"""
get_response: Callable[[HttpRequest], HttpResponse]
+1 -1
View File
@@ -5,7 +5,6 @@ from json import loads
from django.urls import reverse
from rest_framework.test import APITestCase
from authentik.admin.flags import Flag
from authentik.blueprints.tests import apply_blueprint
from authentik.brands.models import SESSION_KEY_BRAND_SAFE_MODE, Brand
from authentik.core.models import Application
@@ -13,6 +12,7 @@ from authentik.core.tests.utils import create_test_admin_user, create_test_brand
from authentik.lib.generators import generate_id
from authentik.providers.oauth2.models import OAuth2Provider
from authentik.providers.saml.models import SAMLProvider
from authentik.tenants.flags import Flag
class TestBrands(APITestCase):
+3 -7
View File
@@ -9,10 +9,9 @@ from django.utils.html import _json_script_escapes
from django.utils.safestring import mark_safe
from authentik import authentik_full_version
from authentik.admin.models import SystemSettings
from authentik.admin.utils import get_system_settings
from authentik.brands.models import _BRAND_RELATED_FK_FIELDS, SESSION_KEY_BRAND_SAFE_MODE, Brand
from authentik.lib.tracing import active_tracer
from authentik.tenants.models import Tenant
_q_default = Q(default=True)
DEFAULT_BRAND = Brand(domain="fallback")
@@ -66,10 +65,7 @@ def get_brand_for_request(request: HttpRequest) -> Brand:
def context_processor(request: HttpRequest) -> dict[str, Any]:
"""Context Processor that injects brand object into every template"""
brand = getattr(request, "brand", DEFAULT_BRAND)
try:
footer_links = get_system_settings().footer_links
except SystemSettings.DoesNotExist:
footer_links = []
tenant = getattr(request, "tenant", Tenant())
# Suppress custom CSS for safe-mode sessions so misconfigured branding can't lock a
# user out of the UI needed to fix it.
safe_mode = session_safe_mode(request)
@@ -82,7 +78,7 @@ def context_processor(request: HttpRequest) -> dict[str, Any]:
"brand": brand,
"brand_css": brand_css,
"safe_mode": safe_mode,
"footer_links": footer_links,
"footer_links": tenant.footer_links,
"html_meta": {**active_tracer().get_http_meta()},
"version": authentik_full_version(),
}
@@ -1,7 +1,7 @@
from django.core.management.commands.migrate import Command as BaseCommand
from django_tenants.management.commands.migrate import Command as BaseCommand
from authentik.commands.management.commands import MigrationAutodetector
class Command(BaseCommand):
autodetector = MigrationAutodetector
autodetector = MigrationAutodetector # type: ignore[assignment]
@@ -0,0 +1,7 @@
from django_tenants.management.commands.migrate_schemas import Command as BaseCommand
from authentik.commands.management.commands import MigrationAutodetector
class Command(BaseCommand):
autodetector = MigrationAutodetector # type: ignore[assignment]
-15
View File
@@ -1,15 +0,0 @@
"""Common SAML Exceptions"""
from django.utils.translation import gettext_lazy as _
from authentik.lib.tracing.exceptions import TracingIgnoredException
ERROR_CANNOT_DECODE_REQUEST = _("Cannot decode SAML request.")
ERROR_SIGNATURE_REQUIRED_BUT_ABSENT = _(
"Verification Certificate configured, but request is not signed."
)
ERROR_FAILED_TO_VERIFY = _("Failed to verify signature")
class CannotHandleAssertion(TracingIgnoredException):
"""This processor does not handle this assertion."""
-10
View File
@@ -1,11 +1,8 @@
"""Shared SAML XML helpers"""
import base64
from collections.abc import Iterator
from typing import cast
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import Certificate
from lxml.etree import _Element
@@ -20,10 +17,3 @@ def get_element_text(element: _Element) -> str:
Reading the text via ``itertext()`` keeps the value equal to what was signed.
"""
return "".join(cast(Iterator[str], element.itertext()))
def x509_certificate_b64(cert: Certificate) -> str:
"""Encode a single certificate as base64 DER, the format used by ds:X509Certificate.
Encodes the parsed certificate, so a keypair holding a chain only yields the leaf."""
return base64.b64encode(cert.public_bytes(Encoding.DER)).decode()
+5 -31
View File
@@ -1,9 +1,7 @@
"""Application Roles API Viewset"""
from django.db.models import QuerySet
from django.http import HttpRequest
from django.utils.translation import gettext_lazy as _
from django_filters import FilterSet, ModelChoiceFilter
from rest_framework.exceptions import ValidationError
from rest_framework.viewsets import ModelViewSet
@@ -14,7 +12,6 @@ from authentik.core.api.utils import ModelSerializer
from authentik.core.models import (
Application,
ApplicationEntitlement,
User,
)
from authentik.lib.utils.reflection import ConditionalInheritance
@@ -44,33 +41,6 @@ class ApplicationEntitlementSerializer(AttributesMixinSerializer, ModelSerialize
]
class ApplicationEntitlementFilter(FilterSet):
"""Filter for application entitlements"""
for_user = ModelChoiceFilter(
queryset=User.objects.all(),
method="filter_for_user",
label=_(
"Entitlements assigned to this user, directly or through a group, "
"regardless of the user's access to the application."
),
)
def filter_for_user(
self, queryset: QuerySet[ApplicationEntitlement], name, value: User
) -> QuerySet[ApplicationEntitlement]:
return queryset.filter(pk__in=value.all_app_entitlements().values("pk"))
class Meta:
model = ApplicationEntitlement
fields = [
"pbm_uuid",
"name",
"app",
"for_user",
]
class ApplicationEntitlementViewSet(
ConditionalInheritance(
"authentik.enterprise.requests.api.apps.ApplicationEntitlementsRequestableMixin"
@@ -89,5 +59,9 @@ class ApplicationEntitlementViewSet(
"app__slug",
"attributes",
]
filterset_class = ApplicationEntitlementFilter
filterset_fields = [
"pbm_uuid",
"name",
"app",
]
ordering = ["name"]
+31 -36
View File
@@ -8,7 +8,6 @@ from django.db.models import Case, QuerySet
from django.db.models.expressions import When
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema
from guardian.shortcuts import get_objects_for_user
@@ -20,9 +19,7 @@ from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from structlog.stdlib import get_logger
from authentik.api.ordering import NullsAwareOrderingFilter
from authentik.api.pagination import Pagination
from authentik.api.search.ql import QLSearch
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
from authentik.core.api.providers import ProviderSerializer
from authentik.core.api.used_by import UsedByMixin
@@ -31,28 +28,22 @@ from authentik.core.api.utils import ModelSerializer, ThemedUrlsSerializer
from authentik.core.apps import AppAccessWithoutBindings
from authentik.core.models import Application, User
from authentik.events.logs import LogEventSerializer, capture_logs
from authentik.lib.config import CONFIG
from authentik.lib.utils.reflection import ConditionalInheritance
from authentik.policies.api.exec import PolicyTestResultSerializer
from authentik.policies.engine import ListPolicyEngine, PolicyEngine
from authentik.policies.types import CACHE_PREFIX, PolicyResult
from authentik.root.middleware import ClientIPMiddleware
from authentik.rbac.filters import ObjectFilter
LOGGER = get_logger()
def user_app_cache_key(
user_pk: str,
client_ip: str | None = None,
page_number: int | None = None,
only_with_launch_url: bool = False,
user_pk: str, page_number: int | None = None, only_with_launch_url: bool = False
) -> str:
"""Cache key where application list for user is saved"""
key = f"{CACHE_PREFIX}app_access/{user_pk}"
if only_with_launch_url:
key += "/launch"
if client_ip:
key += f"/{client_ip}"
if page_number:
key += f"/{page_number}"
return key
@@ -172,6 +163,14 @@ class ApplicationViewSet(
lookup_field = "slug"
ordering = ["name"]
def _filter_queryset_for_list(self, queryset: QuerySet) -> QuerySet:
"""Custom filter_queryset method which ignores guardian, but still supports sorting"""
for backend in list(self.filter_backends):
if backend == ObjectFilter:
continue
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
def _get_allowed_applications(
self, paginated_apps: Iterator[Application], user: User | None = None
) -> list[Application]:
@@ -264,6 +263,11 @@ class ApplicationViewSet(
@extend_schema(
parameters=[
OpenApiParameter(
name="superuser_full_list",
location=OpenApiParameter.QUERY,
type=OpenApiTypes.BOOL,
),
OpenApiParameter(
name="for_user",
location=OpenApiParameter.QUERY,
@@ -274,28 +278,23 @@ class ApplicationViewSet(
location=OpenApiParameter.QUERY,
type=OpenApiTypes.BOOL,
),
],
responses={
200: ApplicationSerializer(many=True),
},
operation_id="core_applications_accessible_list",
]
)
@action(
methods=["GET"],
detail=False,
url_path="@accessible",
# Access is decided by policies below, so skip the RBAC ObjectFilter
filter_backends=[QLSearch, DjangoFilterBackend, NullsAwareOrderingFilter],
)
def accessible(self, request: Request) -> Response:
"""List applications the user passes policies for, regardless of RBAC permissions"""
def list(self, request: Request) -> Response:
"""Custom list method that checks Policy based access instead of guardian"""
should_cache = request.query_params.get("search", "") == ""
superuser_full_list = (
str(request.query_params.get("superuser_full_list", "false")).lower() == "true"
)
if superuser_full_list and request.user.is_superuser:
return super().list(request)
only_with_launch_url = (
str(request.query_params.get("only_with_launch_url", "false")).lower()
) == "true"
queryset = self.filter_queryset(self.get_queryset())
queryset = self._filter_queryset_for_list(self.get_queryset())
queryset = queryset.exclude(meta_hide=True)
if only_with_launch_url:
# Pre-filter at DB level to skip expensive per-app policy evaluation
@@ -303,6 +302,7 @@ class ApplicationViewSet(
# and no provider, so no possible launch URL).
queryset = queryset.exclude(meta_launch_url="", provider__isnull=True)
paginator: Pagination = self.paginator
paginated_apps = paginator.paginate_queryset(queryset, request)
if "for_user" in request.query_params:
try:
@@ -316,23 +316,18 @@ class ApplicationViewSet(
raise ValidationError({"for_user": "User not found"})
except ValueError as exc:
raise ValidationError from exc
# Evaluate the full candidate set so counts and page boundaries reflect
# applications this user can access, rather than all applications.
allowed_applications = self._get_allowed_applications(queryset, user=for_user)
paginated_apps = paginator.paginate_queryset(allowed_applications, request)
allowed_applications = self._get_allowed_applications(paginated_apps, user=for_user)
serializer = self.get_serializer(paginated_apps, many=True)
serializer = self.get_serializer(allowed_applications, many=True)
return self.get_paginated_response(serializer.data)
paginated_apps = paginator.paginate_queryset(queryset, request)
allowed_applications = []
if not should_cache:
allowed_applications = self._get_allowed_applications(paginated_apps)
if should_cache:
client_ip = ClientIPMiddleware.get_client_ip(self.request)
allowed_applications = cache.get(
user_app_cache_key(
self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
self.request.user.pk, paginator.page.number, only_with_launch_url
)
)
if allowed_applications:
@@ -344,10 +339,10 @@ class ApplicationViewSet(
allowed_applications = self._get_allowed_applications(paginated_apps)
cache.set(
user_app_cache_key(
self.request.user.pk, client_ip, paginator.page.number, only_with_launch_url
self.request.user.pk, paginator.page.number, only_with_launch_url
),
allowed_applications,
timeout=CONFIG.get_int("cache.timeout_application_policies", 86400),
timeout=86400,
)
if only_with_launch_url:
+51 -62
View File
@@ -1,9 +1,11 @@
"""Groups API Viewset"""
from json import loads
from django.db.models import Prefetch
from django.http import Http404
from django.utils.translation import gettext as _
from django_filters.filters import ModelMultipleChoiceFilter
from django_filters.filters import CharFilter, ModelMultipleChoiceFilter
from django_filters.filterset import FilterSet
from djangoql.schema import BoolField, StrField
from drf_spectacular.utils import (
@@ -209,8 +211,6 @@ class GroupSerializer(AttributesMixinSerializer, ModelSerializer):
def get_users_obj(self, instance: Group) -> list[PartialUserSerializer] | None:
if not self._should_include_users:
return None
if (precomputed := getattr(instance, "_users_obj", None)) is not None:
return precomputed
return PartialUserSerializer(instance.users, many=True).data
@extend_schema_field(RelatedGroupSerializer(many=True))
@@ -350,6 +350,13 @@ class GroupSerializer(AttributesMixinSerializer, ModelSerializer):
class GroupFilter(FilterSet):
"""Filter for groups"""
attributes = CharFilter(
field_name="attributes",
lookup_expr="",
label="Attributes",
method="filter_attributes",
)
members_by_username = ModelMultipleChoiceFilter(
field_name="users__username",
to_field_name="username",
@@ -361,9 +368,26 @@ class GroupFilter(FilterSet):
distinct=False,
)
def filter_attributes(self, queryset, name, value):
"""Filter attributes by query args"""
try:
value = loads(value)
except ValueError:
raise ValidationError(detail="filter: failed to parse JSON") from None
if not isinstance(value, dict):
raise ValidationError(detail="filter: value must be key:value mapping")
qs = {}
for key, _value in value.items():
qs[f"attributes__{key}"] = _value
try:
_ = len(queryset.filter(**qs))
return queryset.filter(**qs)
except ValueError:
return queryset
class Meta:
model = Group
fields = ["name", "is_superuser", "members_by_pk", "members_by_username"]
fields = ["name", "is_superuser", "members_by_pk", "attributes", "members_by_username"]
class GroupViewSet(UsedByMixin, ModelViewSet):
@@ -392,19 +416,13 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
JSONSearchField(Group, "attributes"),
]
@property
def _should_include_users(self) -> bool:
return self.serializer_class(context={"request": self.request})._should_include_users
def get_queryset(self):
# Always prefetch parents and children since their PKs are always serialized
base_qs = Group.objects.all().prefetch_related("roles", "parents", "children")
# `list` builds both `users` and `users_obj`. Prefetching `users` would include duplicates
if getattr(self, "action", None) == "list":
return base_qs
if self._should_include_users:
if self.serializer_class(context={"request": self.request})._should_include_users:
# Only fetch fields needed by PartialUserSerializer to reduce DB load and instantiation
# time
base_qs = base_qs.prefetch_related(
Prefetch(
"users",
@@ -413,53 +431,22 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
)
return base_qs
def _load_memberships(self, groups: list[Group]) -> dict:
"""Load {group_pk: [user_pk]} in a single query, without instantiating User objects."""
group_pks = {group.pk for group in groups}
memberships = {group_pk: [] for group_pk in group_pks}
if not group_pks:
return memberships
for group_pk, user_pk in User.groups.through.objects.filter(
group_id__in=group_pks
).values_list("group_id", "user_id"):
memberships[group_pk].append(user_pk)
# We sort by PK so repeated requests are stable.
for user_pks in memberships.values():
user_pks.sort()
return memberships
def _attach_user_pk_lists(self, groups: list[Group], memberships: dict | None = None) -> None:
def _attach_user_pk_lists(self, groups: list[Group]) -> None:
"""Batch-load user PKs without materializing User objects."""
if memberships is None:
memberships = self._load_memberships(groups)
for group in groups:
group._users_pk_list = memberships[group.pk]
def _attach_users_obj(self, groups: list[Group], memberships: dict) -> None:
"""Load and serialize user objects exactly once"""
if not any(memberships.values()):
for group in groups:
group._users_obj = []
group_pks = {group.pk for group in groups}
if not group_pks:
return
# This is specifically done with a subquery to get around the Postgres parameter limit
members = User.objects.filter(
pk__in=User.groups.through.objects.filter(group_id__in=memberships.keys()).values(
"user_id"
)
).only(*PARTIAL_USER_SERIALIZER_MODEL_FIELDS)
users_by_group = {group_pk: [] for group_pk in group_pks}
serializer = PartialUserSerializer(context=self.get_serializer_context())
representations = {member.pk: serializer.to_representation(member) for member in members}
through = User.groups.through
for group_pk, user_pk in through.objects.filter(group_id__in=group_pks).values_list(
"group_id", "user_id"
):
users_by_group[group_pk].append(user_pk)
for group in groups:
group._users_obj = [
representations[user_pk]
for user_pk in memberships[group.pk]
if user_pk in representations
]
group._users_pk_list = users_by_group[group.pk]
@extend_schema(
parameters=[
@@ -470,18 +457,20 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
]
)
def list(self, request, *args, **kwargs):
if self.serializer_class(context={"request": self.request})._should_include_users:
return super().list(request, *args, **kwargs)
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
groups = list(page) if page is not None else list(queryset)
memberships = self._load_memberships(groups)
self._attach_user_pk_lists(groups, memberships)
if self._should_include_users:
self._attach_users_obj(groups, memberships)
serializer = self.get_serializer(groups, many=True)
if page is not None:
groups = list(page)
self._attach_user_pk_lists(groups)
serializer = self.get_serializer(groups, many=True)
return self.get_paginated_response(serializer.data)
groups = list(queryset)
self._attach_user_pk_lists(groups)
serializer = self.get_serializer(groups, many=True)
return Response(serializer.data)
@extend_schema(
+3 -3
View File
@@ -14,8 +14,8 @@ from rest_framework.viewsets import ModelViewSet
from authentik.api.validation import validate
from authentik.blueprints.api import ManagedSerializer
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
from authentik.core.api.groups import PartialUserSerializer
from authentik.core.api.used_by import UsedByMixin
from authentik.core.api.users import UserSerializer
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
from authentik.core.models import (
USER_ATTRIBUTE_TOKEN_EXPIRING,
@@ -34,7 +34,7 @@ from authentik.rbac.decorators import permission_required
class TokenSerializer(ManagedSerializer, ModelSerializer):
"""Token Serializer"""
user_obj = PartialUserSerializer(required=False, source="user", read_only=True)
user_obj = UserSerializer(required=False, source="user", read_only=True)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
@@ -124,7 +124,7 @@ class TokenViewSet(UsedByMixin, ModelViewSet):
"""Token Viewset"""
lookup_field = "identifier"
queryset = Token.objects.including_expired().select_related("user")
queryset = Token.objects.including_expired().all()
serializer_class = TokenSerializer
search_fields = [
"identifier",
+34 -26
View File
@@ -1,6 +1,7 @@
"""User API Views"""
from datetime import timedelta
from json import loads
from typing import Any
from django.contrib.auth import update_session_auth_hash
@@ -57,7 +58,6 @@ from rest_framework.validators import UniqueValidator
from rest_framework.viewsets import ModelViewSet
from structlog.stdlib import get_logger
from authentik.admin.utils import get_system_settings
from authentik.api.authentication import TokenAuthentication
from authentik.api.search.fields import (
ChoiceSearchField,
@@ -90,7 +90,6 @@ from authentik.core.models import (
UserTypes,
default_token_duration,
)
from authentik.core.signals import impersonation_changed
from authentik.core.views.user_switch import start_user_switch_flow
from authentik.endpoints.connectors.agent.auth import AgentAuth
from authentik.events.models import Event, EventAction
@@ -533,6 +532,13 @@ class UserRecoveryEmailSerializer(UserRecoveryLinkSerializer):
class UsersFilter(FilterSet):
"""Filter for users"""
attributes = CharFilter(
field_name="attributes",
lookup_expr="",
label="Attributes",
method="filter_attributes",
)
date_joined__lt = IsoDateTimeFilter(field_name="date_joined", lookup_expr="lt")
date_joined = IsoDateTimeFilter(field_name="date_joined")
date_joined__gt = IsoDateTimeFilter(field_name="date_joined", lookup_expr="gt")
@@ -552,10 +558,7 @@ class UsersFilter(FilterSet):
path = CharFilter(field_name="path")
path_startswith = CharFilter(field_name="path", method="filter_path_startswith")
# `type` is a column on the user table, so filtering on it can't duplicate rows. The
# MultipleChoiceFilter default (distinct=True) would make the count and every page
# sort all matching users.
type = MultipleChoiceFilter(choices=UserTypes.choices, field_name="type", distinct=False)
type = MultipleChoiceFilter(choices=UserTypes.choices, field_name="type")
groups_by_name = ModelMultipleChoiceFilter(
field_name="groups__name",
@@ -591,6 +594,23 @@ class UsersFilter(FilterSet):
return queryset
return queryset.filter(Q(path=value) | Q(path__startswith=f"{value}/"))
def filter_attributes(self, queryset, name, value):
"""Filter attributes by query args"""
try:
value = loads(value)
except ValueError:
raise ValidationError(_("filter: failed to parse JSON")) from None
if not isinstance(value, dict):
raise ValidationError(_("filter: value must be key:value mapping"))
qs = {}
for key, _value in value.items():
qs[f"attributes__{key}"] = _value
try:
__ = len(queryset.filter(**qs))
return queryset.filter(**qs)
except ValueError:
return queryset
class Meta:
model = User
fields = [
@@ -602,6 +622,7 @@ class UsersFilter(FilterSet):
"name",
"is_active",
"is_superuser",
"attributes",
"groups_by_name",
"groups_by_pk",
"roles_by_name",
@@ -658,19 +679,13 @@ class UserViewSet(
base_qs = base_qs.prefetch_related(
Prefetch("roles", queryset=Role.objects.all().only("uuid"))
)
# Annotate is_superuser to avoid N+1 query per user.
# Use two EXISTS subqueries (direct membership, membership through a descendant group)
# instead of one EXISTS with an OR across both join paths. PostgreSQL can't hash a
# subquery whose OR mixes two correlated conditions, so that form runs once per user row,
# including rows skipped by OFFSET, and a poor plan for the group ancestry join is paid
# for every row. Each separate EXISTS can run once per query as a hashed subplan.
# Annotate is_superuser to avoid N+1 query per user
base_qs = base_qs.annotate(
_annotated_is_superuser=Exists(
Group.objects.filter(is_superuser=True, users=OuterRef("pk"))
)
| Exists(
Group.objects.filter(
is_superuser=True, descendant_nodes__descendant__users=OuterRef("pk")
is_superuser=True,
).filter(
Q(users=OuterRef("pk")) | Q(descendant_nodes__descendant__users=OuterRef("pk"))
)
)
)
@@ -884,7 +899,7 @@ class UserViewSet(
instance=request._request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER],
context={"request": request},
).data
self.request.session.extend_expiry()
self.request.session.modified = True
return Response(serializer.initial_data)
def _update_session_hash_after_password_change(self, request: Request, user: User):
@@ -1026,7 +1041,7 @@ class UserViewSet(
@action(detail=True, methods=["POST"], permission_classes=[IsAuthenticated])
def impersonate(self, request: Request, pk: int) -> Response:
"""Impersonate a user"""
if not get_system_settings().impersonation:
if not request.tenant.impersonation:
LOGGER.debug("User attempted to impersonate", user=request.user)
return Response(status=401)
user_to_be = self.get_object()
@@ -1043,7 +1058,7 @@ class UserViewSet(
if user_to_be.pk == self.request.user.pk:
LOGGER.debug("User attempted to impersonate themselves", user=request.user)
return Response(status=401)
if not reason and get_system_settings().impersonation_require_reason:
if not reason and request.tenant.impersonation_require_reason:
LOGGER.debug(
"User attempted to impersonate without providing a reason",
user=request.user,
@@ -1055,10 +1070,6 @@ class UserViewSet(
Event.new(EventAction.IMPERSONATION_STARTED, reason=reason).from_http(request, user_to_be)
# Persist the new identity before outposts can start reauthorization.
request.session.save()
impersonation_changed.send(sender=self.__class__, session_key=request.session.session_key)
return Response(status=204)
@extend_schema(
@@ -1084,9 +1095,6 @@ class UserViewSet(
Event.new(EventAction.IMPERSONATION_ENDED).from_http(request, original_user)
request.session.save()
impersonation_changed.send(sender=self.__class__, session_key=request.session.session_key)
return Response(status=204)
@extend_schema(
+5 -5
View File
@@ -4,11 +4,11 @@ import os
from django.utils.translation import gettext_lazy as _
from authentik.admin.flags import Flag
from authentik.blueprints.apps import ManagedAppConfig
from authentik.lib.config import CONFIG
from authentik.lib.tracing import TRACER_DEFER_POSTFORK_ENV_VAR, setup_post_fork, setup_pre_fork
from authentik.tasks.schedules.common import ScheduleSpec
from authentik.tenants.flags import Flag
class Setup(Flag[bool], key="setup"):
@@ -36,8 +36,8 @@ class AuthentikCoreConfig(ManagedAppConfig):
def ready(self) -> None:
if CONFIG.get_bool("error_reporting.enabled", False):
setup_pre_fork()
# The server preloads the app before forking, some backends must finish
# initializing after the fork instead (see lifecycle/server.py's post_fork)
# Under gunicorn's preload_app, some backends must finish initializing after
# the fork instead (see lifecycle/gunicorn.conf.py's post_fork hook)
if not os.environ.get(TRACER_DEFER_POSTFORK_ENV_VAR):
setup_post_fork()
return super().ready()
@@ -46,7 +46,7 @@ class AuthentikCoreConfig(ManagedAppConfig):
super().import_related()
self.import_module("authentik.core.setup.signals")
@ManagedAppConfig.reconcile
@ManagedAppConfig.reconcile_tenant
def source_inbuilt(self):
"""Reconcile inbuilt source"""
from authentik.core.models import Source
@@ -60,7 +60,7 @@ class AuthentikCoreConfig(ManagedAppConfig):
)
@property
def schedule_specs(self) -> list[ScheduleSpec]:
def tenant_schedule_specs(self) -> list[ScheduleSpec]:
from authentik.core.tasks import clean_expired_models, clean_temporary_users
return [
+1 -12
View File
@@ -25,8 +25,6 @@ class PropertyMappingEvaluator(BaseEvaluator):
dry_run: bool
model: Model
# Types the expression may return (besides None); empty allows any type
allowed_types: list[type]
_compiled: CodeType | None = None
def __init__(
@@ -38,7 +36,6 @@ class PropertyMappingEvaluator(BaseEvaluator):
**kwargs,
):
self.model = model
self.allowed_types = []
if hasattr(model, "name"):
_filename = model.name
else:
@@ -87,15 +84,7 @@ class PropertyMappingEvaluator(BaseEvaluator):
def evaluate(self, *args, **kwargs) -> Any:
with PROPERTY_MAPPING_TIME.labels(mapping_name=self._filename).time():
value = super().evaluate(*args, **kwargs)
if value is None or not self.allowed_types:
return value
if not isinstance(value, tuple(self.allowed_types)):
allowed = ", ".join(t.__name__ for t in self.allowed_types)
raise TypeError(
f"Property mapping must return one of {allowed}, got {type(value).__name__}"
)
return value
return super().evaluate(*args, **kwargs)
def compile(self, expression: str | None = None) -> Any:
if not self._compiled:
@@ -14,7 +14,7 @@ class Command(BaseCommand):
configure(
docformat="markdown",
mermaid=True,
logo="https://goauthentik.io/img/icon_top_brand_color.svg",
logo="https://goauthentik.io/img/icon_top_brand_colour.svg",
)
pdoc(
"authentik",
@@ -1,11 +1,10 @@
"""Change user type"""
from django.core.management.base import BaseCommand
from authentik.core.models import User, UserTypes
from authentik.tenants.management import TenantCommand
class Command(BaseCommand):
class Command(TenantCommand):
"""Change user type"""
def add_arguments(self, parser):
@@ -13,7 +12,7 @@ class Command(BaseCommand):
parser.add_argument("--all", action="store_true", default=False)
parser.add_argument("usernames", nargs="*", type=str)
def handle(self, **options):
def handle_per_tenant(self, **options):
new_type = UserTypes(options["type"])
qs = (
User.objects.exclude_anonymous()
@@ -3,12 +3,13 @@
from importlib import import_module
from django.conf import settings
from django.core.management.base import BaseCommand
from authentik.tenants.management import TenantCommand
class Command(BaseCommand):
class Command(TenantCommand):
"""Delete all sessions"""
def handle(self, **options):
def handle_per_tenant(self, **options):
engine = import_module(settings.SESSION_ENGINE)
engine.SessionStore.clear_expired()
@@ -6,6 +6,8 @@ from django.core.management import call_command
from django.core.management.base import BaseCommand, no_translations
from guardian.management import create_anonymous_user
from authentik.tenants.models import Tenant
class Command(BaseCommand):
"""Repair missing permissions"""
@@ -13,11 +15,13 @@ class Command(BaseCommand):
@no_translations
def handle(self, *args, **options):
"""Check permissions for all apps"""
# See https://code.djangoproject.com/ticket/28417
# Remove potential lingering old permissions
call_command("remove_stale_contenttypes", "--no-input")
for tenant in Tenant.objects.filter(ready=True):
with tenant:
# See https://code.djangoproject.com/ticket/28417
# Remove potential lingering old permissions
call_command("remove_stale_contenttypes", "--no-input")
for app in apps.get_app_configs():
self.stdout.write(f"Checking app {app.name} ({app.label})\n")
create_permissions(app, verbosity=0)
create_anonymous_user(None, using="default")
for app in apps.get_app_configs():
self.stdout.write(f"Checking app {app.name} ({app.label})\n")
create_permissions(app, verbosity=0)
create_anonymous_user(None, using="default")
+1 -19
View File
@@ -11,7 +11,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest, HttpResponse, HttpResponseBadRequest
from django.utils.deprecation import MiddlewareMixin
from django.utils.functional import SimpleLazyObject
from django.utils.translation import check_for_language, override
from django.utils.translation import override
from structlog.contextvars import STRUCTLOG_KEY_PREFIX
from authentik.lib.tracing import active_tracer
@@ -95,24 +95,6 @@ class ImpersonateMiddleware:
return self.get_response(request)
class LocaleOverrideMiddleware:
"""Honor an explicit `?locale=` query parameter (a dev/test aid), validated against
the supported languages. Runs after every other locale source so that the web UI,
which reads the same parameter client-side, cannot disagree with the rendered shell."""
get_response: Callable[[HttpRequest], HttpResponse]
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
self.get_response = get_response
def __call__(self, request: HttpRequest) -> HttpResponse:
locale = request.GET.get("locale")
if locale and check_for_language(locale):
with override(locale):
return self.get_response(request)
return self.get_response(request)
class RequestIDMiddleware:
"""Add a unique ID to every request"""
+6 -10
View File
@@ -1,26 +1,22 @@
# Generated by Django 5.2.13 on 2026-04-21 18:49
from django.apps.registry import Apps
from django.db import connections, migrations
from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
def check_is_already_setup(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
from authentik.flows.models import FlowAuthenticationRequirement
from django.conf import settings
from authentik.flows.models import FlowAuthenticationRequirement
VersionHistory = apps.get_model("authentik_admin", "VersionHistory")
Flow = apps.get_model("authentik_flows", "Flow")
User = apps.get_model("authentik_core", "User")
db_alias = schema_editor.connection.alias
# Upgrading from a previous version. authentik_version_history is an unmanaged table
# created by the system migrations, so query it directly.
if not settings.TEST:
with connections[db_alias].cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM authentik_version_history")
if cursor.fetchone()[0] > 1:
return True
# Upgrading from a previous version
if not settings.TEST and VersionHistory.objects.using(db_alias).count() > 1:
return True
# OOBE flow sets itself to this authentication requirement once finished
if (
Flow.objects.using(db_alias)
@@ -6,8 +6,8 @@ from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("authentik_core", "0059_add_application_meta_hide"),
("authentik_rbac", "0010_remove_role_group_alter_role_name"),
("authentik_core", "0063_actor"),
("authentik_rbac", "0011_initialpermissionspermission"),
]
operations = [
@@ -1,13 +0,0 @@
# Generated by Django 5.2.17 on 2026-09-16 12:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("authentik_core", "0063_actor"),
("authentik_core", "0064_user_authentik_c_usernam_2f0e4b_idx"),
]
operations = []
Loaded 100 of 3391 files, more files were not shown because too many files have changed in this diff. Show more