Compare commits

..
Author SHA1 Message Date
Jens Langhammer e89174ba36 fork
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-19 14:14:28 +01:00
Jens Langhammer acd3ed797e back to 3.14
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-19 14:03:46 +01:00
Jens Langhammer 0bcf9ad3c1 Merge branch 'main' into core/embed-python
Signed-off-by: Jens Langhammer <[email protected]>

# Conflicts:
#	pyproject.toml
#	uv.lock
2026-10-19 13:57:25 +01:00
Jens Langhammer f7636d2435 test gc
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 13:46:36 +01:00
Jens Langhammer ce7bd89f9b Merge branch 'main' into core/embed-python
Signed-off-by: Jens Langhammer <[email protected]>

# Conflicts:
#	uv.lock
2026-10-16 12:32:33 +01:00
Jens Langhammer cd5b818a00 absolutely horrid darling
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 12:30:15 +01:00
Jens Langhammer 4c7921607b yeah sure man
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 11:49:59 +01:00
Jens Langhammer d83219faa3 python threads
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 11:25:09 +01:00
Jens Langhammer 295aa9710b test
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 10:39:59 +01:00
Jens Langhammer 3f833268bb test wsgi 2026-10-16 09:39:38 +00:00
Jens Langhammer 1722d988c3 swap image
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 01:34:30 +01:00
Jens Langhammer 3c63849ca3 free-threading..?
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 01:16:59 +01:00
Jens Langhammer 19ce0ea395 embed server
Signed-off-by: Jens Langhammer <[email protected]>
2026-10-16 00:51:17 +01:00
Jens Langhammer f9f310be82 core: run Python lifecycle commands in-process via pyo3
Bootstrap (wait_for_db, migrate) and the manage, dump_config and
test-all commands now run inside the authentik binary through the
embedded interpreter instead of spawning `python`. The interpreter
activates the virtualenv itself, since it isn't started from it.

Claude-Session: https://claude.ai/code/session_019wqL8VsUDCMXtG8EgpkBh8
2026-10-16 00:34:11 +01:00
1509 changed files with 17201 additions and 71249 deletions

No files matched your search

+1 -6
View File
@@ -7,6 +7,7 @@ allow = [
"CDLA-Permissive-2.0",
"ISC",
"MIT",
"MPL-2.0",
"OpenSSL",
"Unicode-3.0",
"Zlib",
@@ -44,9 +45,3 @@ allow = [
]
name = "aws-lc-rs"
exact = true
[advisories]
ignore = [
# https://github.com/askama-rs/askama/issues/594
{ id = "RUSTSEC-2026-0374", reason = "basic-toml is a build-time only dependency of the askama template engine, not shipped in the app or daemon; remove when askama drops basic-toml" },
]
+4 -4
View File
@@ -42,12 +42,12 @@ runs:
sudo rsync -a --delete /tmp/empty/ /usr/local/lib/android/
- name: Install uv
if: ${{ contains(inputs.dependencies, 'python') }}
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v5
uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v5
with:
enable-cache: true
- name: Setup python
if: ${{ contains(inputs.dependencies, 'python') }}
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v5
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v5
with:
python-version-file: "${{ inputs.working-directory }}pyproject.toml"
- name: Install Python deps
@@ -69,7 +69,7 @@ runs:
rustflags: ""
- name: Setup rust dependencies
if: ${{ contains(inputs.dependencies, 'rust') }}
uses: taiki-e/install-action@1919c4a95903d2c33e4a221102edca87309fc14b # v2
uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # 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 # v7.1.0
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: ${{ inputs.working-directory }}package.json
cache: pnpm
-6
View File
@@ -310,12 +310,6 @@ updates:
opentelemetry:
patterns:
- opentelemetry-*
ignore:
# Without this rule no 5.2.x patch PR gets opened.
# TODO: Remove this rule when moving to Django 6.
- dependency-name: "django"
update-types:
- "version-update:semver-major"
#endregion
@@ -28,14 +28,6 @@ on:
description: "Build args to pass to Docker"
type: string
default: ""
image-target:
description: "Dockerfile stage to build. Empty builds the last stage."
type: string
default: ""
image-tag-suffix:
description: "Suffix for the tags and the artifacts of an image variant that is built from another stage"
type: string
default: ""
should-cache:
description: "Whether a build cache should be created"
type: boolean
@@ -55,7 +47,7 @@ jobs:
packages: write
# Needed for checkout
contents: read
name: "Build ${{ inputs.image-name }}${{ inputs.image-tag-suffix }} on ${{ inputs.image-arch }}"
name: "Build ${{ inputs.image-name }} on ${{ inputs.image-arch }}"
runs-on: "${{ inputs.runs-on }}"
outputs:
image-digest: "${{ steps.build.outputs.digest }}"
@@ -82,7 +74,6 @@ jobs:
# inputs
context: .
file: "${{ inputs.image-dockerfile }}"
target: "${{ inputs.image-target }}"
build-args: "${{ inputs.image-build-args }}"
secrets: |
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
@@ -90,19 +81,19 @@ jobs:
# outputs
push: false
cache-from: |
type=registry,ref=ghcr.io/goauthentik/dev-${{ inputs.image-name }}:buildcache-${{ inputs.image-arch }}${{ inputs.image-tag-suffix }}-main
type=registry,ref=ghcr.io/goauthentik/dev-${{ inputs.image-name }}:buildcache-${{ inputs.image-arch }}${{ inputs.image-tag-suffix }}${{ inputs.cache-suffix }}
cache-to: "${{ inputs.should-cache && format('type=registry,ref=ghcr.io/goauthentik/dev-{0}:buildcache-{1}{2}{3},mode=max', inputs.image-name, inputs.image-arch, inputs.image-tag-suffix, inputs.cache-suffix) || '' }}"
type=registry,ref=ghcr.io/goauthentik/dev-${{ inputs.image-name }}:buildcache-${{ inputs.image-arch }}-main
type=registry,ref=ghcr.io/goauthentik/dev-${{ inputs.image-name }}:buildcache-${{ inputs.image-arch }}${{ inputs.cache-suffix }}
cache-to: "${{ inputs.should-cache && format('type=registry,ref=ghcr.io/goauthentik/dev-{0}:buildcache-{1}{2},mode=max', inputs.image-name, inputs.image-arch, inputs.cache-suffix) || '' }}"
attests: |
type=provenance,mode=max
outputs: |
type=oci,dest=build/container/${{ inputs.image-name }}${{ inputs.image-tag-suffix }}-${{ inputs.image-arch }}.oci.tar
type=oci,dest=build/container/${{ inputs.image-name }}-${{ inputs.image-arch }}.oci.tar
# params
platforms: "linux/${{ inputs.image-arch }}"
- id: upload
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
with:
name: "container-build-${{ inputs.image-name }}${{ inputs.image-tag-suffix }}-${{ inputs.image-arch }}"
name: "container-build-${{ inputs.image-name }}-${{ inputs.image-arch }}"
path: build/
if-no-files-found: error
retention-days: 2
@@ -12,14 +12,6 @@ on:
description: "Name of the image to build"
type: string
required: true
image-target:
description: "Dockerfile stage to build. Empty builds the last stage."
type: string
default: ""
image-tag-suffix:
description: "Suffix for the tags and the artifacts of an image variant that is built from another stage"
type: string
default: ""
image-dockerfile:
description: "Path to the Dockerfile to build from"
type: string
@@ -47,8 +39,6 @@ jobs:
image-name: "${{ inputs.image-name }}"
image-arch: amd64
image-dockerfile: "${{ inputs.image-dockerfile }}"
image-target: "${{ inputs.image-target }}"
image-tag-suffix: "${{ inputs.image-tag-suffix }}"
image-build-args: "${{ inputs.image-build-args }}"
should-cache: "${{ inputs.should-cache }}"
cache-suffix: "${{ inputs.cache-suffix }}"
@@ -62,8 +52,6 @@ jobs:
image-name: "${{ inputs.image-name }}"
image-arch: arm64
image-dockerfile: "${{ inputs.image-dockerfile }}"
image-target: "${{ inputs.image-target }}"
image-tag-suffix: "${{ inputs.image-tag-suffix }}"
image-build-args: "${{ inputs.image-build-args }}"
should-cache: "${{ inputs.should-cache }}"
cache-suffix: "${{ inputs.cache-suffix }}"
@@ -85,7 +73,7 @@ jobs:
run: |
set -euo pipefail
image_name="${{ inputs.image-name }}${{ inputs.image-tag-suffix }}"
image_name="${{ inputs.image-name }}"
target="ocidir://${image_name}:build"
regctl image import \
@@ -243,7 +231,7 @@ jobs:
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
with:
name: "container-build-${{ inputs.image-name }}${{ inputs.image-tag-suffix }}"
name: "container-build-${{ inputs.image-name }}"
path: build/
if-no-files-found: error
retention-days: 2
+3 -3
View File
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
+1 -1
View File
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
+3 -3
View File
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
name: Setup Node.js
with:
node-version-file: package.json
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
+5 -7
View File
@@ -22,14 +22,12 @@ jobs:
- version-2026-5
- version-2026-8
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- run: |
set -euo pipefail
current="$(pwd)"
dir="/tmp/authentik/${{ matrix.version }}"
wget "https://${{ matrix.version }}.goauthentik.io/compose.yml" -O /tmp/compose.yml
# Test the release that the compose file runs, with that release's own script
tag="$(grep -m1 -o 'AUTHENTIK_TAG:-[^}]*' /tmp/compose.yml)"
tag="${tag#AUTHENTIK_TAG:-}"
git clone --depth 1 --branch "version/${tag}" https://github.com/goauthentik/authentik.git "${dir}"
cp /tmp/compose.yml "${dir}/lifecycle/container/compose.yml"
mkdir -p "${dir}/lifecycle/container"
cd "${dir}"
./scripts/test_docker.sh
wget "https://${{ matrix.version }}.goauthentik.io/compose.yml" -O "${dir}/lifecycle/container/compose.yml"
"${current}/scripts/test_docker.sh"
+12 -57
View File
@@ -53,10 +53,6 @@ jobs:
include:
- name: server
dockerfile: Dockerfile
- name: server
dockerfile: Dockerfile
target: distroless
tag-suffix: -distroless
- name: proxy
dockerfile: proxy.Dockerfile
- name: ldap
@@ -71,8 +67,6 @@ jobs:
ref: "${{ github.ref }}"
image-name: "${{ matrix.name }}"
image-dockerfile: "lifecycle/container/${{ matrix.dockerfile }}"
image-target: "${{ matrix.target || '' }}"
image-tag-suffix: "${{ matrix.tag-suffix || '' }}"
image-build-args: |
GIT_BUILD_HASH=${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
should-cache: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
@@ -351,7 +345,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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -382,39 +376,6 @@ jobs:
if: ${{ always() }}
with:
flags: e2e
test-container:
name: test-container - server${{ matrix.tag-suffix }}${{ matrix.fips && ' (FIPS)' || '' }} - Run ${{ matrix.run_id }}/10
runs-on: ubuntu-26.04
timeout-minutes: 30
needs:
- build
- test-make-seed
strategy:
fail-fast: false
matrix:
tag-suffix: ["", "-distroless"]
run_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
include:
- tag-suffix: "-distroless"
fips: true
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
with:
name: container-build-server${{ matrix.tag-suffix }}-amd64
- name: Load container image
run: |
skopeo copy "oci-archive:container/server${{ matrix.tag-suffix }}-amd64.oci.tar" "docker-daemon:authentik.invalid/goauthentik/server:ci${{ matrix.tag-suffix }}"
rm -rf container/
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Run tests in the server image
env:
AUTHENTIK_IMAGE: authentik.invalid/goauthentik/server
AUTHENTIK_TAG: ci${{ matrix.tag-suffix }}
CI_TEST_SEED: ${{ needs.test-make-seed.outputs.seed }}
CI_RUN_ID: ${{ matrix.run_id }}
CI_TOTAL_RUNS: "10"
AUTHENTIK_COMPLIANCE__FIPS__ENABLED: ${{ matrix.fips }}
run: ./scripts/test_docker.sh
test-openid-conformance:
name: test-openid-conformance (${{ matrix.job.name }})
runs-on: ubuntu-26.04
@@ -643,7 +604,6 @@ jobs:
- test-unittest
- test-integration
- test-e2e
- test-container
- test-rust
runs-on: ubuntu-26.04
steps:
@@ -655,7 +615,6 @@ jobs:
needs:
- build-compute-tags
- build
- ci-core-mark
permissions:
# Needed to upload container images to ghcr.io
packages: write
@@ -669,14 +628,12 @@ jobs:
strategy:
fail-fast: false
matrix:
include:
- name: server
- name: server
tag-suffix: -distroless
- name: proxy
- name: ldap
- name: radius
- name: rac
name:
- server
- proxy
- ldap
- radius
- rac
steps:
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
# logs in to ghcr.io by default
@@ -689,15 +646,15 @@ jobs:
password: "${{ secrets.GITHUB_TOKEN }}"
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
with:
name: "container-build-${{ matrix.name }}${{ matrix.tag-suffix }}"
name: "container-build-${{ matrix.name }}"
- id: publish
name: publish
run: |
regctl image import "ocidir://${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}" "container/${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ocidir://${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}" "container/${{ matrix.name }}.oci.tar"
echo "digest=$(regctl image digest "ocidir://${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}")" >> "$GITHUB_OUTPUT"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}${{ matrix.tag-suffix }}" "container/${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-branch }}${{ matrix.tag-suffix }}" "container/${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-flux }}${{ matrix.tag-suffix }}" "container/${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}" "container/${{ matrix.name }}.oci.tar"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-branch }}" "container/${{ matrix.name }}.oci.tar"
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-flux }}" "container/${{ matrix.name }}.oci.tar"
- uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6
with:
subject-name: "ghcr.io/goauthentik/dev-${{ matrix.name }}"
@@ -730,7 +687,6 @@ jobs:
```shell
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
AUTHENTIK_TAG=${{ needs.build-compute-tags.outputs.tag-full }}
# Distroless image: AUTHENTIK_TAG=${{ needs.build-compute-tags.outputs.tag-full }}-distroless
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
```
@@ -749,7 +705,6 @@ jobs:
image:
repository: ghcr.io/goauthentik/dev-server
tag: ${{ needs.build-compute-tags.outputs.tag-full }}
# Distroless image: tag: ${{ needs.build-compute-tags.outputs.tag-full }}-distroless
```
Afterwards, run the upgrade commands from the latest release notes.
+3 -3
View File
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
@@ -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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
cache: pnpm
+1 -1
View File
@@ -45,7 +45,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 # v7.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
+5 -13
View File
@@ -21,25 +21,17 @@ jobs:
strategy:
fail-fast: false
matrix:
language:
- lang: "go"
deps: "system,go,runtime"
- lang: "javascript"
deps: "system,node,runtime"
- lang: "python"
deps: "system,python,rust,runtime"
language: ["go", "javascript", "python"]
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
- name: Setup authentik env
uses: ./.github/actions/setup
with:
dependencies: ${{ matrix.language.deps }}
- name: Initialize CodeQL
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
with:
languages: ${{ matrix.language.lang }}
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/autobuild@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
+14 -16
View File
@@ -41,14 +41,12 @@ jobs:
strategy:
fail-fast: false
matrix:
include:
- name: server
- name: server
tag-suffix: -distroless
- name: proxy
- name: ldap
- name: radius
- name: rac
name:
- server
- proxy
- ldap
- radius
- rac
needs:
- metadata
env:
@@ -65,18 +63,18 @@ jobs:
password: "${{ secrets.DOCKER_CORP_PASSWORD }}"
- name: Download release container artifact
run: |
gh release download "${{ needs.metadata.outputs.tag-name }}" --pattern "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
gh attestation verify "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar" --owner goauthentik
gh release download "${{ needs.metadata.outputs.tag-name }}" --pattern "${{ matrix.name }}.oci.tar"
gh attestation verify "${{ matrix.name }}.oci.tar" --owner goauthentik
- id: publish
name: Publish container
run: |
regctl image import "ocidir://${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ocidir://${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
echo "digest=$(regctl image digest "ocidir://${{ matrix.name }}:${{ needs.metadata.outputs.version }}")" >> "$GITHUB_OUTPUT"
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}${{ matrix.tag-suffix }}" "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}${{ matrix.tag-suffix }}" "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
if [ "${{ needs.metadata.outputs.release-reason }}" != "prerelease" ]; then
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}${{ matrix.tag-suffix }}" "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}${{ matrix.tag-suffix }}" "${{ matrix.name }}${{ matrix.tag-suffix }}.oci.tar"
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}" "${{ matrix.name }}.oci.tar"
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}" "${{ matrix.name }}.oci.tar"
fi
# we need to re-login for the attestation to go through
- uses: docker/login-action@v4
@@ -167,7 +165,7 @@ jobs:
container=$(docker container create "$image")
docker cp ${container}:web/ .
- name: Create a Sentry.io release
uses: getsentry/action-release@e6703d0b00208e0b3687ba660d18ab5af7892821 # v3
uses: getsentry/action-release@6fb9aeade7061441cf3864e34fbe11a1457ad7dc # v3
continue-on-error: true
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
+7 -19
View File
@@ -48,11 +48,11 @@ jobs:
- id: changelog-url
run: |
if [ "${{ inputs.release_reason }}" = "feature" ]; then
changelog_url="https://docs.goauthentik.io/releases/${{ steps.check.outputs.version-family }}"
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}"
elif [ "${{ inputs.release_reason }}" = "prerelease" ]; then
changelog_url="https://next.goauthentik.io/releases/${{ steps.check.outputs.version-family }}"
changelog_url="https://next.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}"
else
changelog_url="https://docs.goauthentik.io/releases/${{ steps.check.outputs.version-family }}#fixed-in-$(echo -n "${{ steps.check.outputs.version }}" | sed 's/\.//g')"
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}#fixed-in-$(echo -n "${{ steps.check.outputs.version }}" | sed 's/\.//g')"
fi
echo "changelog-url=${changelog_url}" >> "$GITHUB_OUTPUT"
outputs:
@@ -118,10 +118,6 @@ jobs:
include:
- name: server
dockerfile: Dockerfile
- name: server
dockerfile: Dockerfile
target: distroless
tag-suffix: -distroless
- name: proxy
dockerfile: proxy.Dockerfile
- name: ldap
@@ -136,8 +132,6 @@ jobs:
ref: "${{ needs.bump-version.outputs.release-commit }}"
image-name: "${{ matrix.name }}"
image-dockerfile: "lifecycle/container/${{ matrix.dockerfile }}"
image-target: "${{ matrix.target || '' }}"
image-tag-suffix: "${{ matrix.tag-suffix || '' }}"
image-build-args: |
VERSION=${{ needs.check-inputs.outputs.version }}
build-go-binaries:
@@ -228,24 +222,20 @@ jobs:
retention-days: 2
include-hidden-files: true
test:
name: Pre-release test (server${{ matrix.tag-suffix }})
name: Pre-release test
runs-on: ubuntu-26.04
needs:
- check-inputs
- bump-version
- build-container
strategy:
fail-fast: false
matrix:
tag-suffix: ["", "-distroless"]
steps:
- name: Fetch container images
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
with:
name: container-build-server${{ matrix.tag-suffix }}-amd64
name: container-build-server-amd64
- name: Load container images
run: |
skopeo copy "oci-archive:container/server${{ matrix.tag-suffix }}-amd64.oci.tar" "docker-daemon:authentik.invalid/goauthentik/server:${{ needs.check-inputs.outputs.version }}${{ matrix.tag-suffix }}"
skopeo copy "oci-archive:container/server-amd64.oci.tar" "docker-daemon:authentik.invalid/goauthentik/server:${{ needs.check-inputs.outputs.version }}"
rm -rf container/
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
with:
@@ -254,7 +244,7 @@ jobs:
env:
COMPOSE_PROJECT_NAME: authentik-release-test
AUTHENTIK_IMAGE: authentik.invalid/goauthentik/server
AUTHENTIK_TAG: "${{ needs.check-inputs.outputs.version }}${{ matrix.tag-suffix }}"
AUTHENTIK_TAG: "${{ needs.check-inputs.outputs.version }}"
run: ./scripts/test_docker.sh
create-release:
name: Create release
@@ -311,7 +301,6 @@ jobs:
subject-path: |
metadata.json
container/server.oci.tar
container/server-distroless.oci.tar
container/proxy.oci.tar
container/ldap.oci.tar
container/radius.oci.tar
@@ -331,7 +320,6 @@ jobs:
files: |
metadata.json
container/server.oci.tar
container/server-distroless.oci.tar
container/proxy.oci.tar
container/ldap.oci.tar
container/radius.oci.tar
+1 -1
View File
@@ -1 +1 @@
24.22.1
24.20
+1 -1
View File
@@ -18,7 +18,7 @@ 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, gunicorn config, the `ak` CLI, container + AWS entrypoints
lifecycle/ # Boot/runtime: migrations, the prefork Python server, the `ak` CLI, container + AWS entrypoints
cmd/ # Go entrypoints: ldap/ rac/ radius/ outposts
internal/ # Shared Go: outpost implementations, config
src/ # Rust server/worker (ak-axum based; gated behind cargo features)
Generated
+223 -85
View File
@@ -28,15 +28,15 @@ dependencies = [
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
dependencies = [
"alloc-no-stdlib",
]
@@ -56,6 +56,56 @@ dependencies = [
"libc",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
]
[[package]]
name = "anyhow"
version = "1.0.102"
@@ -64,9 +114,9 @@ checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "arc-swap"
version = "1.9.3"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e"
checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"
dependencies = [
"rustversion",
]
@@ -402,9 +452,9 @@ dependencies = [
[[package]]
name = "aws-lc-rs"
version = "1.19.0"
version = "1.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53"
checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13"
dependencies = [
"aws-lc-fips-sys",
"aws-lc-sys",
@@ -414,9 +464,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.47.0"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52"
checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc"
dependencies = [
"cc",
"cmake",
@@ -649,9 +699,9 @@ dependencies = [
[[package]]
name = "brotli"
version = "9.1.0"
version = "8.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6737ce8b81460bf9407909f73ff50bf13f7cb8577e1e76715f57ed0eba58ba44"
checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -660,9 +710,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "6.2.0"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34c6783f42c21c952ad7112b354f0ba2f10760e9decea5b1b60523d6e270faaf"
checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -770,6 +820,46 @@ dependencies = [
"libloading",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "cmake"
version = "0.1.57"
@@ -812,6 +902,21 @@ dependencies = [
"tracing-error",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "colored"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "combine"
version = "4.6.7"
@@ -824,9 +929,9 @@ dependencies = [
[[package]]
name = "compression-codecs"
version = "0.4.46"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cae36683101b2899f48bd31f8db9839437356188e3b1ff23096e73dab09ba8fe"
checksum = "eb7b51a7d9c967fc26773061ba86150f19c50c0d65c887cb1fbe295fd16619b7"
dependencies = [
"brotli",
"compression-core",
@@ -838,9 +943,9 @@ dependencies = [
[[package]]
name = "compression-core"
version = "0.4.34"
version = "0.4.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a"
checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d"
[[package]]
name = "concurrent-queue"
@@ -1049,9 +1154,9 @@ dependencies = [
[[package]]
name = "ctutils"
version = "0.4.5"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
dependencies = [
"cmov",
]
@@ -1167,6 +1272,17 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "docsmg"
version = "0.0.0"
dependencies = [
"clap",
"colored",
"dotenvy",
"eyre",
"regex",
]
[[package]]
name = "dotenvy"
version = "0.15.7"
@@ -1363,6 +1479,15 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsevent-sys"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
dependencies = [
"libc",
]
[[package]]
name = "futures"
version = "0.3.34"
@@ -2010,6 +2135,12 @@ dependencies = [
"serde",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.13.0"
@@ -2444,21 +2575,20 @@ dependencies = [
[[package]]
name = "notify"
version = "8.2.1"
version = "8.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674"
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
dependencies = [
"bitflags 2.11.0",
"fsevent-sys",
"inotify",
"kqueue",
"libc",
"log",
"mio",
"notify-types",
"objc2-core-foundation",
"objc2-core-services",
"walkdir",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -2596,16 +2726,6 @@ dependencies = [
"objc2-foundation",
]
[[package]]
name = "objc2-core-services"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
dependencies = [
"libc",
"objc2-core-foundation",
]
[[package]]
name = "objc2-core-text"
version = "0.3.2"
@@ -2715,6 +2835,12 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "openssl-probe"
version = "0.2.1"
@@ -2928,9 +3054,9 @@ dependencies = [
[[package]]
name = "pyo3"
version = "0.30.1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
checksum = "fc153f5fd745cc038b5eed86622125969f8a39834a57bc96beaaf2512b1da729"
dependencies = [
"libc",
"once_cell",
@@ -2942,18 +3068,18 @@ dependencies = [
[[package]]
name = "pyo3-build-config"
version = "0.30.1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
checksum = "bb77d9aa6d647507b55c69ee714d266d84c526c78ff0bc6dd8757f58591e64d1"
dependencies = [
"target-lexicon",
]
[[package]]
name = "pyo3-ffi"
version = "0.30.1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
checksum = "3160087aa5733bce7d9a729f8c55f85a2a53b74742a09613178eeebff0722253"
dependencies = [
"libc",
"pyo3-build-config",
@@ -2961,26 +3087,26 @@ dependencies = [
[[package]]
name = "pyo3-macros"
version = "0.30.1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
checksum = "91f9d455db760a9a0b0ddeaac25f1390b8a36ba73dfbda9f127cac6fc340d4d5"
dependencies = [
"proc-macro2",
"pyo3-macros-backend",
"quote",
"syn 3.0.3",
"syn 2.0.117",
]
[[package]]
name = "pyo3-macros-backend"
version = "0.30.1"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
checksum = "e343bcec300ff262f5806a33a4e51b6d097a8a46435f512fcb83e95592581625"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 3.0.3",
"syn 2.0.117",
]
[[package]]
@@ -3424,9 +3550,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.16"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"aws-lc-rs",
"ring",
@@ -3507,9 +3633,9 @@ checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "sentry"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c2c887f17023c9462a4202176efc33ca7228f9c30c0141c765ab534ab2d36b"
checksum = "9fa951f4e644464ebfd2347a7ab03b0828c512d2448a76262cad2607b343dff4"
dependencies = [
"cfg_aliases",
"httpdate",
@@ -3528,9 +3654,9 @@ dependencies = [
[[package]]
name = "sentry-backtrace"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c391d4330f3b37fdddf2b928151244e8c2dc0cfea1740e455cc8942af436f919"
checksum = "f4f27cf048aa63ccd5bc94c29989133eabb82e9c6bf7441b58e9d4a95837a105"
dependencies = [
"backtrace",
"regex",
@@ -3539,9 +3665,9 @@ dependencies = [
[[package]]
name = "sentry-contexts"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "654dacb94135c713e1dcbff01314a83d333f0e62f76b91fed5ab87415075530c"
checksum = "c5ed680585dbdacdf9859c2b4dc53358ff02bd256766882e22e343836db36b22"
dependencies = [
"hostname",
"libc",
@@ -3553,9 +3679,9 @@ dependencies = [
[[package]]
name = "sentry-core"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edcb294ca821e5c5624edaf33535eb18b06ef4f8675201d3e4d81ce325741692"
checksum = "c3ed398494bb8fc412a11a182c1883a10ae147587b8f6314abd222d1d626f31b"
dependencies = [
"rand 0.10.3",
"sentry-types",
@@ -3566,9 +3692,9 @@ dependencies = [
[[package]]
name = "sentry-debug-images"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74835055f6a57b78c0e13f941b460e39edc1899b05fe31dd47cd02367f70888f"
checksum = "55854bb40681e84ffd2a69578ad4ef9bfaf5bf2bf1380a745578b591fa24af22"
dependencies = [
"findshlibs",
"sentry-core",
@@ -3576,9 +3702,9 @@ dependencies = [
[[package]]
name = "sentry-panic"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5d28522f81ed90510ec43ed01cb1873a393b329dc719f93335b4c75fbef05d1"
checksum = "b7153e68642b761ed3aa62c022795c11b2facc728b2db7484084492373c944f9"
dependencies = [
"sentry-backtrace",
"sentry-core",
@@ -3586,9 +3712,9 @@ dependencies = [
[[package]]
name = "sentry-tower"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "057730796d82b72f35f57e66fc41c2b9e334eb3edf5030dd18d3b1f88d062c78"
checksum = "624ee2c60caf72fa2cd6be00334b3a3ce0c6df3b1f01941ea62e3d244492d334"
dependencies = [
"sentry-core",
"tower-layer",
@@ -3597,9 +3723,9 @@ dependencies = [
[[package]]
name = "sentry-tracing"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec67c296aadc41d4d41b64738908c51cacddf99edebe7a2b476f9bf40de93ff5"
checksum = "e7e7db1aefdf623f4e48e21ec9e4af535024187aeafb2a4cc7e29d035def5a13"
dependencies = [
"bitflags 2.11.0",
"sentry-backtrace",
@@ -3610,9 +3736,9 @@ dependencies = [
[[package]]
name = "sentry-types"
version = "0.49.5"
version = "0.49.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83d84a36b6bdeeb7813976fb899fca45d94540d2e2b80eac91ba66b4c654d8f0"
checksum = "1c18bf7b159bdfc7c8f97816f476b4947a1937fb6bea9d38d3479e58631614ac"
dependencies = [
"debugid",
"hex",
@@ -3903,7 +4029,7 @@ dependencies = [
"tracing",
"url",
"uuid",
"webpki-roots 1.0.10",
"webpki-roots 1.0.6",
]
[[package]]
@@ -4054,6 +4180,12 @@ dependencies = [
"unicode-properties",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
@@ -4256,9 +4388,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.54.1"
version = "1.53.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
dependencies = [
"bytes",
"libc",
@@ -4681,7 +4813,7 @@ dependencies = [
"rustls-pki-types",
"ureq-proto",
"utf8-zero",
"webpki-roots 1.0.10",
"webpki-roots 1.0.6",
]
[[package]]
@@ -4722,10 +4854,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "uuid"
version = "1.29.0"
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"getrandom 0.4.2",
"js-sys",
@@ -4922,9 +5060,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.10"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca"
dependencies = [
"rustls-pki-types",
]
@@ -4935,14 +5073,14 @@ version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.10",
"webpki-roots 1.0.6",
]
[[package]]
name = "webpki-roots"
version = "1.0.10"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
dependencies = [
"rustls-pki-types",
]
@@ -5543,27 +5681,27 @@ checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
[[package]]
name = "zstd"
version = "0.14.3"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70"
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "8.2.0"
version = "7.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b"
checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.1.2+zstd.1.5.7"
version = "2.0.16+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
dependencies = [
"cc",
"pkg-config",
+12 -8
View File
@@ -3,6 +3,7 @@ members = [
"packages/ak-axum",
"packages/ak-common",
"packages/client-rust",
"website/scripts/docsmg",
]
resolver = "3"
@@ -18,19 +19,21 @@ license-file = "LICENSE"
publish = false
[workspace.dependencies]
arc-swap = "= 1.9.3"
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.19.0", features = ["fips"] }
aws-lc-rs = { version = "= 1.18.2", 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"] }
chrono = { version = "0.4.45", features = ["serde"] }
color-eyre = "= 0.6.5"
colored = "= 3.1.1"
config-rs = { package = "config", version = "= 0.15.22", default-features = false, features = [
"json",
"yaml",
@@ -68,15 +71,16 @@ moka = { version = "= 0.12.16", default-features = false, features = [
nix = { version = "= 0.31.3", features = [
"fs",
"hostname",
"process",
"signal",
"user",
] }
notify = "= 8.2.1"
notify = "= 8.2.0"
pem = "= 4.0.0"
percent-encoding = "= 2.3.2"
pin-project-lite = "= 0.2.17"
pyo3 = "= 0.30.1"
pyo3-build-config = "= 0.30.1"
pyo3 = "= 0.29.1"
pyo3-build-config = "= 0.29.1"
rand = "= 0.10.3"
rcgen = { version = "= 0.14.10", default-features = false, features = [
"aws_lc_rs",
@@ -99,7 +103,7 @@ reqwest-middleware = { version = "= 0.5.2", features = [
"rustls",
] }
rustls = { version = "= 0.23.46", features = ["fips"] }
sentry = { version = "= 0.49.5", default-features = false, features = [
sentry = { version = "= 0.49.3", default-features = false, features = [
"backtrace",
"contexts",
"debug-images",
@@ -129,7 +133,7 @@ sqlx = { version = "= 0.9.0", default-features = false, features = [
tempfile = "= 3.27.0"
thiserror = "= 2.0.21"
time = { version = "= 0.3.55", features = ["macros"] }
tokio = { version = "= 1.54.1", features = ["full", "tracing"] }
tokio = { version = "= 1.53.3", features = ["full", "tracing"] }
tokio-retry2 = "= 0.9.1"
tokio-rustls = "= 0.26.6"
tokio-tungstenite = { version = "= 0.30.0", features = [
@@ -153,7 +157,7 @@ tracing-subscriber = { version = "= 0.3.23", features = [
"tracing-log",
] }
url = "= 2.5.8"
uuid = { version = "= 1.29.0", features = ["serde", "v4"] }
uuid = { version = "= 1.28.0", 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" }
+2 -3
View File
@@ -12,7 +12,7 @@ from rest_framework.permissions import SAFE_METHODS
from authentik.admin.flags import Flag
from authentik.admin.models import SystemSettings
from authentik.admin.utils import normalize_base_url
from authentik.admin.utils import get_system_settings, normalize_base_url
from authentik.core.api.utils import JSONDictField, ModelSerializer
from authentik.rbac.permissions import HasPermission
@@ -122,7 +122,6 @@ class SettingsView(RetrieveUpdateAPIView):
]
def get_object(self):
# Fresh instance; the serializer mutates it on update
obj = SystemSettings.objects.get(pk=True)
obj = get_system_settings()
self.check_object_permissions(self.request, obj)
return obj
-34
View File
@@ -8,7 +8,6 @@ from typing import TypedDict
from cryptography.hazmat.backends.openssl.backend import backend
from django.conf import settings
from django.db import Error, connection
from django.utils.timezone import now
from django.views.debug import SafeExceptionReporterFilter
from drf_spectacular.utils import extend_schema
@@ -49,17 +48,6 @@ class RuntimeDict(TypedDict):
authentik_version: str
class PostgreSQLDict(TypedDict):
"""PostgreSQL information"""
version: str
jit: str
jit_source: str
ssl: bool
ssl_version: str | None
ssl_cipher: str | None
class SystemInfoSerializer(PassiveSerializer):
"""Get system information."""
@@ -72,7 +60,6 @@ class SystemInfoSerializer(PassiveSerializer):
embedded_outpost_disabled = SerializerMethodField()
embedded_outpost_host = SerializerMethodField()
base_url = SerializerMethodField()
postgresql = SerializerMethodField(allow_null=True)
def get_http_headers(self, request: Request) -> dict[str, str]:
"""Get HTTP Request headers"""
@@ -133,27 +120,6 @@ class SystemInfoSerializer(PassiveSerializer):
"""Configured external base URL. Can be empty"""
return get_system_settings().base_url
def get_postgresql(self, request: Request) -> PostgreSQLDict:
"""PostgreSQL information for this request's database connection"""
try:
with connection.cursor() as cursor:
cursor.execute(
"SELECT current_setting('server_version'), setting, source, ssl, "
"version, cipher FROM pg_settings, pg_stat_ssl WHERE name = 'jit' "
"AND pid = pg_backend_pid()"
)
version, jit, jit_source, ssl, ssl_version, ssl_cipher = cursor.fetchone()
except Error:
return None
return {
"version": version,
"jit": jit,
"jit_source": jit_source,
"ssl": ssl,
"ssl_version": ssl_version,
"ssl_cipher": ssl_cipher,
}
class SystemView(APIView):
"""Get system information."""
+3 -2
View File
@@ -106,8 +106,9 @@ class FileView(APIView):
raise ValidationError(
{
"file": [
_("File size ({size}B) exceeds maximum allowed size ({max_size}B).").format(
size=file.size, max_size=MAX_FILE_SIZE_BYTES
_(
f"File size ({file.size}B) exceeds maximum allowed "
f"size ({MAX_FILE_SIZE_BYTES}B)."
)
]
}
+4 -11
View File
@@ -1,9 +1,12 @@
from collections.abc import Generator, Iterator
from contextlib import contextmanager
from tempfile import SpooledTemporaryFile
from typing import TYPE_CHECKING, Any, TypeVar
from typing import Any, TypeVar
from urllib.parse import urlsplit, urlunsplit
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from django.db import connection
from django.http.request import HttpRequest
@@ -12,9 +15,6 @@ from authentik.admin.files.usage import FileUsage
from authentik.lib.config import CONFIG
from authentik.lib.utils.time import timedelta_from_string
if TYPE_CHECKING:
import boto3
_ConfigValue = TypeVar("_ConfigValue")
@@ -74,9 +74,6 @@ class S3Backend(ManageableBackend):
@property
def session(self) -> boto3.Session:
"""Create boto3 session with configured credentials."""
# boto3 is heavy, only import it when S3 is used
import boto3
session_profile, session_profile_r = self._get_config("session_profile", None)
if session_profile is not None:
if session_profile_r or self._session is None:
@@ -103,8 +100,6 @@ class S3Backend(ManageableBackend):
@property
def client(self):
"""Create S3 client with configured endpoint and region."""
from botocore.config import Config
endpoint_url, endpoint_url_r = self._get_config("endpoint", None)
session = self.session
use_ssl, use_ssl_r = self._get_bool_config("use_ssl", True)
@@ -279,8 +274,6 @@ class S3Backend(ManageableBackend):
def file_exists(self, name: str) -> bool:
"""Check if a file exists in S3."""
from botocore.exceptions import ClientError
try:
self.client.head_object(
Bucket=self.bucket_name,
+6 -35
View File
@@ -1,10 +1,9 @@
from collections.abc import Generator
from pathlib import Path, PurePosixPath
from pathlib import Path
from django.conf import settings
from django.http.request import HttpRequest
from authentik.admin.files.backends.base import THEME_VARIABLE, Backend, get_valid_themes
from authentik.admin.files.backends.base import Backend
from authentik.admin.files.usage import FileUsage
from authentik.lib.config import CONFIG
@@ -13,15 +12,6 @@ STATIC_ASSETS_DIRS = [Path(p) for p in ("assets/icons", "assets/images")]
STATIC_ASSETS_SOURCES_DIR = Path("web/authentik/sources")
STATIC_FILE_EXTENSIONS = [".svg", ".png", ".jpg", ".jpeg"]
STATIC_PATH_PREFIX = "/static"
STATIC_SOURCES_PREFIX = f"{STATIC_PATH_PREFIX}/authentik/sources/"
def static_url_name(url: str | None) -> str | None:
"""Name of the static file behind a URL from Django's ``static()``, as this backend
names it. Models use ``static()`` for their default icons."""
if not url or not url.startswith(settings.STATIC_URL):
return None
return f"{STATIC_PATH_PREFIX}/{url.removeprefix(settings.STATIC_URL)}"
class StaticBackend(Backend):
@@ -40,15 +30,11 @@ class StaticBackend(Backend):
def list_files(self) -> Generator[str]:
"""List all static files."""
# List built-in source icons, one folder per icon with a variant per theme
# List built-in source icons
if STATIC_ASSETS_SOURCES_DIR.exists():
for icon_dir in STATIC_ASSETS_SOURCES_DIR.iterdir():
if not icon_dir.is_dir():
continue
for light in icon_dir.glob("light.*"):
if light.suffix in STATIC_FILE_EXTENSIONS:
icon = f"{icon_dir.name}/{THEME_VARIABLE}{light.suffix}"
yield f"{STATIC_SOURCES_PREFIX}{icon}"
for file_path in STATIC_ASSETS_SOURCES_DIR.iterdir():
if file_path.is_file() and (file_path.suffix in STATIC_FILE_EXTENSIONS):
yield f"{STATIC_PATH_PREFIX}/authentik/sources/{file_path.name}"
# List other static assets
for dir in STATIC_ASSETS_DIRS:
@@ -70,18 +56,3 @@ class StaticBackend(Backend):
if request is None:
return url
return request.build_absolute_uri(url)
def themed_urls(
self,
name: str,
request: HttpRequest | None = None,
use_cache: bool = True,
) -> dict[str, str] | None:
"""Theme variants of ``%(theme)s`` files, and of a single variant of a built-in
source icon, such as ``github/light.svg``, which models use as default icons."""
path = PurePosixPath(name)
if path.parent.parent == PurePosixPath(STATIC_SOURCES_PREFIX) and (
path.stem in get_valid_themes()
):
name = str(path.with_stem(THEME_VARIABLE))
return super().themed_urls(name, request, use_cache=use_cache)
@@ -19,7 +19,7 @@ class TestS3BackendClientCache(TestCase):
@CONFIG.patch("storage.s3.use_ssl", "true")
def test_client_reuses_boto_client(self):
"""Test repeated client access reuses the same boto client."""
with patch("boto3.Session") as session_cls:
with patch("authentik.admin.files.backends.s3.boto3.Session") as session_cls:
session = session_cls.return_value
client = Mock()
session.client.return_value = client
@@ -36,7 +36,7 @@ class TestS3BackendClientCache(TestCase):
def test_client_refreshes_when_config_changes(self):
"""Test client cache is invalidated when S3 client config changes."""
with CONFIG.patch("storage.s3.endpoint", "https://s3-1.example.com"):
with patch("boto3.Session") as session_cls:
with patch("authentik.admin.files.backends.s3.boto3.Session") as session_cls:
session = session_cls.return_value
first_client = Mock()
second_client = Mock()
@@ -34,42 +34,9 @@ class TestStaticBackend(TestCase):
self.assertFalse(self.backend.supports_file("test.jpg"))
def test_list_files(self):
"""Test list_files lists built-in source icons with a variant per theme"""
"""Test list_files includes expected files"""
files = list(self.backend.list_files())
self.assertIn("/static/authentik/sources/github/%(theme)s.svg", files)
self.assertIn("/static/authentik/sources/kerberos/%(theme)s.png", files)
self.assertNotIn("/static/authentik/sources/github/light.svg", files)
self.assertNotIn("/static/authentik/sources/github/dark.svg", files)
def test_themed_urls_source_icon(self):
"""Test themed_urls of a built-in source icon picked in the file picker"""
self.assertEqual(
self.backend.themed_urls("/static/authentik/sources/github/%(theme)s.svg"),
{
"light": "/static/authentik/sources/github/light.svg",
"dark": "/static/authentik/sources/github/dark.svg",
},
)
def test_themed_urls_source_icon_variant(self):
"""Test themed_urls of one variant of a built-in source icon, as used by defaults"""
github = {
"light": "/static/authentik/sources/github/light.svg",
"dark": "/static/authentik/sources/github/dark.svg",
}
self.assertEqual(
self.backend.themed_urls("/static/authentik/sources/github/light.svg"), github
)
self.assertEqual(
self.backend.themed_urls("/static/authentik/sources/github/dark.svg"), github
)
def test_themed_urls_other_static_files(self):
"""Test themed_urls returns None for other static files"""
self.assertIsNone(self.backend.themed_urls("/static/dist/assets/icons/icon.svg"))
self.assertIsNone(self.backend.themed_urls("/static/dist/assets/icons/light.svg"))
self.assertIsNone(self.backend.themed_urls("/static/authentik/sources/github/logo.svg"))
self.assertIsNone(
self.backend.themed_urls("/static/authentik/sources/github/../github/light.svg")
)
self.assertIn("/static/authentik/sources/ldap.png", files)
self.assertIn("/static/authentik/sources/openidconnect.svg", files)
self.assertIn("/static/authentik/sources/saml.png", files)
+3 -8
View File
@@ -5,7 +5,7 @@ from django.http.request import HttpRequest
from rest_framework.request import Request
from structlog.stdlib import get_logger
from authentik.admin.files.backends.base import ManageableBackend, substitute_theme
from authentik.admin.files.backends.base import ManageableBackend
from authentik.admin.files.backends.file import FileBackend
from authentik.admin.files.backends.passthrough import PassthroughBackend
from authentik.admin.files.backends.s3 import S3Backend
@@ -78,9 +78,6 @@ class FileManager:
Set ``use_cache=False`` when the caller needs a fresh signed URL instead
of a cached one, for example when serializing flow/login payloads that
may be refreshed after the previous JWT has expired.
A name with ``%(theme)s`` resolves to its light variant, so the URL always
points at a real file. Callers that know the theme use ``themed_urls()``.
"""
if not name:
return ""
@@ -88,7 +85,6 @@ class FileManager:
if isinstance(request, Request):
request = request._request
name = substitute_theme(name, "light")
for backend in self.backends:
if backend.supports_file(name):
return backend.file_url(name, request, use_cache=use_cache)
@@ -103,13 +99,12 @@ class FileManager:
use_cache: bool = True,
) -> dict[str, str] | None:
"""
Get URLs for each theme variant when filename contains %(theme)s, or when it is
one variant of a built-in source icon.
Get URLs for each theme variant when filename contains %(theme)s.
``use_cache`` has the same semantics as ``file_url()`` and allows
callers to force regeneration of expiring signed URLs.
Returns dict mapping theme to URL if there are theme variants, None otherwise.
Returns dict mapping theme to URL if %(theme)s present, None otherwise.
"""
if not name:
return None
+9 -15
View File
@@ -92,13 +92,10 @@ class TestFileAPI(FileTestFileBackendMixin, TestCase):
self.assertEqual(response.status_code, 200)
self.assertIn(
{
"name": "/static/authentik/sources/ldap/%(theme)s.svg",
"url": "http://testserver/static/authentik/sources/ldap/light.svg",
"mime_type": "image/svg+xml",
"themed_urls": {
"light": "http://testserver/static/authentik/sources/ldap/light.svg",
"dark": "http://testserver/static/authentik/sources/ldap/dark.svg",
},
"name": "/static/authentik/sources/ldap.png",
"url": "http://testserver/static/authentik/sources/ldap.png",
"mime_type": "image/png",
"themed_urls": None,
},
response.data,
)
@@ -123,7 +120,7 @@ class TestFileAPI(FileTestFileBackendMixin, TestCase):
reverse(
"authentik_api:files",
query={
"search": "LDAP/",
"search": "LDAP.PNG",
},
)
)
@@ -131,13 +128,10 @@ class TestFileAPI(FileTestFileBackendMixin, TestCase):
self.assertEqual(response.status_code, 200)
self.assertIn(
{
"name": "/static/authentik/sources/ldap/%(theme)s.svg",
"url": "http://testserver/static/authentik/sources/ldap/light.svg",
"mime_type": "image/svg+xml",
"themed_urls": {
"light": "http://testserver/static/authentik/sources/ldap/light.svg",
"dark": "http://testserver/static/authentik/sources/ldap/dark.svg",
},
"name": "/static/authentik/sources/ldap.png",
"url": "http://testserver/static/authentik/sources/ldap.png",
"mime_type": "image/png",
"themed_urls": None,
},
response.data,
)
@@ -54,18 +54,6 @@ class TestResolveFileUrlBasic(TestCase):
result = manager.file_url("/static/authentik/sources/icon.svg")
self.assertEqual(result, "/static/authentik/sources/icon.svg")
def test_file_url_theme_variable_uses_light(self):
"""Test file_url resolves %(theme)s to the light variant, never the placeholder"""
manager = FileManager(FileUsage.MEDIA)
self.assertEqual(
manager.file_url("/static/authentik/sources/kerberos/%(theme)s.png"),
"/static/authentik/sources/kerberos/light.png",
)
self.assertEqual(
manager.file_url("https://example.com/logo-%(theme)s.png"),
"https://example.com/logo-light.png",
)
def test_file_url_forwards_use_cache(self):
"""Test file_url forwards use_cache to backend."""
manager = FileManager(FileUsage.MEDIA)
+2 -8
View File
@@ -76,16 +76,10 @@ def validate_upload_file_name(
# Check path length limits
normalized = str(path)
if len(normalized) > MAX_FILE_NAME_LENGTH:
raise ValidationError(
_("File name too long (max {MAX_FILE_NAME_LENGTH} characters)").format(
MAX_FILE_NAME_LENGTH=MAX_FILE_NAME_LENGTH
)
)
raise ValidationError(_(f"File name too long (max {MAX_FILE_NAME_LENGTH} characters)"))
for part in path.parts:
if len(part) > MAX_PATH_COMPONENT_LENGTH:
raise ValidationError(
_("Path component too long (max {MAX_PATH_COMPONENT_LENGTH} characters)").format(
MAX_PATH_COMPONENT_LENGTH=MAX_PATH_COMPONENT_LENGTH
)
_(f"Path component too long (max {MAX_PATH_COMPONENT_LENGTH} characters)")
)
+2 -1
View File
@@ -46,7 +46,7 @@ class Flag[T]:
@classmethod
def set(cls, value: T, settings: SystemSettings | None = None) -> T | None:
from authentik.admin.models import SystemSettings
from authentik.admin.utils import get_system_settings
from authentik.admin.utils import clear_system_settings_cache, get_system_settings
if not settings:
settings = get_system_settings()
@@ -59,6 +59,7 @@ class Flag[T]:
function="jsonb_set",
)
)
clear_system_settings_cache()
def get_default(self) -> T | None:
return self.default
@@ -1,34 +0,0 @@
"""Change a user's password"""
from getpass import getpass
from django.core.management.base import BaseCommand, CommandError
from rest_framework.exceptions import ValidationError
from authentik.core.models import User
from authentik.stages.password.models import PasswordDevice
class Command(BaseCommand):
"""Change a user's password, replacing Django's command that writes to the user"""
help = "Change a user's password."
def add_arguments(self, parser):
parser.add_argument("username")
def handle(self, *args, username: str, **options):
user = User.objects.filter(username=username).first()
if not user:
raise CommandError(f"User '{username}' does not exist")
password = getpass("Password: ")
if password != getpass("Password (again): "):
raise CommandError("Passwords do not match")
if not password:
raise CommandError("Password cannot be empty")
try:
PasswordDevice.set_password(user, password)
except ValidationError as exc:
# An LDAP or Kerberos source refused the password
raise CommandError(str(exc)) from exc
self.stdout.write(f"Password changed for user '{username}'")
+18
View File
@@ -0,0 +1,18 @@
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)
-12
View File
@@ -18,23 +18,11 @@ DEFAULT_REPUTATION_LOWER_LIMIT = -5
DEFAULT_REPUTATION_UPPER_LIMIT = 5
class SystemSettingsQuerySet(models.QuerySet):
def update(self, **kwargs) -> int:
# Queryset updates skip post_save, so drop the cached settings here too
from authentik.admin.utils import get_system_settings
rows = super().update(**kwargs)
get_system_settings.cache_clear()
return rows
class SystemSettings(InternallyManagedMixin, SerializerModel):
"""Global settings for this authentik instance"""
id = models.BooleanField(primary_key=True, default=True)
objects = SystemSettingsQuerySet.as_manager()
avatars = models.TextField(
help_text=_("Configure how authentik should show avatars for users."),
default="gravatar,initials",
+2 -2
View File
@@ -3,7 +3,7 @@ from django.dispatch import receiver
from authentik.admin.models import SystemSettings
from authentik.admin.tasks import _set_prom_info
from authentik.admin.utils import get_system_settings
from authentik.admin.utils import clear_system_settings_cache
from authentik.root.signals import post_startup
@@ -14,4 +14,4 @@ def post_startup_admin_metrics(sender, **_):
@receiver(post_save, sender=SystemSettings)
def system_settings_saved(**_):
get_system_settings.cache_clear()
clear_system_settings_cache()
+2 -2
View File
@@ -106,8 +106,8 @@ def update_latest_version():
return
Event.new(
EventAction.UPDATE_AVAILABLE,
message=_("New version {version} available!").format(
version=upstream_version.version
message=_(
"New version {version} available!".format(version=upstream_version.version)
),
new_version=upstream_version.version,
changelog=upstream_version.changelog_url,
-14
View File
@@ -2,7 +2,6 @@
from json import loads
from django.db import connection
from django.test import TestCase
from django.urls import reverse
@@ -45,16 +44,3 @@ class TestAdminAPI(TestCase):
"""Test system API"""
response = self.client.get(reverse("authentik_api:admin_system"))
self.assertEqual(response.status_code, 200)
def test_system_postgresql(self):
"""Test system API reports the JIT setting and TLS status of the database connection"""
with connection.cursor() as cursor:
cursor.execute("SET jit = off")
response = self.client.get(reverse("authentik_api:admin_system"))
self.assertEqual(response.status_code, 200)
postgresql = loads(response.content)["postgresql"]
self.assertEqual(postgresql["jit"], "off")
self.assertEqual(postgresql["jit_source"], "session")
self.assertTrue(postgresql["version"])
self.assertEqual(postgresql["ssl"], connection.connection.pgconn.ssl_in_use)
self.assertEqual(postgresql["ssl_version"] is not None, postgresql["ssl"])
@@ -1,20 +1,32 @@
from django.test import TestCase
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_cached(self):
"""Settings are cached across calls"""
self.assertIs(get_system_settings(), get_system_settings())
def test_scoped_to_request(self):
"""Settings are only cached within a single request"""
seen = []
def test_cleared_on_save(self):
"""Saving the settings drops the cached instance"""
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()
settings = SystemSettings.objects.get(pk=True)
settings.avatars = "none"
settings.save()
SystemSettings.objects.filter(pk=True).update(avatars="none")
second = get_system_settings()
self.assertIsNot(first, second)
self.assertEqual(second.avatars, "none")
+28 -5
View File
@@ -1,14 +1,37 @@
"""authentik admin utils"""
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar
from authentik.admin.models import SystemSettings
from authentik.lib.config import CONFIG
from authentik.root.cache import in_memory_cache
_CTX_SYSTEM_SETTINGS = ContextVar[dict[str, SystemSettings] | None](
"authentik_system_settings", default=None
)
@in_memory_cache(key=lambda: None, timeout=CONFIG.get_int("cache.timeout_system_settings", 30))
def get_system_settings() -> SystemSettings:
"""Get the system settings. The returned object is shared, don't mutate it."""
return SystemSettings.objects.get(pk=True)
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:
+3 -44
View File
@@ -1,19 +1,15 @@
"""DjangoQL search"""
from django.db.models import QuerySet
from django.db.models.constants import LOOKUP_SEP
from djangoql.ast import Name
from djangoql.exceptions import DjangoQLError
from djangoql.parser import DjangoQLParser
from djangoql.queryset import build_filter
from djangoql.queryset import apply_search
from djangoql.schema import DjangoQLSchema
from rest_framework.filters import SearchFilter
from rest_framework.request import Request
from structlog.stdlib import get_logger
from authentik.api.search.fields import JSONSearchField
from authentik.rbac.endpoint_checks import EndpointChecks
from authentik.rbac.field_rules import FieldRules
LOGGER = get_logger()
@@ -37,35 +33,12 @@ class BaseSchema(DjangoQLSchema):
return super().resolve_name(name)
class HiddenFieldsSearchFilter(SearchFilter):
"""This is used to prevent unauthorized users from probing values of fields hidden to them."""
def __init__(self):
super().__init__()
self.hidden_whole_fields: set[str] = set()
def get_search_fields(self, view, request: Request):
fields = super().get_search_fields(view, request)
if not fields or not self.hidden_whole_fields:
return fields
return [
field for field in fields if self.searched_field(field) not in self.hidden_whole_fields
]
def searched_field(self, search_field: str) -> str:
"""The model field a `search_fields` entry starts from, without DRF's lookup prefix
(`^`, `=`, `@` or `$`) or a `__` path into related models"""
if search_field[:1] in self.lookup_prefixes:
search_field = search_field[1:]
return search_field.split(LOOKUP_SEP)[0]
class QLSearch(SearchFilter):
"""rest_framework search filter which uses DjangoQL"""
def __init__(self):
super().__init__()
self._fallback = HiddenFieldsSearchFilter()
self._fallback = SearchFilter()
def get_search_terms(self, request: Request) -> str:
"""Search terms are set by a ?search=... query parameter,
@@ -86,26 +59,12 @@ class QLSearch(SearchFilter):
return InlineSchema
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
rules = EndpointChecks.for_request(request).field_rules()
rules.refuse_hidden_parameters(request, view)
self._fallback.hidden_whole_fields = rules.hidden_whole_fields
search_query = self.get_search_terms(request)
schema = self.get_schema(request, view)
if len(search_query) == 0:
return self._fallback.filter_queryset(request, queryset, view)
try:
return self.apply_search(queryset, search_query, schema, rules)
return apply_search(queryset, search_query, schema=schema)
except DjangoQLError as exc:
LOGGER.debug("Failed to parse search expression", exc=exc)
return self._fallback.filter_queryset(request, queryset, view)
def apply_search(
self, queryset: QuerySet, search: str, schema: type[BaseSchema], rules: FieldRules
) -> QuerySet:
"""This is a rewrite of `djangoql.queryset.apply_search`"""
ast = DjangoQLParser().parse(search)
if rules.hidden:
rules.guard_search(ast)
schema_instance = schema(queryset.model)
schema_instance.validate(ast)
return queryset.filter(build_filter(ast, schema_instance))
+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 gunicorn worker)
Counters are per-process (per server worker)
"""
cache = caches["throttle"]
-4
View File
@@ -61,8 +61,6 @@ class ConfigSerializer(PassiveSerializer):
cache_timeout = IntegerField(required=True)
cache_timeout_flows = IntegerField(required=True)
cache_timeout_policies = IntegerField(required=True)
cache_timeout_brands = IntegerField(required=True)
cache_timeout_system_settings = IntegerField(required=True)
class ConfigView(APIView):
@@ -108,8 +106,6 @@ class ConfigView(APIView):
"cache_timeout": CONFIG.get_int("cache.timeout"),
"cache_timeout_flows": CONFIG.get_int("cache.timeout_flows"),
"cache_timeout_policies": CONFIG.get_int("cache.timeout_policies"),
"cache_timeout_brands": CONFIG.get_int("cache.timeout_brands"),
"cache_timeout_system_settings": CONFIG.get_int("cache.timeout_system_settings"),
}
)
+1 -2
View File
@@ -12,7 +12,6 @@ from structlog.stdlib import get_logger
from authentik.api.v3.config import ConfigView
from authentik.api.views import APIBrowserView
from authentik.lib.utils.reflection import get_apps
from authentik.lib.utils.urls import sort_hot
LOGGER = get_logger()
@@ -46,7 +45,7 @@ for _authentik_app in get_apps():
)
urlpatterns = sort_hot(
urlpatterns = (
[
path("", APIBrowserView.as_view(), name="schema-browser"),
]
+1 -1
View File
@@ -227,7 +227,7 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
try:
importer = Importer.from_string(string_contents, context)
except EntryInvalidError as exc:
raise ValidationError(_("Invalid blueprint file: {exc}").format(exc=str(exc))) from None
raise ValidationError(_("Invalid blueprint file: {exc}".format(exc=str(exc)))) from None
check_blueprint_perms(importer.blueprint, self.request.user)
return importer
@@ -1,6 +1,7 @@
"""Test and debug Blueprints"""
import atexit
import readline
from pathlib import Path
from pprint import pformat
from sys import exit as sysexit
@@ -10,12 +11,6 @@ from django.core.management.base import BaseCommand, no_translations
from structlog.stdlib import get_logger
from yaml import load
try:
import readline
except ImportError: # pragma: no cover
# There's no libreadline in the distroless image, degrade instead of failing
readline = None
from authentik.blueprints.v1.common import BlueprintLoader, EntryInvalidError
from authentik.core.management.commands.shell import get_banner_text
from authentik.lib.utils.errors import exception_to_string
@@ -30,9 +25,6 @@ class Command(BaseCommand):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
if readline is None:
self.stderr.write("readline is not available, line editing and history are disabled")
return
histfolder = Path("~").expanduser() / Path(".local/share/authentik")
histfolder.mkdir(parents=True, exist_ok=True)
histfile = histfolder / Path("blueprint_shell_history")
@@ -38,16 +38,6 @@ class TestBlueprintsV1RBAC(TransactionTestCase):
self.assertIsNotNone(role)
self.assertEqual(get_perms(role), {"authentik_blueprints.view_blueprintinstance"})
def test_role_unknown_permission(self):
"""Test that an unknown permission fails validation"""
uid = generate_id()
import_yaml = load_fixture("fixtures/rbac_role.yaml", id=uid).replace(
"authentik_blueprints.view_blueprintinstance", "authentik_blueprints.view_nothing"
)
importer = Importer.from_string(import_yaml)
self.assertFalse(importer.validate()[0])
def test_object_permission(self):
"""Test permissions"""
uid = generate_id()
+2 -54
View File
@@ -3,10 +3,8 @@
from hashlib import sha512
from pathlib import Path
from tempfile import NamedTemporaryFile, mkdtemp
from unittest.mock import patch
from django.test import TransactionTestCase
from django.utils.crypto import salted_hmac
from yaml import dump
from authentik.blueprints.models import BlueprintInstance, BlueprintInstanceStatus
@@ -127,49 +125,6 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
},
)
@CONFIG.patch("blueprints_dir", TMP)
def test_valid_updated_external_values(self):
"""Test that changing only an `!Env` or `!File` value reapplies the blueprint"""
name = generate_id()
env_key = f"AUTHENTIK_TEST_{generate_id().upper()}"
with (
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
NamedTemporaryFile(mode="w+") as value_file,
patch.dict("os.environ", {env_key: "foo"}),
):
value_file.write("foo")
value_file.flush()
content = (
"version: 1\n"
f"metadata:\n name: {name}\n"
f"context:\n env: !Env {env_key}\n file: !File {value_file.name}\n"
"entries: []\n"
)
file.write(content)
file.flush()
blueprints_discovery.send()
instance = BlueprintInstance.objects.get(name=name)
first_hash = instance.last_applied_hash
self.assertNotEqual(first_hash, sha512(content.encode()).hexdigest())
# Unchanged values don't reapply
blueprints_discovery.send()
instance.refresh_from_db()
self.assertEqual(instance.last_applied_hash, first_hash)
with patch.dict("os.environ", {env_key: "bar"}):
blueprints_discovery.send()
instance.refresh_from_db()
env_hash = instance.last_applied_hash
self.assertNotEqual(env_hash, first_hash)
value_file.seek(0)
value_file.write("bar")
value_file.flush()
blueprints_discovery.send()
instance.refresh_from_db()
self.assertNotIn(instance.last_applied_hash, [first_hash, env_hash])
@CONFIG.patch("blueprints_dir", TMP)
def test_valid_disabled(self):
"""Test valid file"""
@@ -335,13 +290,8 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
):
content = f"version: 1\nentries: []\ncontext:\n secret: {reference}\n"
expected = sha512(content.encode())
expected.update(
salted_hmac(
"goauthentik.io/blueprints/v1/external-values",
sha512(b"initial").digest() * routes,
algorithm="sha512",
).digest()
)
for _ in range(routes):
expected.update(sha512(b"initial").digest())
self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())
@CONFIG.patch("blueprints_dir", TMP)
@@ -382,8 +332,6 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
("path no syscall can take", '!File "\\0"'),
("path outside the filesystem encoding", '!File "\\ud800"'),
("env key with a null byte", '!Env "\\0"'),
("env key outside the filesystem encoding", '!Env "\\ud800"'),
("sequence containing itself", "&anchor [*anchor]"),
("mapping containing itself", "&anchor {key: *anchor}"),
("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
+1 -1
View File
@@ -69,7 +69,7 @@ class Exporter:
blueprint = Blueprint()
self._pre_export(blueprint)
blueprint.metadata = BlueprintMetadata(
name=_("authentik Export - {date}").format(date=str(now())),
name=_("authentik Export - {date}".format_map({"date": str(now())})),
labels={
LABEL_AUTHENTIK_GENERATED: "true",
},
+24 -43
View File
@@ -2,27 +2,23 @@
from collections.abc import Generator
from hashlib import sha512
from os import getenv
from pathlib import Path
from typing import Any
from django.utils.crypto import salted_hmac
from yaml import load
from yaml.error import YAMLError
from authentik.blueprints.v1.common import BlueprintLoader, Env, File, YAMLTag
from authentik.blueprints.v1.common import BlueprintLoader, File, YAMLTag
def iter_external_tags(
value: Any, ancestors: frozenset[int] = frozenset()
) -> Generator[Env | File]:
"""Find all `!Env` and `!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."""
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, Env | File):
if isinstance(value, File):
yield value
if isinstance(value, dict):
children = value.values()
@@ -33,47 +29,32 @@ def iter_external_tags(
else:
return
for child in children:
yield from iter_external_tags(child, ancestors)
yield from iter_file_tags(child, ancestors)
# One byte where a readable value contributes a 64-byte digest
MISSING_VALUE_MARKER = b"\0"
# 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 current values of its `!Env` and `!File` tags.
The values are keyed with the secret key, as the hash is visible in the API and a
plain hash of a short secret could be brute-forced."""
"""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()
values = salted_hmac("goauthentik.io/blueprints/v1/external-values", b"", algorithm="sha512")
has_values = False
for tag in iter_external_tags(raw_blueprint):
# Mapping-node tags have no key or path; nested tags cannot be resolved here
if isinstance(tag, Env):
key = getattr(tag, "key", None)
if not isinstance(key, str):
continue
try:
env = getenv(key)
except ValueError:
env = None
value = None if env is None else env.encode(errors="surrogateescape")
else:
path = getattr(tag, "path", None)
if not isinstance(path, str):
continue
try:
value = Path(path).read_bytes()
except OSError, ValueError:
value = None
has_values = True
# A missing value still takes its place in the sequence, so a value that goes
# missing while another appears cannot leave the hash unchanged
values.update(MISSING_VALUE_MARKER if value is None else sha512(value).digest())
if has_values:
hasher.update(values.digest())
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()
-21
View File
@@ -1,21 +0,0 @@
"""authentik brand signals"""
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from authentik.brands.models import Brand
from authentik.brands.utils import get_brand_for_request
from authentik.core.models import Application
from authentik.flows.models import Flow
@receiver(post_save, sender=Brand)
@receiver(post_delete, sender=Brand)
# Cached brands carry their flows and default application (see _BRAND_RELATED_FK_FIELDS)
@receiver(post_save, sender=Flow)
@receiver(post_delete, sender=Flow)
@receiver(post_save, sender=Application)
@receiver(post_delete, sender=Application)
def brand_cache_clear(**_):
"""Drop cached brand lookups when a brand or an object it caches changes"""
get_brand_for_request.cache_clear()
-5
View File
@@ -12,9 +12,7 @@ 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.config import CONFIG
from authentik.lib.tracing import active_tracer
from authentik.root.cache import in_memory_cache
_q_default = Q(default=True)
DEFAULT_BRAND = Brand(domain="fallback")
@@ -29,9 +27,6 @@ def session_safe_mode(request: HttpRequest) -> bool:
return bool(session.get(SESSION_KEY_BRAND_SAFE_MODE))
@in_memory_cache(
key=lambda request: request.get_host(), timeout=CONFIG.get_int("cache.timeout_brands", 30)
)
def get_brand_for_request(request: HttpRequest) -> Brand:
"""Get brand object for current request"""
-2
View File
@@ -16,8 +16,6 @@ GRANT_TYPE_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange" #
# https://datatracker.ietf.org/doc/html/rfc8693#section-3
TOKEN_TYPE_URI_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token" # nosec
TOKEN_TYPE_URI_JWT = "urn:ietf:params:oauth:token-type:jwt" # nosec
# Only valid as requested_token_type, with a federated SAML provider as `audience`
TOKEN_TYPE_URI_SAML2 = "urn:ietf:params:oauth:token-type:saml2" # nosec
# authentik's own built-in Token model (e.g. API tokens), not part of RFC 8693 -- only
# meaningful as an actor_token_type, never as a subject_token/requested_token_type
TOKEN_TYPE_URI_AUTHENTIK_TOKEN = "goauthentik.io/oauth/token-type/authentik_token" # nosec
-22
View File
@@ -73,25 +73,3 @@ DIGEST_ALGORITHM_TRANSLATION_MAP = {
SHA384: xmlsec.constants.TransformSha384,
SHA512: xmlsec.constants.TransformSha512,
}
AES128_CBC = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"
AES256_CBC = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"
AES128_GCM = "http://www.w3.org/2009/xmlenc11#aes128-gcm"
AES256_GCM = "http://www.w3.org/2009/xmlenc11#aes256-gcm"
RSA_OAEP_MGF1P = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"
# Algorithms advertised in SP metadata as <md:EncryptionMethod>, in order of preference
ENCRYPTION_METHODS_ADVERTISED = (
AES256_GCM,
AES128_GCM,
AES256_CBC,
AES128_CBC,
RSA_OAEP_MGF1P,
)
ENCRYPTION_ALGORITHM_TRANSLATION_MAP = {
AES128_CBC: (xmlsec.constants.TransformAes128Cbc, 128),
AES256_CBC: (xmlsec.constants.TransformAes256Cbc, 256),
AES128_GCM: (xmlsec.constants.TransformAes128Gcm, 128),
AES256_GCM: (xmlsec.constants.TransformAes256Gcm, 256),
}
@@ -2,17 +2,13 @@
from base64 import b64decode
from dataclasses import dataclass
from xml.etree.ElementTree import ParseError # nosec
from defusedxml import ElementTree
from structlog.stdlib import get_logger
from authentik.common.saml.constants import NS_SAML_ASSERTION, NS_SAML_PROTOCOL
from authentik.common.saml.exceptions import ERROR_CANNOT_DECODE_REQUEST, CannotHandleAssertion
from authentik.providers.saml.utils.encoding import decode_base64_and_inflate
LOGGER = get_logger()
@dataclass(slots=True)
class LogoutRequest:
@@ -35,15 +31,7 @@ class LogoutRequestParser:
"""LogoutRequest Parser"""
def _parse_xml(self, decoded_xml: str | bytes, relay_state: str | None = None) -> LogoutRequest:
try:
root = ElementTree.fromstring(decoded_xml)
except (ParseError, ValueError) as exc:
LOGGER.warning("Failed to parse SAML logout request", exc=exc)
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST) from exc
# `ID` is a required attribute of every SAML request (SAML 2.0 core §3.2.1)
if "ID" not in root.attrib:
LOGGER.warning("SAML logout request is missing the ID attribute")
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST)
root = ElementTree.fromstring(decoded_xml)
request = LogoutRequest(
id=root.attrib["ID"],
)
@@ -78,9 +66,8 @@ class LogoutRequestParser:
"""Validate and parse raw request with enveloped signautre."""
try:
decoded_xml = b64decode(saml_request.encode())
except ValueError as exc:
LOGGER.warning("Failed to decode SAML logout request", exc=exc)
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST) from exc
except UnicodeDecodeError:
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST) from None
return self._parse_xml(decoded_xml, relay_state)
def parse_detached(
@@ -91,8 +78,7 @@ class LogoutRequestParser:
"""Validate and parse raw request with detached signature"""
try:
decoded_xml = decode_base64_and_inflate(saml_request)
except ValueError as exc:
LOGGER.warning("Failed to decode SAML logout request", exc=exc)
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST) from exc
except UnicodeDecodeError:
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_REQUEST) from None
return self._parse_xml(decoded_xml, relay_state)
@@ -1,84 +0,0 @@
"""LogoutResponse parser"""
import binascii
from base64 import b64decode
from dataclasses import dataclass
from xml.etree.ElementTree import ParseError # nosec
from defusedxml import ElementTree
from django.utils.translation import gettext_lazy as _
from authentik.common.saml.constants import NS_SAML_ASSERTION, NS_SAML_PROTOCOL, SAML_STATUS_SUCCESS
from authentik.common.saml.exceptions import CannotHandleAssertion
from authentik.providers.saml.utils.encoding import decode_base64_and_inflate
ERROR_CANNOT_DECODE_RESPONSE = _("Cannot decode SAML response.")
@dataclass(slots=True)
class LogoutResponse:
"""Logout Response"""
id: str | None = None
in_response_to: str | None = None
issuer: str | None = None
status: str | None = None
relay_state: str | None = None
class LogoutResponseParser:
"""LogoutResponse Parser"""
def _parse_xml(
self, decoded_xml: str | bytes, relay_state: str | None = None
) -> LogoutResponse:
try:
root = ElementTree.fromstring(decoded_xml)
except (ParseError, ValueError) as exc:
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_RESPONSE) from exc
response = LogoutResponse(
id=root.attrib.get("ID"),
in_response_to=root.attrib.get("InResponseTo"),
)
# Try both namespaces for Issuer
issuers = root.findall(f"{{{NS_SAML_ASSERTION}}}Issuer")
if not issuers:
issuers = root.findall(f"{{{NS_SAML_PROTOCOL}}}Issuer")
if len(issuers) > 0:
response.issuer = issuers[0].text
# Extract Status
status_elements = root.findall(f"{{{NS_SAML_PROTOCOL}}}Status")
if len(status_elements) > 0:
status_codes = status_elements[0].findall(f"{{{NS_SAML_PROTOCOL}}}StatusCode")
if len(status_codes) > 0:
response.status = status_codes[0].attrib.get("Value")
response.relay_state = relay_state
return response
def parse(self, saml_response: str, relay_state: str | None = None) -> LogoutResponse:
"""Parse raw response with enveloped signature (POST binding)"""
try:
decoded_xml = b64decode(saml_response.encode())
except UnicodeDecodeError, binascii.Error:
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_RESPONSE) from None
return self._parse_xml(decoded_xml, relay_state)
def parse_detached(self, saml_response: str, relay_state: str | None = None) -> LogoutResponse:
"""Parse raw response with detached signature (Redirect binding)"""
try:
decoded_xml = decode_base64_and_inflate(saml_response)
except UnicodeDecodeError, binascii.Error:
raise CannotHandleAssertion(ERROR_CANNOT_DECODE_RESPONSE) from None
return self._parse_xml(decoded_xml, relay_state)
def verify_status(self, response: LogoutResponse) -> None:
"""Verify that the LogoutResponse has a successful status."""
if response.status != SAML_STATUS_SUCCESS:
raise CannotHandleAssertion(f"LogoutResponse status is not success: {response.status}")
-85
View File
@@ -1,85 +0,0 @@
"""Shared SAML signature verification"""
from base64 import b64decode
from urllib.parse import urlencode
import xmlsec
from lxml.etree import _Element # nosec
from authentik.common.saml.constants import NS_MAP, SIGN_ALGORITHM_TRANSFORM_MAP
from authentik.common.saml.exceptions import (
ERROR_FAILED_TO_VERIFY,
ERROR_SIGNATURE_REQUIRED_BUT_ABSENT,
CannotHandleAssertion,
)
from authentik.crypto.models import CertificateKeyPair
from authentik.lib.xml import UnsafeXML, lxml_from_string
def verify_enveloped_signature(
raw_xml: bytes, verification_kp: CertificateKeyPair, xpath: str
) -> None:
"""Verify an enveloped XML signature (POST binding).
`xpath` selects the signature node, for example `/samlp:LogoutRequest/ds:Signature`."""
try:
root = lxml_from_string(raw_xml)
except UnsafeXML as exc:
raise CannotHandleAssertion(str(exc)) from exc
xmlsec.tree.add_ids(root, ["ID"])
signature_nodes = root.xpath(xpath, namespaces=NS_MAP)
if not isinstance(signature_nodes, list) or len(signature_nodes) < 1:
raise CannotHandleAssertion(ERROR_SIGNATURE_REQUIRED_BUT_ABSENT)
signature_node = signature_nodes[0]
if not isinstance(signature_node, _Element):
raise CannotHandleAssertion(ERROR_SIGNATURE_REQUIRED_BUT_ABSENT)
try:
ctx = xmlsec.SignatureContext()
ctx.key = xmlsec.Key.from_memory(
verification_kp.certificate_data,
xmlsec.constants.KeyDataFormatCertPem,
None,
)
ctx.verify(signature_node)
except xmlsec.Error as exc:
raise CannotHandleAssertion(ERROR_FAILED_TO_VERIFY) from exc
def verify_detached_signature( # noqa: PLR0913
saml_param_name: str,
saml_value: str,
relay_state: str | None,
signature: str | None,
sig_alg: str | None,
verification_kp: CertificateKeyPair,
) -> None:
"""Verify a detached signature (Redirect binding).
`saml_param_name` is either `SAMLRequest` or `SAMLResponse`, and `saml_value` the
encoded message as it was received."""
if not (signature and sig_alg):
raise CannotHandleAssertion(ERROR_SIGNATURE_REQUIRED_BUT_ABSENT)
params = {saml_param_name: saml_value}
if relay_state is not None:
params["RelayState"] = relay_state
params["SigAlg"] = sig_alg
querystring = urlencode(params)
ctx = xmlsec.SignatureContext()
ctx.key = xmlsec.Key.from_memory(
verification_kp.certificate_data, xmlsec.constants.KeyDataFormatCertPem, None
)
sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
sig_alg, xmlsec.constants.TransformRsaSha1
)
try:
ctx.verify_binary(
querystring.encode("utf-8"),
sign_algorithm_transform,
b64decode(signature),
)
except xmlsec.Error as exc:
raise CannotHandleAssertion(ERROR_FAILED_TO_VERIFY) from exc
+6 -26
View File
@@ -4,10 +4,7 @@ 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 drf_spectacular.utils import extend_schema_field
from guardian.shortcuts import get_objects_for_user
from rest_framework.exceptions import ValidationError
from rest_framework.fields import ReadOnlyField
from rest_framework.viewsets import ModelViewSet
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
@@ -25,9 +22,6 @@ from authentik.lib.utils.reflection import ConditionalInheritance
class ApplicationEntitlementSerializer(AttributesMixinSerializer, ModelSerializer):
"""ApplicationEntitlement Serializer"""
app_name = ReadOnlyField(source="app.name")
app_slug = ReadOnlyField(source="app.slug")
def validate_app(self, app: Application) -> Application:
"""Ensure user has permission to view"""
request: HttpRequest = self.context.get("request")
@@ -46,8 +40,6 @@ class ApplicationEntitlementSerializer(AttributesMixinSerializer, ModelSerialize
"pbm_uuid",
"name",
"app",
"app_name",
"app_slug",
"attributes",
]
@@ -58,26 +50,15 @@ class ApplicationEntitlementFilter(FilterSet):
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."
),
)
@extend_schema_field(
{
"type": "integer",
"description": _(
"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]:
if (
not get_objects_for_user(self.request.user, "authentik_core.view_user_applications")
.filter(pk=value.pk)
.exists()
):
raise ValidationError({"for_user": "User not found"})
return queryset.filter(pk__in=value.all_app_entitlements().values("pk"))
class Meta:
@@ -99,7 +80,7 @@ class ApplicationEntitlementViewSet(
):
"""ApplicationEntitlement Viewset"""
queryset = ApplicationEntitlement.objects.select_related("app").all()
queryset = ApplicationEntitlement.objects.all()
serializer_class = ApplicationEntitlementSerializer
search_fields = [
"pbm_uuid",
@@ -109,5 +90,4 @@ class ApplicationEntitlementViewSet(
"attributes",
]
filterset_class = ApplicationEntitlementFilter
ordering = ["app__name", "name"]
ordering_fields = ["name", "app__name"]
ordering = ["name"]
+20 -10
View File
@@ -12,6 +12,7 @@ from drf_spectacular.utils import (
extend_schema,
extend_schema_field,
)
from guardian.shortcuts import get_objects_for_user
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import action
from rest_framework.exceptions import PermissionDenied
@@ -35,7 +36,6 @@ from authentik.core.models import Group, User
from authentik.endpoints.connectors.agent.auth import AgentAuth
from authentik.rbac.api.roles import RoleSerializer
from authentik.rbac.decorators import permission_required
from authentik.rbac.filters import ObjectFilter
from authentik.rbac.models import Role
@@ -253,9 +253,11 @@ class GroupSerializer(AttributesMixinSerializer, ModelSerializer):
if not has_perm:
raise ValidationError(
_(
"User does not have permission to set "
"superuser status to {superuser_status}."
).format(superuser_status=superuser)
(
"User does not have permission to set "
"superuser status to {superuser_status}."
).format_map({"superuser_status": superuser})
)
)
return superuser
@@ -512,9 +514,13 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
def add_user(self, request: Request, body: UserAccountSerializer, pk: str) -> Response:
"""Add user to group"""
group: Group = self.get_object()
user = ObjectFilter.visible_in_list(
request, User.objects.filter(pk=body.validated_data.get("pk")), "core/users:list"
).first()
user: User = (
get_objects_for_user(request.user, "authentik_core.view_user")
.filter(
pk=body.validated_data.get("pk"),
)
.first()
)
if not user:
raise Http404
if not group.users.filter(pk=user.pk).exists():
@@ -547,9 +553,13 @@ class GroupViewSet(UsedByMixin, ModelViewSet):
def remove_user(self, request: Request, body: UserAccountSerializer, pk: str) -> Response:
"""Remove user from group"""
group: Group = self.get_object()
user = ObjectFilter.visible_in_list(
request, User.objects.filter(pk=body.validated_data.get("pk")), "core/users:list"
).first()
user: User = (
get_objects_for_user(request.user, "authentik_core.view_user")
.filter(
pk=body.validated_data.get("pk"),
)
.first()
)
if not user:
raise Http404
group.users.remove(user)
+2 -6
View File
@@ -1,7 +1,6 @@
from typing import Any
from django.contrib.contenttypes.models import ContentType
from django.db.models import Model
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError
from rest_framework.fields import CharField, SerializerMethodField
@@ -13,6 +12,7 @@ from authentik.lib.utils.dict import get_path_from_dict
class AttributesMixinSerializer(ModelSerializer):
def validate(self, data: dict[str, Any]) -> dict[str, Any]:
model = self.Meta.model
attrs = data.get("attributes", {})
@@ -20,12 +20,7 @@ class AttributesMixinSerializer(ModelSerializer):
object_type=ContentType.objects.get_for_model(model),
enabled=True,
)
instance = self.instance if isinstance(self.instance, Model) else None
hidden = self.field_rules(instance).hidden
for attr in attributes:
path = f"attributes.{attr.key}"
if any(path == key or path.startswith(f"{key}.") for key in hidden):
continue
value = get_path_from_dict(attrs, attr.key)
attr.run_validation(value)
return data
@@ -49,6 +44,7 @@ class ContentTypeSerializer(ModelSerializer):
class ObjectAttributeSerializer(ModelSerializer):
object_type = CharField()
object_type_obj = ContentTypeSerializer(read_only=True, source="object_type")
+2 -11
View File
@@ -9,10 +9,7 @@ from rest_framework.fields import (
from rest_framework.request import Request
from rest_framework.response import Response
from authentik.admin.files.backends.static import static_url_name
from authentik.admin.files.manager import get_file_manager
from authentik.admin.files.usage import FileUsage
from authentik.core.api.utils import PassiveSerializer, ThemedUrlsSerializer
from authentik.core.api.utils import PassiveSerializer
from authentik.lib.models import DeprecatedMixin
from authentik.lib.utils.reflection import all_subclasses
@@ -26,7 +23,6 @@ class TypeCreateSerializer(PassiveSerializer):
model_name = CharField(required=True)
icon_url = CharField(required=False)
icon_themed_urls = ThemedUrlsSerializer(required=False, allow_null=True)
requires_enterprise = BooleanField(default=False)
deprecated = BooleanField(default=False)
@@ -64,17 +60,12 @@ class TypesMixin:
continue
instance = subclass()
try:
icon_url = getattr(instance, "icon_url", None)
type_signature = {
"name": subclass._meta.verbose_name,
"description": subclass.__doc__,
"component": instance.component,
"model_name": subclass._meta.model_name,
"icon_url": icon_url,
# Types only have their built-in default icons, from static()
"icon_themed_urls": get_file_manager(FileUsage.MEDIA).themed_urls(
static_url_name(icon_url)
),
"icon_url": getattr(instance, "icon_url", None),
"requires_enterprise": False,
"deprecated": isinstance(instance, DeprecatedMixin),
}
+45 -65
View File
@@ -4,7 +4,7 @@ from datetime import timedelta
from typing import Any
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import AnonymousUser, Permission
from django.db import models
from django.db.models import Exists, OuterRef, Prefetch, Q
from django.db.transaction import atomic
@@ -14,7 +14,7 @@ from django.urls import reverse_lazy
from django.utils.http import urlencode
from django.utils.text import slugify
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _
from django_filters.filters import (
BooleanFilter,
CharFilter,
@@ -101,19 +101,14 @@ from authentik.flows.views.executor import QS_KEY_TOKEN
from authentik.lib.avatars import get_avatar
from authentik.lib.utils.reflection import ConditionalInheritance
from authentik.lib.utils.time import timedelta_from_string, timedelta_string_validator
from authentik.lib.validators import (
PasswordHashRequiresOverride,
PasswordHashValidator,
)
from authentik.rbac.api.rbac import PermissionField
from authentik.lib.validators import validate_password_hash
from authentik.rbac.api.roles import RoleSerializer
from authentik.rbac.decorators import permission_required
from authentik.rbac.models import Role
from authentik.rbac.models import Role, get_permission_choices
from authentik.stages.email.flow import pickle_flow_token_for_email
from authentik.stages.email.models import EmailStage
from authentik.stages.email.tasks import send_mails
from authentik.stages.email.utils import TemplateEmailMessage
from authentik.stages.password.models import PasswordDevice
LOGGER = get_logger()
@@ -140,13 +135,7 @@ class PartialGroupSerializer(ModelSerializer):
]
class UserSerializer(
ConditionalInheritance(
"authentik.enterprise.required_actions.api.RequiredActionsUserSerializerMixin"
),
AttributesMixinSerializer,
ModelSerializer,
):
class UserSerializer(AttributesMixinSerializer, ModelSerializer):
"""User Serializer"""
is_superuser = SerializerMethodField()
@@ -171,14 +160,6 @@ class UserSerializer(
max_length=USERNAME_MAX_LENGTH,
validators=[UniqueValidator(queryset=User.objects.all().order_by("username"))],
)
password_change_date = DateTimeField(read_only=True)
password_locked = SerializerMethodField()
password_device = IntegerField(source="password_device.pk", read_only=True, allow_null=True)
def get_password_locked(self, user: User) -> bool:
"""Whether the user's password currently refuses authentication."""
device = getattr(user, "password_device", None)
return device is not None and device.locked
@property
def _should_include_groups(self) -> bool:
@@ -220,7 +201,10 @@ class UserSerializer(
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
self.fields["password"] = CharField(required=False, allow_null=True)
self.fields["password_hash"] = CharField(required=False, allow_null=True)
self.fields["permissions"] = ListField(required=False, child=PermissionField())
self.fields["permissions"] = ListField(
required=False,
child=ChoiceField(choices=get_permission_choices()),
)
def create(self, validated_data: dict) -> User:
"""Create a user, with blueprint-only password and permission writes."""
@@ -233,7 +217,12 @@ class UserSerializer(
instance: User = super().create(validated_data)
if is_blueprint:
self._set_password(instance, password, password_hash)
instance.assign_perms_to_managed_role(permissions)
perms_qs = Permission.objects.filter(
codename__in=[permission.split(".")[1] for permission in permissions]
).values_list("content_type__app_label", "codename")
perms_list = [f"{ct}.{name}" for ct, name in perms_qs]
instance.assign_perms_to_managed_role(perms_list)
self._ensure_password_not_empty(instance)
return instance
def update(self, instance: User, validated_data: dict) -> User:
@@ -247,15 +236,28 @@ class UserSerializer(
instance = super().update(instance, validated_data)
if is_blueprint:
self._set_password(instance, password, password_hash)
instance.assign_perms_to_managed_role(permissions)
perms_qs = Permission.objects.filter(
codename__in=[permission.split(".")[1] for permission in permissions]
).values_list("content_type__app_label", "codename")
perms_list = [f"{ct}.{name}" for ct, name in perms_qs]
instance.assign_perms_to_managed_role(perms_list)
self._ensure_password_not_empty(instance)
return instance
def _set_password(self, instance: User, password: str | None, password_hash: str | None = None):
"""Set password from plain text or hash."""
if password_hash is not None:
PasswordDevice.set_password_from_hash(instance, password_hash)
instance.set_password_from_hash(password_hash)
instance.save()
elif password:
PasswordDevice.set_password(instance, password)
instance.set_password(password)
instance.save()
def _ensure_password_not_empty(self, instance: User):
"""Store an explicit unusable password instead of an empty password field."""
if len(instance.password) == 0:
instance.set_unusable_password()
instance.save()
def get_avatar(self, user: User) -> str:
"""User's avatar, either a http/https URL or a data URI"""
@@ -351,13 +353,12 @@ class UserSerializer(
"type",
"uuid",
"password_change_date",
"password_locked",
"password_device",
"last_updated",
]
extra_kwargs = {
"name": {"allow_blank": True},
"date_joined": {"read_only": True},
"password_change_date": {"read_only": True},
}
@@ -499,32 +500,7 @@ class UserPasswordSetSerializer(PassiveSerializer):
class UserPasswordHashSetSerializer(PassiveSerializer):
"""Payload to set a users' password hash directly"""
password = CharField(required=True)
override = BooleanField(
default=False,
help_text=_(
"Import a valid password hash even when its parameters do not match authentik's "
"current password hashing settings."
),
)
def validate(self, attrs: dict) -> dict:
"""Validate the password hash with the requested override."""
try:
PasswordHashValidator(strict=not attrs["override"])(attrs["password"])
except PasswordHashRequiresOverride as exc:
raise ValidationError(
{
"password": [
_('%(reason)s Set "override" to true to import it anyway.')
% {"reason": reason}
for reason in exc.detail
]
}
) from exc
except ValidationError as exc:
raise ValidationError({"password": exc.detail}) from exc
return attrs
password = CharField(required=True, validators=[validate_password_hash])
class UserServiceAccountSerializer(PassiveSerializer):
@@ -667,7 +643,7 @@ class UserViewSet(
]
def get_queryset(self):
base_qs = User.objects.all().exclude_anonymous().select_related("password_device")
base_qs = User.objects.all().exclude_anonymous()
# Always prefetch groups since group PKs are always serialized.
# Use full prefetch when include_groups=true (for groups_obj), ID-only otherwise.
if self.serializer_class(context={"request": self.request})._should_include_groups:
@@ -821,6 +797,9 @@ class UserViewSet(
attributes={USER_ATTRIBUTE_TOKEN_EXPIRING: expiring},
path=USER_PATH_SERVICE_ACCOUNT,
)
user.set_unusable_password()
user.save()
response = {
"username": user.username,
"user_uid": user.uid,
@@ -931,7 +910,8 @@ class UserViewSet(
"""Set password for user"""
user: User = self.get_object()
try:
PasswordDevice.set_password(user, body.validated_data["password"], request=request)
user.set_password(body.validated_data["password"], request=request)
user.save()
except (ValidationError, IntegrityError) as exc:
LOGGER.debug("Failed to set password", exc=exc)
return Response(status=400)
@@ -964,12 +944,12 @@ class UserViewSet(
is available from the request payload.
"""
user: User = self.get_object()
PasswordDevice.set_password_from_hash(
user,
body.validated_data["password"],
request=request,
hasher_defaults_overridden=body.validated_data["override"],
)
try:
user.set_password_from_hash(body.validated_data["password"], request=request)
user.save()
except (ValidationError, IntegrityError) as exc:
LOGGER.debug("Failed to set password hash", exc=exc)
return Response(status=400)
self._update_session_hash_after_password_change(request, user)
return Response(status=204)
+8 -33
View File
@@ -20,13 +20,8 @@ from rest_framework.serializers import (
model_meta,
raise_errors_on_nested_writes,
)
from structlog.stdlib import get_logger
from authentik.lib.models import SimpleThroughModel
from authentik.rbac.endpoint_checks import EndpointChecks
from authentik.rbac.field_rules import FieldRules
LOGGER = get_logger()
def is_dict(value: Any):
@@ -52,6 +47,7 @@ class JSONExtension(OpenApiSerializerFieldExtension):
class ModelSerializer(BaseModelSerializer):
# By default, JSON fields we have are used to store dictionaries
serializer_field_mapping = BaseModelSerializer.serializer_field_mapping.copy()
serializer_field_mapping[models.JSONField] = JSONDictField
@@ -61,36 +57,15 @@ class ModelSerializer(BaseModelSerializer):
# `secret_fields` are visible for users which are allowed to change the object
secret_fields = getattr(self.Meta, "secret_fields", [])
request = self.context.get("request")
if secret_fields and request:
permission = f"{instance._meta.app_label}.change_{instance._meta.model_name}"
if not request.user.has_perm(permission, instance):
for field_name in secret_fields:
data.pop(field_name, None)
if rules := self.field_rules(instance):
data = rules.hide(data, self.fields)
if not secret_fields or not request:
return data
permission = f"{instance._meta.app_label}.change_{instance._meta.model_name}"
if request.user.has_perm(permission, instance):
return data
for field_name in secret_fields:
data.pop(field_name, None)
return data
def to_internal_value(self, data):
# Strip updates to fields not visible to the user
instance = self.instance if isinstance(self.instance, Model) else None
if rules := self.field_rules(instance):
data = rules.restrict_input(data, instance, self.fields)
return super().to_internal_value(data)
def field_rules(self, instance: Model | None) -> FieldRules:
request = self.context.get("request")
view = self.context.get("view")
model = getattr(getattr(self, "Meta", None), "model", None)
if request is None or model is None:
return FieldRules()
if model is not getattr(getattr(view, "queryset", None), "model", None):
return FieldRules()
checks = EndpointChecks.for_request(request)
rules = checks.field_rules(instance)
if unknown := rules.unknown_fields(self.fields):
checks.report_unknown_fields(unknown)
return rules
def update(self, instance: Model, validated_data):
raise_errors_on_nested_writes("update", self, validated_data)
info = model_meta.get_field_info(instance)
+2 -2
View File
@@ -36,8 +36,8 @@ class AuthentikCoreConfig(ManagedAppConfig):
def ready(self) -> None:
if CONFIG.get_bool("error_reporting.enabled", False):
setup_pre_fork()
# Under gunicorn's preload_app, some backends must finish initializing after
# the fork instead (see lifecycle/gunicorn.conf.py's post_fork hook)
# The server preloads the app before forking, some backends must finish
# initializing after the fork instead (see lifecycle/server.py's post_fork)
if not os.environ.get(TRACER_DEFER_POSTFORK_ENV_VAR):
setup_post_fork()
return super().ready()
+8 -15
View File
@@ -2,9 +2,7 @@
from typing import Any
from asgiref.sync import sync_to_async
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.http.request import HttpRequest
from authentik.core.models import Token, TokenIntents, User
@@ -40,15 +38,8 @@ class InbuiltBackend(ModelBackendNoAuthz):
def authenticate(
self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any
) -> User | None:
if username is None or password is None:
return None
user = User.objects.select_related("password_device").filter(username=username).first()
device = getattr(user, "password_device", None)
if device is None:
# Hash once, so a missing user or password takes as long as a wrong password.
make_password(password)
return None
if not device.check_password(password) or not self.user_can_authenticate(user):
user = super().authenticate(request, username=username, password=password, **kwargs)
if not user:
return None
self.set_method("password", request)
return user
@@ -56,9 +47,11 @@ class InbuiltBackend(ModelBackendNoAuthz):
async def aauthenticate(
self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any
) -> User | None:
return await sync_to_async(self.authenticate)(
request, username=username, password=password, **kwargs
)
user = await super().aauthenticate(request, username=username, password=password, **kwargs)
if not user:
return None
self.set_method("password", request)
return user
def set_method(self, method: str, request: HttpRequest | None, **kwargs):
"""Set method data on current flow, if possbiel"""
@@ -85,7 +78,7 @@ class TokenBackend(InbuiltBackend):
except User.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a nonexistent user (#20760).
make_password(password)
User().set_password(password, request=request)
return None
tokens = Token.objects.filter(
@@ -1,42 +0,0 @@
# Generated by Django 5.2.17 on 2026-10-10 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("authentik_core", "0066_user_authentik_core_user_email_idx"),
("authentik_stages_password", "0011_password_devices"),
]
operations = [
migrations.RemoveIndex(
model_name="user",
name="authentik_c_passwor_eec915_idx",
),
# Passwords moved to password devices. Keep the legacy columns, nullable,
# until a later release drops them.
migrations.AlterField(
model_name="user",
name="password",
field=models.CharField(max_length=128, null=True, verbose_name="password"),
),
migrations.AlterField(
model_name="user",
name="password_change_date",
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.SeparateDatabaseAndState(
state_operations=[
migrations.RemoveField(
model_name="user",
name="password",
),
migrations.RemoveField(
model_name="user",
name="password_change_date",
),
],
),
]
@@ -1,74 +0,0 @@
# Generated by Django 5.2.17 on 2026-10-30 04:07
from django.apps.registry import Apps
from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
PREFIX = "/static/authentik/sources/"
# Built-in source icons moved from a single file to a folder with a variant per theme
MOVED_ICONS = {
f"{PREFIX}{name}.svg": f"{PREFIX}{name}/%(theme)s.svg"
for name in (
"apple",
"azuread",
"discord",
"dropbox",
"entraid",
"facebook",
"github",
"gitlab",
"google",
"mailcow",
"okta",
"openidconnect",
"patreon",
"plex",
"proxy",
"rac",
"radius",
"reddit",
"slack",
"ssf",
"telegram",
"twitch",
"twitter",
"wechat",
"wsfed",
)
} | {
f"{PREFIX}kerberos.png": f"{PREFIX}kerberos/%(theme)s.png",
f"{PREFIX}ldap.png": f"{PREFIX}ldap/%(theme)s.svg",
f"{PREFIX}saml.png": f"{PREFIX}saml/%(theme)s.png",
f"{PREFIX}scim.png": f"{PREFIX}scim/%(theme)s.svg",
}
# Fields set through the file picker, where admins could pick a built-in icon
FILE_FIELDS = (
("authentik_core", "source", "icon"),
("authentik_core", "application", "meta_icon"),
("authentik_brands", "brand", "branding_logo"),
("authentik_brands", "brand", "branding_favicon"),
("authentik_brands", "brand", "branding_default_flow_background"),
("authentik_flows", "flow", "background"),
)
def move_source_icons(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
db_alias = schema_editor.connection.alias
for app_label, model_name, field in FILE_FIELDS:
model = apps.get_model(app_label, model_name)
for old, new in MOVED_ICONS.items():
model.objects.using(db_alias).filter(**{field: old}).update(**{field: new})
class Migration(migrations.Migration):
dependencies = [
("authentik_core", "0067_password_devices"),
("authentik_brands", "0016_brand_branding_map_tiles"),
("authentik_flows", "0031_alter_flow_layout"),
]
operations = [
migrations.RunPython(move_source_icons, migrations.RunPython.noop),
]
+47 -45
View File
@@ -9,9 +9,8 @@ from typing import Any, Self
from uuid import uuid4
import pgtrigger
from asgiref.sync import sync_to_async
from deepmerge import always_merger
from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import AbstractUser, Permission
from django.contrib.auth.models import UserManager as DjangoUserManager
from django.contrib.contenttypes.models import ContentType
@@ -34,7 +33,6 @@ from rest_framework.fields import BooleanField, CharField, IntegerField, ListFie
from rest_framework.serializers import Serializer
from structlog.stdlib import get_logger
from authentik.admin.files.backends.static import static_url_name
from authentik.admin.files.fields import FileField
from authentik.admin.files.manager import get_file_manager
from authentik.admin.files.usage import FileUsage
@@ -135,9 +133,6 @@ class UserTypes(models.TextChoices):
INTERNAL_SERVICE_ACCOUNT = "internal_service_account"
SERVICE_ACCOUNT_TYPES = (UserTypes.SERVICE_ACCOUNT, UserTypes.INTERNAL_SERVICE_ACCOUNT)
class AttributesMixin(models.Model):
"""Adds an attributes property to a model"""
@@ -370,12 +365,7 @@ class UserManager(DjangoUserManager.from_queryset(UserQuerySet)):
def create_user(self, username, email=None, password=None, **extra_fields):
"""User manager that doesn't assign is_superuser and is_staff"""
from authentik.stages.password.models import PasswordDevice
user = self.create(username=username, email=self.normalize_email(email), **extra_fields)
if password is not None:
PasswordDevice.set_password(user, password, signal=False)
return user
return self._create_user(username, email, password, **extra_fields)
def exclude_anonymous(self) -> QuerySet:
"""Exclude anonymous user"""
@@ -399,6 +389,7 @@ class User(SerializerModel, AttributesMixin, AbstractUser):
roles = models.ManyToManyField(
"authentik_rbac.Role", related_name="users", blank=True, through="UserRole"
)
password_change_date = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
@@ -415,6 +406,7 @@ class User(SerializerModel, AttributesMixin, AbstractUser):
]
indexes = [
models.Index(fields=["last_login"]),
models.Index(fields=["password_change_date"]),
models.Index(fields=["uuid"]),
models.Index(fields=["path"]),
models.Index(fields=["type"]),
@@ -503,7 +495,7 @@ class User(SerializerModel, AttributesMixin, AbstractUser):
def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]:
"""Get all entitlements this user has for `app`."""
if not app:
return ApplicationEntitlement.objects.none()
return []
return self.all_app_entitlements().filter(app=app)
def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]:
@@ -581,33 +573,49 @@ class User(SerializerModel, AttributesMixin, AbstractUser):
)
return self.groups
# Passwords are written through authentik.stages.password.models.PasswordDevice.
# These read-only properties keep `user.password` and `user.password_change_date`
# working in expressions, Django's session hash and the user API.
@property
def password(self) -> str:
device = getattr(self, "password_device", None)
return device.password if device else UNUSABLE_PASSWORD_PREFIX
def set_password(self, raw_password, signal=True, sender=None, request=None):
if self.pk and signal:
from authentik.core.signals import password_changed
@property
def password_change_date(self) -> datetime:
device = getattr(self, "password_device", None)
return device.password_change_date if device else self.date_joined
if not sender:
sender = self
password_changed.send(sender=sender, user=self, password=raw_password, request=request)
self.password_change_date = now()
return super().set_password(raw_password)
def set_password_from_hash(self, password_hash: str, signal=True, sender=None, request=None):
"""Set password directly from a pre-hashed value.
Unlike set_password(), this does not hash the input again. The provided value
must already be validated by the caller, and it is stored directly on the user.
Because no raw password is available, downstream password sync integrations
such as LDAP and Kerberos cannot be updated from this code path.
"""
if self.pk and signal:
from authentik.core.signals import password_hash_changed
if not sender:
sender = self
password_hash_changed.send(sender=sender, user=self, request=request)
self.password = password_hash
self.password_change_date = now()
def check_password(self, raw_password: str) -> bool:
# Django's version writes `password` when it upgrades an outdated hash.
device = getattr(self, "password_device", None)
return device.check_password(raw_password) if device else False
"""
Return a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
async def acheck_password(self, raw_password: str) -> bool:
return await sync_to_async(self.check_password)(raw_password)
Slightly changed version which doesn't send a signal for such internal hash upgrades
"""
# Django's password writes would assign the read-only `password`; fail loudly instead.
def set_password(self, raw_password):
raise NotImplementedError("Use PasswordDevice.set_password()")
def setter(raw_password):
self.set_password(raw_password, signal=False)
# Password hash upgrades shouldn't be considered password changes.
self._password = None
self.save(update_fields=["password"])
def set_unusable_password(self):
raise NotImplementedError("Use PasswordDevice.set_unusable_password()")
return check_password(raw_password, self.password, setter)
@property
def uid(self) -> str:
@@ -632,13 +640,6 @@ class User(SerializerModel, AttributesMixin, AbstractUser):
return get_avatar(self)
def get_init_anonymous_user(user_model: type[User]) -> User:
"""Build guardian's anonymous user, which has no password device and so no password.
guardian's default calls `set_unusable_password()`, which needs a writable `password`."""
return user_model(username=settings.ANONYMOUS_USER_NAME)
class Provider(SerializerModel):
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
@@ -801,7 +802,7 @@ class Application(RequestableModel, SerializerModel, PolicyBindingModel):
@property
def get_meta_icon_themed_urls(self) -> dict[str, str] | None:
"""Get themed URLs for meta_icon if it contains %(theme)s or is a built-in source icon"""
"""Get themed URLs for meta_icon if it contains %(theme)s"""
if not self.meta_icon:
return None
@@ -1036,10 +1037,9 @@ class Source(ManagedModel, SerializerModel, PolicyBindingModel):
request=None,
use_cache: bool = True,
) -> dict[str, str] | None:
"""Get themed URLs for the icon if it contains %(theme)s or is a built-in source icon."""
"""Get themed URLs for icon if it contains %(theme)s."""
if not self.icon:
# Subclasses fall back to a built-in default icon, relative like their icon_url
return get_file_manager(FileUsage.MEDIA).themed_urls(static_url_name(self.icon_url))
return None
return get_file_manager(FileUsage.MEDIA).themed_urls(
self.icon,
request,
@@ -1692,4 +1692,6 @@ class Actor(ExpiringModel, User):
type=UserTypes.SERVICE_ACCOUNT,
**kwargs,
)
actor.set_unusable_password()
actor.save()
return actor
+2 -10
View File
@@ -2,14 +2,13 @@ from os import getenv
from django.core.exceptions import ImproperlyConfigured
from django.dispatch import receiver
from rest_framework.exceptions import ValidationError
from structlog.stdlib import get_logger
from authentik.admin.utils import get_system_settings
from authentik.blueprints.models import BlueprintInstance
from authentik.blueprints.v1.importer import Importer
from authentik.core.apps import Setup
from authentik.lib.validators import PasswordHashValidator
from authentik.lib.validators import validate_password_hash
from authentik.root.signals import post_startup
BOOTSTRAP_BLUEPRINT = "system/bootstrap.yaml"
@@ -39,14 +38,7 @@ def post_startup_setup_bootstrap(sender, **_):
LOGGER.info("Instance is already setup, skipping")
return
if password_hash := getenv("AUTHENTIK_BOOTSTRAP_PASSWORD_HASH"):
try:
PasswordHashValidator()(password_hash)
except ValidationError as exc:
raise ImproperlyConfigured(
"AUTHENTIK_BOOTSTRAP_PASSWORD_HASH does not match authentik's current "
"password hashing settings. Generate a new hash with authentik's current "
"settings. See https://docs.goauthentik.io/core/password-hashes/."
) from exc
validate_password_hash(password_hash)
importer = Importer.from_string(content)
valid, logs = importer.validate()
if not valid:
+2 -2
View File
@@ -11,6 +11,7 @@ from structlog.stdlib import get_logger
from authentik.admin.models import SystemSettings
from authentik.admin.utils import (
clear_system_settings_cache,
get_system_settings,
normalize_base_url,
)
@@ -19,7 +20,6 @@ from authentik.core.apps import Setup
from authentik.flows.models import Flow, FlowAuthenticationRequirement, in_memory_stage
from authentik.flows.planner import FlowPlanner
from authentik.flows.stage import StageView
from authentik.outposts.apps import set_outpost_host
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
LOGGER = get_logger()
@@ -80,7 +80,7 @@ class PostSetupStageView(StageView):
)
if base_url:
SystemSettings.objects.filter(pk=get_system_settings().pk).update(base_url=base_url)
set_outpost_host(base_url)
clear_system_settings_cache()
# Remember we're setup
Setup.set(True)
# Disable OOBE Blueprints
+13 -7
View File
@@ -244,8 +244,10 @@ class SourceFlowManager:
error = Exception(
_(
"Request to authenticate with {source} has been denied. Please authenticate "
"with the source you've previously signed up with."
).format(source=self.source.name),
"with the source you've previously signed up with.".format_map(
{"source": self.source.name}
)
),
)
return self.error_handler(error)
@@ -383,8 +385,10 @@ class SourceFlowManager:
stages=[
in_memory_stage(
MessageStage,
message=_("Successfully authenticated with {source}!").format(
source=self.source.name
message=_(
"Successfully authenticated with {source}!".format_map(
{"source": self.source.name}
)
),
)
],
@@ -416,7 +420,7 @@ class SourceFlowManager:
).from_http(self.request)
messages.success(
self.request,
_("Successfully linked {source}!").format(source=self.source.name),
_("Successfully linked {source}!".format_map({"source": self.source.name})),
)
return redirect(
reverse(
@@ -443,8 +447,10 @@ class SourceFlowManager:
stages=[
in_memory_stage(
MessageStage,
message=_("Successfully authenticated with {source}!").format(
source=self.source.name
message=_(
"Successfully authenticated with {source}!".format_map(
{"source": self.source.name}
)
),
)
],
@@ -1,5 +1,13 @@
{% load i18n %}
<div class="ak-c-placeholder" id="ak-placeholder" slot="placeholder">
{% include "./spinner.html" %}
<span
class="pf-c-spinner"
role="progressbar"
aria-valuetext="Loading..."
>
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
</div>
@@ -1,7 +0,0 @@
{% load i18n %}
<span class="pf-c-spinner" role="progressbar" aria-valuetext="{% trans "Loading..." %}">
<span class="pf-c-spinner__clipper"></span>
<span class="pf-c-spinner__lead-ball"></span>
<span class="pf-c-spinner__tail-ball"></span>
</span>
@@ -14,13 +14,6 @@
:root {
--ak-global--background-image: url("{{ request.brand.branding_default_flow_background_url|iriencode|safe }}");
}
{% with themed=request.brand.branding_default_flow_background_themed_urls %}
{% if themed %}
:root[data-theme="dark"] {
--ak-global--background-image: url("{{ themed.dark|iriencode|safe }}");
}
{% endif %}
{% endwith %}
:root[data-theme="dark"] .branding-logo--light,
:root:not([data-theme="dark"]) .branding-logo--dark {
display: none;
@@ -135,112 +135,6 @@ class TestApplicationEntitlements(APITestCase):
{"non_field_errors": ["One of 'group', 'user' must be set."]},
)
def test_api_for_user(self):
"""Test listing all entitlements a user has via for_user"""
other_app = Application.objects.create(name=generate_id(), slug=generate_id())
ent_direct = ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
PolicyBinding.objects.create(target=ent_direct, user=self.user, order=0)
group = Group.objects.create(name=generate_id())
self.user.groups.add(group)
ent_group = ApplicationEntitlement.objects.create(app=other_app, name=generate_id())
PolicyBinding.objects.create(target=ent_group, group=group, order=0)
# Entitlement the user does not have
ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
self.client.force_login(create_test_admin_user())
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": self.user.pk},
)
self.assertEqual(res.status_code, 200)
body = res.json()
self.assertEqual(body["pagination"]["count"], 2)
self.assertCountEqual(
[ent["name"] for ent in body["results"]],
[ent_direct.name, ent_group.name],
)
self.assertCountEqual(
[ent["app_name"] for ent in body["results"]],
[self.app.name, other_app.name],
)
def test_api_for_user_ordering(self):
"""Test that for_user results can be ordered by application name"""
app_a = Application.objects.create(name=f"aaa-{generate_id()}", slug=generate_id())
app_b = Application.objects.create(name=f"bbb-{generate_id()}", slug=generate_id())
ent_a = ApplicationEntitlement.objects.create(app=app_a, name=generate_id())
ent_b = ApplicationEntitlement.objects.create(app=app_b, name=generate_id())
PolicyBinding.objects.create(target=ent_a, user=self.user, order=0)
PolicyBinding.objects.create(target=ent_b, user=self.user, order=0)
self.client.force_login(create_test_admin_user())
for ordering, expected in [
("app__name", [ent_a.name, ent_b.name]),
("-app__name", [ent_b.name, ent_a.name]),
]:
with self.subTest(ordering=ordering):
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": self.user.pk, "ordering": ordering, "search": ""},
)
self.assertEqual(res.status_code, 200)
self.assertEqual(
[ent["name"] for ent in res.json()["results"]],
expected,
)
def test_api_for_user_deduplicated(self):
"""Test that an entitlement matched by multiple bindings is only returned once"""
ent = ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
PolicyBinding.objects.create(target=ent, user=self.user, order=0)
group = Group.objects.create(name=generate_id())
self.user.groups.add(group)
PolicyBinding.objects.create(target=ent, group=group, order=1)
self.client.force_login(create_test_admin_user())
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": self.user.pk},
)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.json()["pagination"]["count"], 1)
def test_api_for_user_with_permission(self):
"""Test for_user with explicitly granted permissions (non-superuser)"""
ent = ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
PolicyBinding.objects.create(target=ent, user=self.user, order=0)
self.other_user.assign_perms_to_managed_role("authentik_core.view_applicationentitlement")
self.other_user.assign_perms_to_managed_role("authentik_core.view_user_applications")
self.client.force_login(self.other_user)
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": self.user.pk},
)
self.assertEqual(res.status_code, 200)
body = res.json()
self.assertEqual(body["pagination"]["count"], 1)
self.assertEqual(body["results"][0]["name"], ent.name)
def test_api_for_user_denied(self):
"""Test that for_user requires view_user_applications on the target user"""
ent = ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
PolicyBinding.objects.create(target=ent, user=self.user, order=0)
self.other_user.assign_perms_to_managed_role("authentik_core.view_applicationentitlement")
self.client.force_login(self.other_user)
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": self.user.pk},
)
self.assertEqual(res.status_code, 400)
self.assertJSONEqual(res.content, {"for_user": "User not found"})
def test_api_for_user_invalid(self):
"""Test for_user with a non-numerical value"""
self.client.force_login(create_test_admin_user())
res = self.client.get(
reverse("authentik_api:applicationentitlement-list"),
{"for_user": "foo"},
)
self.assertEqual(res.status_code, 400)
self.assertIn("for_user", res.json())
def test_api_bindings_group(self):
"""Test that API doesn't allow policies to be bound to this"""
ent = ApplicationEntitlement.objects.create(app=self.app, name=generate_id())
-29
View File
@@ -67,32 +67,3 @@ class TestErrorViewsRouting(TestCase):
response = getattr(self.client, method)(url)
self.assertEqual(response.status_code, 404)
self.assertTemplateUsed(response, "if/error.html")
class TestErrorViewsThemedBackground(TestCase):
"""The error page renders without the UI, so it resolves a themed default flow
background itself instead of sending the browser a %(theme)s placeholder."""
def test_themed_background(self):
"""The light variant is the default and the dark variant follows data-theme"""
create_test_brand(
branding_default_flow_background="/static/authentik/sources/kerberos/%(theme)s.png"
)
response = self.client.get("/this-path-does-not-exist/")
self.assertEqual(response.status_code, 404)
self.assertTemplateUsed(response, "if/error.html")
content = response.content.decode()
self.assertNotIn("%(theme)s", content)
self.assertIn(
'<link rel="prefetch" href="/static/authentik/sources/kerberos/light.png"', content
)
self.assertRegex(
content,
r":root \{\s*--ak-global--background-image: "
r'url\("/static/authentik/sources/kerberos/light.png"\);',
)
self.assertRegex(
content,
r':root\[data-theme="dark"\] \{\s*--ak-global--background-image: '
r'url\("/static/authentik/sources/kerberos/dark.png"\);',
)
@@ -1,50 +0,0 @@
"""Test moving stored built-in source icons to their themed folders"""
from importlib import import_module
from django.apps import apps
from django.db import connection
from django.test import TestCase
from authentik.core.models import Application
from authentik.flows.models import Flow, FlowDesignation
from authentik.lib.generators import generate_id
from authentik.sources.oauth.models import OAuthSource
move_source_icons = import_module(
"authentik.core.migrations.0068_move_source_icons"
).move_source_icons
class TestMoveSourceIcons(TestCase):
"""Test moving stored built-in source icons to their themed folders"""
def test_move(self):
"""Test built-in icons are moved, other values are kept"""
github = OAuthSource.objects.create(
name=generate_id(), slug=generate_id(), icon="/static/authentik/sources/github.svg"
)
custom = OAuthSource.objects.create(
name=generate_id(), slug=generate_id(), icon="sources/github.svg"
)
app = Application.objects.create(
name=generate_id(), slug=generate_id(), meta_icon="/static/authentik/sources/ldap.png"
)
flow = Flow.objects.create(
name=generate_id(),
slug=generate_id(),
designation=FlowDesignation.AUTHENTICATION,
background="/static/authentik/sources/kerberos.png",
)
with connection.schema_editor() as schema_editor:
move_source_icons(apps, schema_editor)
github.refresh_from_db()
custom.refresh_from_db()
app.refresh_from_db()
flow.refresh_from_db()
self.assertEqual(github.icon, "/static/authentik/sources/github/%(theme)s.svg")
self.assertEqual(custom.icon, "sources/github.svg")
self.assertEqual(app.meta_icon, "/static/authentik/sources/ldap/%(theme)s.svg")
self.assertEqual(flow.background, "/static/authentik/sources/kerberos/%(theme)s.png")
@@ -1,49 +0,0 @@
"""Existing passwords move to password devices."""
from datetime import timedelta
from importlib import import_module
from django.contrib.auth.hashers import make_password
from django.db import connection
from django.db.migrations.loader import MigrationLoader
from django.test import TestCase
from django.utils.timezone import now
from authentik.core.models import User
from authentik.lib.generators import generate_id
from authentik.stages.password.models import PasswordDevice
MIGRATION = ("authentik_stages_password", "0011_password_devices")
class TestPasswordMigration(TestCase):
"""Run the data copy against the historical models and the retained columns."""
def test_create_password_devices(self):
usable, unusable, empty = (User.objects.create(username=generate_id()) for _ in range(3))
password = make_password(generate_id())
changed_at = now() - timedelta(days=3)
with connection.cursor() as cursor:
# Before the migration, every user row has a password.
cursor.execute("UPDATE authentik_core_user SET password = '' WHERE password IS NULL")
cursor.executemany(
"UPDATE authentik_core_user SET password = %s, password_change_date = %s "
"WHERE id = %s",
[
(password, changed_at, usable.pk),
(make_password(None), changed_at, unusable.pk),
("", changed_at, empty.pk),
],
)
apps = MigrationLoader(connection).project_state(MIGRATION).apps
migration = import_module(f"authentik.stages.password.migrations.{MIGRATION[1]}")
with connection.schema_editor() as schema_editor:
migration.create_password_devices(apps, schema_editor)
device = PasswordDevice.objects.get(user=usable)
self.assertEqual(device.password, password)
self.assertEqual(device.password_change_date, changed_at)
self.assertEqual(device.failed_attempts, 0)
self.assertIsNone(device.locked_at)
self.assertFalse(PasswordDevice.objects.filter(user__in=[unusable, empty]).exists())
@@ -1,51 +0,0 @@
"""Nested user data must not load a password device for every row."""
from django.test import TestCase
from django.utils.timezone import now
from authentik.core.api.users import UserSerializer
from authentik.core.models import Application, User
from authentik.core.tests.utils import create_test_flow, create_test_user
from authentik.lib.generators import generate_id
from authentik.providers.oauth2.api.tokens import (
AccessTokenViewSet,
AuthorizationCodeViewSet,
RefreshTokenViewSet,
)
from authentik.providers.oauth2.models import OAuth2Provider
from authentik.stages.consent.api import UserConsentViewSet
from authentik.stages.consent.models import UserConsent
class TestPasswordQueries(TestCase):
"""Cover both users with a password and users without a device."""
def test_nested_password_dates(self):
users = [create_test_user(), User.objects.create(username=generate_id())]
provider = OAuth2Provider.objects.create(
name=generate_id(), authorization_flow=create_test_flow()
)
application = Application.objects.create(name=generate_id(), slug=generate_id())
field = UserSerializer().fields["password_change_date"]
expected = [field.to_representation(user.password_change_date) for user in users]
for viewset in (
AuthorizationCodeViewSet,
RefreshTokenViewSet,
AccessTokenViewSet,
UserConsentViewSet,
):
with self.subTest(viewset=viewset):
model = viewset.queryset.model
for user in users:
extra = {"code": generate_id()} if viewset is AuthorizationCodeViewSet else {}
if model is UserConsent:
model.objects.create(user=user, application=application)
else:
model.objects.create(user=user, provider=provider, auth_time=now(), **extra)
with self.assertNumQueries(1):
dates = [
field.to_representation(field.get_attribute(record.user))
for record in viewset.queryset.filter(user__in=users).order_by("user_id")
]
self.assertEqual(dates, expected)
@@ -1,7 +1,5 @@
"""Test providers API"""
from json import loads
from django.urls import reverse
from rest_framework.test import APITestCase
@@ -26,18 +24,3 @@ class TestProvidersAPI(APITestCase):
reverse("authentik_api:provider-types"),
)
self.assertEqual(response.status_code, 200)
def test_types_icon_themed_urls(self):
"""Test themed icon URLs of provider types"""
response = self.client.get(reverse("authentik_api:provider-types"))
types = {
provider_type["model_name"]: provider_type for provider_type in loads(response.content)
}
self.assertEqual(
types["proxyprovider"]["icon_themed_urls"],
{
"light": "/static/authentik/sources/proxy/light.svg",
"dark": "/static/authentik/sources/proxy/dark.svg",
},
)
+5 -28
View File
@@ -2,20 +2,19 @@ from http import HTTPStatus
from os import environ
from unittest.mock import patch
from django.contrib.auth.hashers import PBKDF2PasswordHasher, make_password
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from rest_framework.exceptions import ValidationError
from authentik.admin.flags import patch_flag
from authentik.admin.utils import get_system_settings
from authentik.blueprints.tests import apply_blueprint, reconcile_app
from authentik.blueprints.tests import apply_blueprint
from authentik.core.apps import Setup
from authentik.core.models import Token, TokenIntents, User
from authentik.flows.models import Flow
from authentik.flows.tests import APIFlowTestCase
from authentik.lib.generators import generate_id
from authentik.outposts.apps import MANAGED_OUTPOST
from authentik.outposts.models import Outpost, OutpostConfig
from authentik.root.signals import post_startup, pre_startup
@@ -81,13 +80,9 @@ class TestSetup(APIFlowTestCase):
@apply_blueprint("default/flow-oobe.yaml")
@apply_blueprint("system/bootstrap.yaml")
@reconcile_app("authentik_outposts")
def test_setup_flow_full(self):
"""Test full setup flow"""
Setup.set(False)
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
outpost.config = OutpostConfig(authentik_host="")
outpost.save()
res = self.client.get(reverse("authentik_core:setup"))
self.assertEqual(res.status_code, HTTPStatus.FOUND)
@@ -136,8 +131,6 @@ class TestSetup(APIFlowTestCase):
self.assertTrue(user.check_password(pw))
self.assertEqual(get_system_settings().base_url, "https://authentik.company")
outpost.refresh_from_db()
self.assertEqual(outpost.config.authentik_host, "https://authentik.company")
@patch_flag(Setup, False)
@apply_blueprint("default/flow-oobe.yaml")
@@ -259,31 +252,15 @@ class TestSetup(APIFlowTestCase):
self.assertEqual(user.password, password_hash)
self.assertTrue(user.check_password(password))
@patch_flag(Setup, False)
def test_setup_bootstrap_env_noncurrent_password_hash(self):
"""Test setup rejects a noncurrent password hash from the environment."""
User.objects.filter(username="akadmin").delete()
environ.pop("AUTHENTIK_BOOTSTRAP_PASSWORD", None)
hasher = PBKDF2PasswordHasher()
hasher.iterations -= 1
environ["AUTHENTIK_BOOTSTRAP_PASSWORD_HASH"] = hasher.encode(generate_id(), hasher.salt())
pre_startup.send(sender=self)
with self.assertRaises(ImproperlyConfigured):
post_startup.send(sender=self)
self.assertFalse(Setup.get())
self.assertFalse(User.objects.filter(username="akadmin").exists())
@patch_flag(Setup, False)
def test_setup_bootstrap_env_malformed_password_hash(self):
"""Test setup rejects a malformed password hash from the environment."""
User.objects.filter(username="akadmin").delete()
environ.pop("AUTHENTIK_BOOTSTRAP_PASSWORD", None)
environ["AUTHENTIK_BOOTSTRAP_PASSWORD_HASH"] = "not-a-valid-hash"
environ["AUTHENTIK_BOOTSTRAP_PASSWORD_HASH"] = "pbkdf2_sha256$1000000/K4wGpWYKfJPSCcNM="
pre_startup.send(sender=self)
with self.assertRaises(ImproperlyConfigured):
with self.assertRaises(ValidationError):
post_startup.send(sender=self)
self.assertFalse(Setup.get())
-33
View File
@@ -1,17 +1,8 @@
from json import loads
from django.apps import apps
from django.urls import reverse
from rest_framework.test import APITestCase
from authentik.core.tests.utils import create_test_admin_user
from authentik.lib.generators import generate_id
from authentik.sources.oauth.models import OAuthSource
GITHUB_ICON_THEMED_URLS = {
"light": "/static/authentik/sources/github/light.svg",
"dark": "/static/authentik/sources/github/dark.svg",
}
class TestSourceAPI(APITestCase):
@@ -26,27 +17,3 @@ class TestSourceAPI(APITestCase):
reverse("authentik_api:source-used-by", kwargs={"slug": "authentik-built-in"}),
)
self.assertEqual(response.status_code, 200)
def test_user_settings_icon_themed_urls(self):
"""Test themed icon URLs of user settings"""
github = OAuthSource.objects.create(
name=generate_id(), slug=generate_id(), provider_type="github"
)
custom = OAuthSource.objects.create(
name=generate_id(), slug=generate_id(), icon="https://example.com/logo.png"
)
response = self.client.get(reverse("authentik_api:source-user-settings"))
self.assertEqual(response.status_code, 200)
settings = {setting["object_uid"]: setting for setting in loads(response.content)}
self.assertEqual(settings[github.slug]["icon_themed_urls"], GITHUB_ICON_THEMED_URLS)
self.assertIsNone(settings[custom.slug]["icon_themed_urls"])
def test_types_icon_themed_urls(self):
"""Test themed icon URLs of source types"""
response = self.client.get(reverse("authentik_api:source-types"))
self.assertEqual(response.status_code, 200)
types = {source_type["model_name"]: source_type for source_type in loads(response.content)}
self.assertEqual(types["githuboauthsource"]["icon_themed_urls"], GITHUB_ICON_THEMED_URLS)
+2 -3
View File
@@ -12,7 +12,6 @@ from authentik.core.models import User
from authentik.core.signals import password_changed, password_hash_changed
from authentik.events.models import Event
from authentik.lib.generators import generate_id
from authentik.stages.password.models import PasswordDevice
class TestUsers(TestCase):
@@ -113,14 +112,14 @@ class TestUsers(TestCase):
"UserKerberosSourceConnection.objects.select_related"
) as kerberos_connections_select,
):
PasswordDevice.set_password_from_hash(user, make_password("new-password")) # nosec
user.set_password_from_hash(make_password("new-password")) # nosec
user.save()
finally:
password_changed.disconnect(dispatch_uid=dispatch_uid)
password_hash_changed.disconnect(dispatch_uid=hash_dispatch_uid)
self.assertEqual(password_changed_captured, [])
self.assertEqual(len(password_hash_changed_captured), 1)
self.assertFalse(password_hash_changed_captured[0]["hasher_defaults_overridden"])
ldap_sources_filter.assert_not_called()
kerberos_connections_select.assert_not_called()
+18 -88
View File
@@ -3,16 +3,10 @@
from datetime import datetime, timedelta
from json import loads
from django.conf import settings
from django.contrib.auth.hashers import (
PBKDF2PasswordHasher,
check_password,
make_password,
)
from django.contrib.auth.hashers import make_password
from django.db import connection
from django.test.utils import CaptureQueriesContext
from django.urls.base import reverse
from django.utils.module_loading import import_string
from django.utils.timezone import now
from rest_framework.test import APITestCase
@@ -33,19 +27,13 @@ from authentik.core.tests.utils import (
create_test_session,
create_test_user,
)
from authentik.events.models import Event, EventAction
from authentik.flows.models import FlowAuthenticationRequirement, FlowDesignation
from authentik.lib.generators import generate_id, generate_key
from authentik.rbac.models import Role
from authentik.stages.email.models import EmailStage
INVALID_PASSWORD_HASH = "not-a-valid-hash"
ALLOWED_ALGORITHMS = ", ".join(
import_string(path)().algorithm for path in settings.PASSWORD_HASHERS_IMPORT_ALLOWED
)
INVALID_PASSWORD_HASH_ERROR = (
f"Cannot identify hash function. Password hash must use one of: {ALLOWED_ALGORITHMS}."
)
INVALID_PASSWORD_HASH_ERROR = "Invalid password hash format. Must be a valid Django password hash."
class TestUsersAPI(APITestCase):
@@ -55,15 +43,10 @@ class TestUsersAPI(APITestCase):
self.admin = create_test_admin_user()
self.user = create_test_user()
def _set_password_hash(
self, user: User, password_hash: str, client=None, override: bool | None = None
):
data: dict[str, str | bool] = {"password": password_hash}
if override is not None:
data["override"] = override
def _set_password_hash(self, user: User, password_hash: str, client=None):
return (client or self.client).post(
reverse("authentik_api:user-set-password-hash", kwargs={"pk": user.pk}),
data=data,
data={"password": password_hash},
)
def _assert_password_hash_set(
@@ -72,20 +55,16 @@ class TestUsersAPI(APITestCase):
self.assertEqual(response.status_code, 204, response.data)
user.refresh_from_db()
self.assertEqual(user.password, password_hash)
self.assertTrue(check_password(password, user.password))
self.assertTrue(user.check_password(password))
def _assert_password_hash_rejected(
self,
user: User,
original_password_hash: str,
response,
errors: str | list[str] | None = INVALID_PASSWORD_HASH_ERROR,
self, user: User, original_password_hash: str, response
) -> None:
self.assertEqual(response.status_code, 400)
if errors is not None:
if isinstance(errors, str):
errors = [errors]
self.assertJSONEqual(response.content, {"password": errors})
self.assertJSONEqual(
response.content,
{"password": [INVALID_PASSWORD_HASH_ERROR]},
)
user.refresh_from_db()
self.assertEqual(user.password, original_password_hash)
@@ -113,30 +92,6 @@ class TestUsersAPI(APITestCase):
)
self.assertEqual(body["pagination"]["count"], len(expected))
def test_password_dates_do_not_add_queries_per_user(self):
"""Listing more password dates does not query each user's device separately."""
self.client.force_login(self.admin)
path = generate_id()
url = reverse("authentik_api:user-list")
counts = []
for size in (1, 5):
for _ in range(size):
create_test_user(path=path)
self.client.get(url, data={"path": path})
with CaptureQueriesContext(connection) as queries:
response = self.client.get(url, data={"path": path})
self.assertEqual(response.status_code, 200)
self.assertTrue(
all(user["password_change_date"] for user in response.json()["results"])
)
counts.append(
sum(
'FROM "authentik_stages_password_passworddevice"' in query["sql"]
for query in queries
)
)
self.assertEqual(*counts)
def test_filter_type_no_distinct(self):
"""Test that filtering by type doesn't make the list and count queries DISTINCT"""
self.client.force_login(self.admin)
@@ -320,7 +275,7 @@ class TestUsersAPI(APITestCase):
self.assertJSONEqual(response.content, {"password": ["This field may not be blank."]})
def test_set_password_hash(self):
"""Test setting a user's password from a current hash."""
"""Test setting a user's password from a hash."""
self.client.force_login(self.admin)
password = generate_key()
password_hash = make_password(password)
@@ -331,40 +286,15 @@ class TestUsersAPI(APITestCase):
def test_set_password_hash_invalid(self):
"""Test invalid password hashes are rejected."""
self.client.force_login(self.admin)
response = self._set_password_hash(self.user, INVALID_PASSWORD_HASH)
self._assert_password_hash_rejected(self.user, self.user.password, response)
def _noncurrent_pbkdf2_hash(self, password: str, salt: str | None = None) -> str:
hasher = PBKDF2PasswordHasher()
hasher.iterations -= 1
return hasher.encode(password, salt or hasher.salt())
def test_set_password_hash_override(self):
"""Test override imports a non-current hash, but not an invalid one."""
self.client.force_login(self.admin)
original_password = self.user.password
password = generate_key()
password_hash = self._noncurrent_pbkdf2_hash(password, "salt")
for password_hash in (
INVALID_PASSWORD_HASH,
"pbkdf2_sha256$1000000/K4wGpWYKfJPSCcNM=",
):
with self.subTest(password_hash=password_hash):
response = self._set_password_hash(self.user, password_hash)
response = self._set_password_hash(self.user, password_hash)
errors = response.json()["password"]
self._assert_password_hash_rejected(self.user, original_password, response, errors=errors)
self.assertEqual(len(errors), 2)
self.assertTrue(all("override" in error for error in errors))
response = self._set_password_hash(self.user, password_hash, override=True)
self._assert_password_hash_set(self.user, password, password_hash, response)
self.assertTrue(
Event.objects.filter(
action=EventAction.PASSWORD_SET,
user__pk=self.user.pk,
context__hasher_defaults_overridden=True,
).exists()
)
response = self._set_password_hash(self.user, INVALID_PASSWORD_HASH, override=True)
self._assert_password_hash_rejected(self.user, password_hash, response)
self._assert_password_hash_rejected(self.user, original_password, response)
def test_recovery(self):
"""Test user recovery link"""
+2 -2
View File
@@ -23,7 +23,6 @@ from authentik.crypto.builder import CertificateBuilder, PrivateKeyAlg
from authentik.crypto.models import CertificateKeyPair
from authentik.flows.models import Flow, FlowDesignation
from authentik.lib.generators import generate_id
from authentik.stages.password.models import PasswordDevice
def create_test_flow(
@@ -45,7 +44,8 @@ def create_test_user(name: str | None = None, **kwargs) -> User:
name=uid,
**kwargs,
)
PasswordDevice.set_password(user, uid)
user.set_password(uid)
user.save()
return user
+1 -5
View File
@@ -4,7 +4,7 @@ from dataclasses import dataclass
from rest_framework.fields import CharField
from authentik.core.api.utils import PassiveSerializer, ThemedUrlsSerializer
from authentik.core.api.utils import PassiveSerializer
from authentik.flows.challenge import Challenge
@@ -21,9 +21,6 @@ class UILoginButton:
# Icon URL, used as-is
icon_url: str | None = None
# Icon URLs per theme, preferred over icon_url when set
icon_themed_urls: dict[str, str] | None = None
# Whether this source should be displayed as a prominent button
promoted: bool = False
@@ -36,4 +33,3 @@ class UserSettingSerializer(PassiveSerializer):
title = CharField(required=True)
configure_url = CharField(required=False)
icon_url = CharField(required=False)
icon_themed_urls = ThemedUrlsSerializer(required=False, allow_null=True)
-5
View File
@@ -4,11 +4,9 @@ from json import loads
from os import makedirs
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import skipIf
from unittest.mock import patch
from cryptography.exceptions import InternalError
from cryptography.hazmat.backends.openssl.backend import backend
from cryptography.hazmat.primitives.serialization import (
load_pem_private_key as cryptography_load_pem_private_key,
)
@@ -197,7 +195,6 @@ class TestCrypto(APITestCase):
)
self.assertEqual(response.status_code, 400)
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_builder_mldsa(self):
"""Test Builder with the ML-DSA (FIPS 204) parameter sets"""
for alg, key_type in (
@@ -221,7 +218,6 @@ class TestCrypto(APITestCase):
instance.certificate.public_key().public_bytes_raw(),
)
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_builder_api_mldsa(self):
"""Test Builder (via API) with ML-DSA"""
self.client.force_login(create_test_admin_user())
@@ -268,7 +264,6 @@ class TestCrypto(APITestCase):
self.assertEqual(response.status_code, 400)
self.assertIn("key_data", loads(response.content))
@skipIf(backend._fips_enabled, "The FIPS provider has no ML-DSA")
def test_mldsa_key_type_validation(self):
"""ML-DSA keypairs are accepted for TLS, and rejected where nothing can sign with them"""
builder = CertificateBuilder(generate_id())
+2
View File
@@ -65,6 +65,8 @@ class Agent(Actor):
expiring=expiring,
expires=expires,
)
agent.set_unusable_password()
agent.save()
if policy_behavior == ActorPolicyInheritance.COPY:
agent.copy_parent_policy_bindings()
return agent
+22 -9
View File
@@ -1,6 +1,7 @@
"""Enterprise audit middleware"""
from copy import deepcopy
from functools import partial
from typing import Any
from django.apps.registry import apps
@@ -9,7 +10,7 @@ from django.db import connection
from django.db.models import ManyToManyRel, Model
from django.db.models.expressions import BaseExpression, Combinable
from django.db.models.signals import post_init
from django.http import HttpRequest, HttpResponse
from django.http import HttpRequest
from authentik.enterprise.audit.apps import AuditIncludeExpandedDiff
from authentik.events.middleware import AuditMiddleware, should_log_model
@@ -24,11 +25,23 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
"""Check if audit logging is enabled"""
return apps.get_app_config("authentik_enterprise").enabled()
def __call__(self, request: HttpRequest) -> HttpResponse:
# post_init fires for every model instance, so only connect it once enterprise is in use
if self.enabled:
self.connect(post_init, "post_init_handler")
return super().__call__(request)
def connect(self, request: HttpRequest):
super().connect(request)
if not self.enabled:
return
if not hasattr(request, "request_id"):
return
post_init.connect(
partial(self.post_init_handler, request=request),
dispatch_uid=request.request_id,
weak=False,
)
def disconnect(self, request: HttpRequest):
super().disconnect(request)
if not hasattr(request, "request_id"):
return
post_init.disconnect(dispatch_uid=request.request_id)
def serialize_simple(self, model: Model) -> dict:
"""Serialize a model in a very simple way. No ForeignKeys or other relationships are
@@ -91,11 +104,11 @@ class EnterpriseAuditMiddleware(AuditMiddleware):
**_,
):
if not self.is_current_request(request):
return None
if not should_log_model(instance):
return None
return
if not self.enabled:
return super().post_save_handler(request, sender, instance, created, thread_kwargs, **_)
if not should_log_model(instance):
return None
thread_kwargs = {}
if hasattr(instance, "_previous_state") or created:
prev_state = getattr(instance, "_previous_state", {})
+26 -17
View File
@@ -12,7 +12,7 @@ from authentik.core.models import Group, User
from authentik.core.tests.utils import create_test_admin_user
from authentik.enterprise.audit.apps import AuditIncludeExpandedDiff
from authentik.enterprise.audit.middleware import EnterpriseAuditMiddleware
from authentik.events.middleware import AuditMiddleware
from authentik.events.middleware import _CTX_REQUEST
from authentik.events.models import Event, EventAction
from authentik.events.utils import sanitize_item
from authentik.lib.generators import generate_id
@@ -88,6 +88,11 @@ class TestEnterpriseAudit(APITestCase):
"first_name": {"new_value": "", "previous_value": None},
"id": {"new_value": user.pk, "previous_value": None},
"last_name": {"new_value": "", "previous_value": None},
"password": {"new_value": "********************", "previous_value": None},
"password_change_date": {
"new_value": sanitize_item(user.password_change_date),
"previous_value": None,
},
},
)
@@ -224,6 +229,8 @@ class TestEnterpriseAudit(APITestCase):
"last_name": "",
"last_updated": sanitize_item(user.last_updated),
"name": user.name,
"password": "********************",
"password_change_date": sanitize_item(user.password_change_date),
"path": "users",
"type": "internal",
"username": user.username,
@@ -289,22 +296,24 @@ class TestEnterpriseAudit(APITestCase):
class TestEnterpriseAuditLifecycle(SimpleTestCase):
"""Enterprise audit callbacks stay scoped to their request."""
def test_post_init_connected_lazily(self):
"""post_init fires for every model instance, so only connect it once licensed"""
middleware = EnterpriseAuditMiddleware(Mock())
def test_disconnect_without_license_lookup(self):
"""Disconnect even if licensing is unavailable after connecting."""
request = RequestFactory().get("/")
request.request_id = generate_id()
with (
patch.object(EnterpriseAuditMiddleware, "connect") as connect,
patch.object(
EnterpriseAuditMiddleware, "enabled", new_callable=PropertyMock, return_value=False
) as enabled,
):
middleware(request)
connect.assert_not_called()
enabled.return_value = True
middleware(request)
connect.assert_called_once_with(post_init, "post_init_handler")
middleware = EnterpriseAuditMiddleware(Mock())
baseline = len(post_init.receivers)
with patch.object(
EnterpriseAuditMiddleware, "enabled", new_callable=PropertyMock, return_value=True
) as enabled:
middleware.connect(request)
self.assertEqual(len(post_init.receivers), baseline + 1)
try:
enabled.side_effect = AssertionError("cleanup must not query licensing")
middleware.disconnect(request)
self.assertEqual(len(post_init.receivers), baseline)
finally:
enabled.side_effect = None
middleware.disconnect(request)
def test_foreign_request_handlers(self):
"""Another request's callbacks must not query licensing or serialize models."""
@@ -315,7 +324,7 @@ class TestEnterpriseAuditLifecycle(SimpleTestCase):
other.request_id = generate_id()
for current in (None, other):
with self.subTest(current=current):
token = AuditMiddleware._current.set((middleware, current) if current else None)
token = _CTX_REQUEST.set(current)
try:
with (
patch.object(
@@ -333,4 +342,4 @@ class TestEnterpriseAuditLifecycle(SimpleTestCase):
enabled.assert_not_called()
serialize.assert_not_called()
finally:
AuditMiddleware._current.reset(token)
_CTX_REQUEST.reset(token)
@@ -110,91 +110,3 @@ class TestAppleRegister(APITestCase):
binding.refresh_from_db()
self.assertEqual(binding.apple_secure_enclave_key, new_enclave_key)
self.assertEqual(binding.apple_enclave_key_id, new_enclave_key_id)
@enterprise_test()
@reconcile_app("authentik_crypto")
def test_registration_state(self):
self.connection.apple_signing_key = generate_id()
self.connection.apple_sign_key_id = generate_id()
self.connection.apple_enc_key_id = generate_id()
self.connection.save()
binding = AgentDeviceUserBinding.objects.create(
target=self.device,
user=self.user,
connector=self.connector,
order=0,
apple_enclave_key_id=generate_id(),
)
response = self.client.get(
reverse("authentik_api:psso-register-device"),
HTTP_AUTHORIZATION=f"Bearer+agent {self.device_token.key}",
)
self.assertEqual(response.status_code, 200)
self.assertJSONEqual(
response.content,
{
"device_registered": True,
"sign_key_id": self.connection.apple_sign_key_id,
"enc_key_id": self.connection.apple_enc_key_id,
"users": [
{
"username": self.user.username,
"enclave_key_id": binding.apple_enclave_key_id,
}
],
},
)
@enterprise_test()
@reconcile_app("authentik_crypto")
def test_registration_state_unregistered(self):
response = self.client.get(
reverse("authentik_api:psso-register-device"),
HTTP_AUTHORIZATION=f"Bearer+agent {self.device_token.key}",
)
self.assertEqual(response.status_code, 200)
body = loads(response.content)
self.assertFalse(body["device_registered"])
self.assertEqual(body["users"], [])
@enterprise_test()
@reconcile_app("authentik_crypto")
def test_unregister_device(self):
self.connection.apple_signing_key = generate_id()
self.connection.apple_encryption_key = generate_id()
self.connection.apple_key_exchange_key = generate_id()
self.connection.apple_sign_key_id = generate_id()
self.connection.apple_enc_key_id = generate_id()
self.connection.save()
binding = AgentDeviceUserBinding.objects.create(
target=self.device,
user=self.user,
connector=self.connector,
order=0,
apple_secure_enclave_key=generate_id(),
apple_enclave_key_id=generate_id(),
)
DeviceAuthenticationToken.objects.create(
device=self.device,
device_token=self.device_token,
connector=self.connector,
user=self.user,
token=generate_id(),
)
response = self.client.delete(
reverse("authentik_api:psso-register-device"),
HTTP_AUTHORIZATION=f"Bearer+agent {self.device_token.key}",
)
self.assertEqual(response.status_code, 204)
self.connection.refresh_from_db()
self.assertEqual(self.connection.apple_signing_key, "")
self.assertEqual(self.connection.apple_encryption_key, "")
self.assertEqual(self.connection.apple_key_exchange_key, "")
self.assertEqual(self.connection.apple_sign_key_id, "")
self.assertEqual(self.connection.apple_enc_key_id, "")
binding.refresh_from_db()
self.assertEqual(binding.apple_secure_enclave_key, "")
self.assertEqual(binding.apple_enclave_key_id, "")
self.assertFalse(DeviceAuthenticationToken.objects.filter(device=self.device).exists())
# The device itself stays enrolled, only Platform SSO state is cleared
self.assertTrue(DeviceToken.objects.filter(pk=self.device_token.pk).exists())
@@ -1,13 +1,11 @@
from django.db import transaction
from django.urls import reverse
from drf_spectacular.utils import extend_schema
from rest_framework.exceptions import ValidationError
from rest_framework.fields import BooleanField, CharField
from rest_framework.fields import CharField
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from structlog.stdlib import get_logger
from authentik.api.validation import validate
from authentik.core.api.users import UserSelfSerializer
@@ -16,22 +14,10 @@ from authentik.endpoints.connectors.agent.auth import AgentAuth
from authentik.endpoints.connectors.agent.models import (
AgentDeviceConnection,
AgentDeviceUserBinding,
AppleUnlockKey,
DeviceAuthenticationToken,
DeviceToken,
)
from authentik.enterprise.api import EnterpriseRequiredMixin
from authentik.events.models import Event, EventAction
from authentik.events.utils import model_to_dict
LOGGER = get_logger()
class AgentPSSODeviceStateUser(PassiveSerializer):
"""A user currently registered for Platform SSO on this device"""
username = CharField()
enclave_key_id = CharField()
class RegisterDeviceView(APIView):
@@ -55,75 +41,12 @@ class RegisterDeviceView(APIView):
nonce_endpoint = CharField()
authorization_endpoint = CharField()
class AgentPSSODeviceState(PassiveSerializer):
"""What authentik currently has stored for this device's Platform SSO
registration, so the client can detect drift and repair it"""
device_registered = BooleanField()
sign_key_id = CharField(allow_blank=True)
enc_key_id = CharField(allow_blank=True)
users = AgentPSSODeviceStateUser(many=True)
permission_classes = [IsAuthenticated]
pagination_class = None
filter_backends = []
serializer_class = AgentPSSODeviceRegistration
authentication_classes = [AgentAuth]
@extend_schema(
responses={
200: AgentPSSODeviceState(),
}
)
def get(self, request: Request) -> Response:
device_token: DeviceToken = request.auth
conn: AgentDeviceConnection = device_token.device
users = AgentDeviceUserBinding.objects.filter(
target=conn.device, connector=conn.connector
).select_related("user")
return Response(
data={
"device_registered": bool(conn.apple_signing_key),
"sign_key_id": conn.apple_sign_key_id,
"enc_key_id": conn.apple_enc_key_id,
"users": [
{
"username": binding.user.username,
"enclave_key_id": binding.apple_enclave_key_id,
}
for binding in users
],
}
)
@extend_schema(responses={204: None})
@transaction.atomic()
def delete(self, request: Request) -> Response:
"""Clear this device's Platform SSO registration, used when the configuration
profile is removed from the device. The device stays enrolled otherwise."""
device_token: DeviceToken = request.auth
conn: AgentDeviceConnection = device_token.device
conn.apple_signing_key = ""
conn.apple_encryption_key = ""
conn.apple_key_exchange_key = ""
conn.apple_sign_key_id = ""
conn.apple_enc_key_id = ""
conn.save()
bindings = AgentDeviceUserBinding.objects.filter(
target=conn.device, connector=conn.connector
)
# Unlock keys hang off the bindings and are useless without the enclave key
AppleUnlockKey.objects.filter(device_user__in=bindings).delete()
bindings.update(apple_secure_enclave_key="", apple_enclave_key_id="")
DeviceAuthenticationToken.objects.filter(device=conn.device).delete()
LOGGER.info("Cleared Platform SSO registration", device=conn.device.name)
Event.new(
EventAction.MODEL_UPDATED,
model=model_to_dict(conn),
message="Platform SSO registration removed",
).from_http(request)
return Response(status=204)
@extend_schema(
responses={
200: AgentPSSODeviceRegistrationResponse(),
@@ -2,6 +2,7 @@ from json import dumps, loads
from django.http import HttpRequest, HttpResponseRedirect
from django.urls import reverse
from googleapiclient.discovery import build
from authentik.endpoints.controller import BaseController, Capabilities
from authentik.endpoints.facts import DeviceFacts, OSFamily
@@ -27,8 +28,6 @@ class GoogleChromeController(BaseController[GoogleChromeConnector]):
def __init__(self, connector):
super().__init__(connector)
from googleapiclient.discovery import build
self.google_client = build(
"verifiedaccess",
"v2",
@@ -5,6 +5,8 @@ from typing import TYPE_CHECKING
from django.db import models
from django.templatetags.static import static
from django.utils.translation import gettext_lazy as _
from google.auth.exceptions import GoogleAuthError
from google.oauth2.service_account import Credentials
from rest_framework.serializers import BaseSerializer
from authentik.endpoints.controller import ConnectorSyncException
@@ -23,9 +25,6 @@ class GoogleChromeConnector(Connector):
credentials = models.JSONField()
def google_credentials(self):
from google.auth.exceptions import GoogleAuthError
from google.oauth2.service_account import Credentials
try:
return {
"credentials": Credentials.from_service_account_info(
@@ -37,7 +36,7 @@ class GoogleChromeConnector(Connector):
@property
def icon_url(self):
return static("authentik/sources/google/light.svg")
return static("authentik/sources/google.svg")
@property
def serializer(self) -> type[BaseSerializer]:
-3
View File
@@ -35,7 +35,6 @@ from authentik.enterprise.models import (
LicenseUsage,
LicenseUsageStatus,
)
from authentik.root.cache import in_memory_cache
from authentik.root.install_id import get_install_id
CACHE_KEY_ENTERPRISE_LICENSE = "goauthentik.io/enterprise/license"
@@ -241,8 +240,6 @@ class LicenseKey:
return summary
@staticmethod
# Checked on every request and audited model save, so don't go to the cache each time
@in_memory_cache(key=lambda: None, timeout=30)
def cached_summary() -> LicenseSummary:
"""Helper method which looks up the last summary"""
summary = cache.get(CACHE_KEY_ENTERPRISE_LICENSE)
@@ -4,7 +4,7 @@ from django.db import models, transaction
from django.db.models import Q
from django.http import HttpRequest
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _
from rest_framework.serializers import BaseSerializer
from authentik.lib.models import SerializerModel
@@ -412,10 +412,7 @@ class TestOffboardingAPI(APITestCase):
},
)
self.assertEqual(response.status_code, 400)
self.assertJSONEqual(
response.content,
{"non_field_errors": ["The fields user must make a unique set."]},
)
self.assertIn("user", response.data)
def test_duplicate_pending_race_returns_400(self):
"""If two requests race past validation, the DB constraint yields a 400, not a 500."""
@@ -436,10 +433,8 @@ class TestOffboardingAPI(APITestCase):
},
)
self.assertEqual(response.status_code, 400)
self.assertJSONEqual(
response.content,
{"non_field_errors": ["The fields user must make a unique set."]},
) # The losing insert did not create a second pending row.
self.assertIn("user", response.data)
# The losing insert did not create a second pending row.
self.assertEqual(
UserOffboarding.objects.filter(
user=self.user, status=OffboardingStatus.PENDING
@@ -30,4 +30,4 @@ class ReviewViewSet(EnterpriseRequiredMixin, CreateModelMixin, GenericViewSet):
def perform_create(self, serializer: ReviewSerializer) -> None:
review = serializer.save(reviewer=self.request.user)
review.iteration.on_review(review, self.request)
review.iteration.on_review(self.request)
@@ -9,7 +9,7 @@ from django.db.models.fields import Field
from django.db.models.functions import Cast
from django.http import HttpRequest
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext as _
from rest_framework.serializers import BaseSerializer
from authentik.blueprints.models import ManagedModel
@@ -270,7 +270,7 @@ class LifecycleIteration(SerializerModel, ManagedModel):
return {
"target": self.object,
"hyperlink": link_for_model(self.object),
"hyperlink_label": _("Go to {model_name}").format(model_name=self._get_model_name()),
"hyperlink_label": _(f"Go to {self._get_model_name()}"),
"lifecycle_iteration": self.id,
}
@@ -283,9 +283,7 @@ class LifecycleIteration(SerializerModel, ManagedModel):
object_label = str(self.object)
event = Event.new(
EventAction.REVIEW_INITIATED,
message=_("Access review is due for {model_name} {object_label}").format(
model_name=self.content_type.name.lower(), object_label=object_label
),
message=_(f"Access review is due for {self.content_type.name.lower()} {object_label}"),
**self._get_event_args(),
)
event.save()
@@ -296,9 +294,7 @@ class LifecycleIteration(SerializerModel, ManagedModel):
event = Event.new(
EventAction.REVIEW_OVERDUE,
message=_("Access review is overdue for {model_name} {object_label}").format(
model_name=self.content_type.name, object_label=str(self.object)
),
message=_(f"Access review is overdue for {self.content_type.name} {str(self.object)}"),
**self._get_event_args(),
)
event.save()
@@ -317,26 +313,16 @@ class LifecycleIteration(SerializerModel, ManagedModel):
self.state = ReviewState.REVIEWED
event = Event.new(
EventAction.REVIEW_COMPLETED,
message=_("Access review completed for {model_name} {object_label}").format(
model_name=self.content_type.name, object_label=str(self.object)
),
message=_(f"Access review completed for {self.content_type.name} {str(self.object)}"),
**self._get_event_args(),
).from_http(request)
event.save()
self.rule.notify_reviewers(event, NotificationSeverity.NOTICE)
self.save()
def on_review(self, review: Review, request: HttpRequest):
def on_review(self, request: HttpRequest):
if self.state not in (ReviewState.PENDING, ReviewState.OVERDUE):
raise AssertionError("Review is not pending or overdue")
Event.new(
EventAction.REVIEW_ATTESTED,
message=_("Access review attested for {model_name} {object_label}").format(
model_name=self.content_type.name, object_label=str(self.object)
),
note=review.note,
**self._get_event_args(),
).from_http(request, review.reviewer)
if self.rule.is_satisfied_for_iteration(self):
self.make_reviewed(request)
@@ -11,7 +11,6 @@ from authentik.enterprise.lifecycle.review.models import (
ReviewState,
)
from authentik.enterprise.tests import enterprise_test
from authentik.events.models import Event, EventAction
from authentik.lib.generators import generate_id
@@ -326,13 +325,6 @@ class TestReviewAPI(APITestCase):
self.assertEqual(response.data["iteration"], iteration.pk)
self.assertEqual(response.data["note"], "Reviewed and approved")
self.assertEqual(response.data["reviewer"]["pk"], self.user.pk)
event = Event.objects.get(
action=EventAction.REVIEW_ATTESTED,
context__lifecycle_iteration=iteration.pk.hex,
)
self.assertEqual(event.user["pk"], self.user.pk)
self.assertEqual(event.context["note"], "Reviewed and approved")
self.assertEqual(event.context["target"]["pk"], self.app.pk.hex)
def test_create_review_completes_iteration(self):
rule = LifecycleRule.objects.create(
@@ -102,25 +102,16 @@ class TestLifecycleModels(TestCase):
)
request = self._get_request()
review = Review.objects.create(iteration=iteration, reviewer=reviewer_one)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=reviewer_one)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.PENDING)
review = Review.objects.create(iteration=iteration, reviewer=reviewer_two)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=reviewer_two)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
self.assertTrue(Event.objects.filter(action=EventAction.REVIEW_COMPLETED).exists())
self.assertEqual(
set(
Event.objects.filter(
action=EventAction.REVIEW_ATTESTED,
context__lifecycle_iteration=iteration.pk.hex,
).values_list("user__pk", flat=True)
),
{reviewer_one.pk, reviewer_two.pk},
)
def test_review_min_reviewers_from_groups(self):
"""Group-based reviews complete once the minimum number of reviewers review."""
@@ -140,13 +131,13 @@ class TestLifecycleModels(TestCase):
)
request = self._get_request()
review = Review.objects.create(iteration=iteration, reviewer=reviewer_one)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=reviewer_one)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.PENDING)
review = Review.objects.create(iteration=iteration, reviewer=reviewer_two)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=reviewer_two)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
@@ -171,14 +162,14 @@ class TestLifecycleModels(TestCase):
request = self._get_request()
# Only group member reviews - not satisfied (explicit reviewer missing)
review = Review.objects.create(iteration=iteration, reviewer=group_member)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=group_member)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.PENDING)
# Explicit reviewer reviews - now satisfied
review = Review.objects.create(iteration=iteration, reviewer=explicit_reviewer)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=explicit_reviewer)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
@@ -202,14 +193,14 @@ class TestLifecycleModels(TestCase):
request = self._get_request()
# Only member from group_one reviews - not satisfied (need member from each group)
review = Review.objects.create(iteration=iteration, reviewer=member_group_one)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=member_group_one)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.PENDING)
# Member from group_two reviews - now satisfied
review = Review.objects.create(iteration=iteration, reviewer=member_group_two)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=member_group_two)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
@@ -236,8 +227,8 @@ class TestLifecycleModels(TestCase):
# Child group member should be able to review
self.assertTrue(iteration.user_can_review(child_member))
review = Review.objects.create(iteration=iteration, reviewer=child_member)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=child_member)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
@@ -269,13 +260,13 @@ class TestLifecycleModels(TestCase):
self.assertTrue(iteration.user_can_review(parent_member))
self.assertTrue(iteration.user_can_review(child_member))
review = Review.objects.create(iteration=iteration, reviewer=parent_member)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=parent_member)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.PENDING)
review = Review.objects.create(iteration=iteration, reviewer=child_member)
iteration.on_review(review, request)
Review.objects.create(iteration=iteration, reviewer=child_member)
iteration.on_review(request)
iteration.refresh_from_db()
self.assertEqual(iteration.state, ReviewState.REVIEWED)
@@ -703,8 +694,8 @@ class TestLifecycleModels(TestCase):
request = self._get_request()
# Review only rule_one's iteration
review = Review.objects.create(iteration=iter_one, reviewer=reviewer)
iter_one.on_review(review, request)
Review.objects.create(iteration=iter_one, reviewer=reviewer)
iter_one.on_review(request)
iter_one.refresh_from_db()
iter_two.refresh_from_db()
Loaded 100 of 1509 files, more files were not shown because too many files have changed in this diff. Show more