Compare commits
185 Commits
ci/push-to
...
root/move-
Author | SHA1 | Date | |
---|---|---|---|
e86a5cf5a7 | |||
7659afdd30 | |||
faab182404 | |||
90a85abf9d | |||
4d061e1af9 | |||
0720b3db3c | |||
236455fc45 | |||
ac08805d73 | |||
656beebd63 | |||
6430cdcd68 | |||
b8c97eb7c1 | |||
9eef9ee230 | |||
84cc2b4f11 | |||
e988799e12 | |||
7c71f9fcac | |||
1eeb85a4e7 | |||
4182ead0b9 | |||
dc45e8c08c | |||
d111740f6b | |||
4597ee45f8 | |||
735f48981d | |||
f35457492b | |||
af9ba83529 | |||
3c6cb9dbad | |||
1d63359077 | |||
33121d86f2 | |||
0c235909a2 | |||
91ef8c2c8d | |||
4ee45bb5cc | |||
b4ae3ba390 | |||
f3834016dc | |||
661a966e23 | |||
813273338e | |||
99639a9ed0 | |||
41aa36d06f | |||
62fc4c56e4 | |||
4514412010 | |||
463efac469 | |||
f4508659cf | |||
336f6f0dc2 | |||
c19a887356 | |||
09931bcbc2 | |||
7a4293bf17 | |||
6e569acd84 | |||
02c69d767f | |||
1863a9a12b | |||
b981bc5ba1 | |||
5da02971eb | |||
1f49ee77df | |||
baf8f18d54 | |||
5445b1235a | |||
2893a54ffb | |||
94eff50306 | |||
0befc26507 | |||
629d5df763 | |||
3098313981 | |||
c0a370bb2b | |||
a19d915d2b | |||
9a0dc50174 | |||
ac0a708f92 | |||
0ffaf0393e | |||
9bb3aa0374 | |||
f6a32dc6e5 | |||
af83fc7245 | |||
84de15568a | |||
29f8a82b49 | |||
cd05c0ec19 | |||
c19a1b373a | |||
31b9cbfb85 | |||
c0fe0dab61 | |||
1bd42345b9 | |||
90e7545d57 | |||
78d42c391d | |||
2ad831adb0 | |||
5eaa94917b | |||
6c0d462410 | |||
9dc2c26ba9 | |||
774a84f9e6 | |||
56015d883b | |||
9d15fa4a57 | |||
bb7338f5c1 | |||
f949141d03 | |||
646d133c30 | |||
3ee3adc509 | |||
1b4fee2bac | |||
10c358401d | |||
9dddbd2f0c | |||
078d643c20 | |||
733b7cf139 | |||
f83fab214b | |||
9ce460a0ac | |||
e69a380a39 | |||
2d89f42c68 | |||
3d4d167542 | |||
ee8d3c5146 | |||
0406b0d95a | |||
44d49bb14c | |||
afb1686be7 | |||
6b1802697d | |||
943fd6b78b | |||
ed33d314cd | |||
d343ccc539 | |||
31e8fb7c8c | |||
23faa0b839 | |||
3cbfd836ac | |||
10ab6e4327 | |||
561d2220bc | |||
e6c47db9f8 | |||
5f5171c472 | |||
bdf4236973 | |||
a61a41d7d0 | |||
c7532d35f2 | |||
27baedfea4 | |||
e3011eab9a | |||
9635dd98f3 | |||
bd0d7edbc4 | |||
9b05418306 | |||
d4e15f0f39 | |||
ec9c2266eb | |||
5ebd280087 | |||
1cc8d80600 | |||
3b70cd735e | |||
42766e13da | |||
8938fa5a7e | |||
4c8f610cdb | |||
8690200cd8 | |||
91145b7929 | |||
d255e53756 | |||
d51e6a5551 | |||
5433839ea0 | |||
863a7e6095 | |||
50db80428c | |||
ffd5234396 | |||
95890638a5 | |||
f7d2a68b1d | |||
83ecb64f33 | |||
40b0f7df8d | |||
ee6fcdfbd8 | |||
94623615a6 | |||
aa4f817856 | |||
c3aefd55a2 | |||
1298cdc338 | |||
3eaaa35a4c | |||
d17f781d11 | |||
c82b79f10f | |||
0aa7be6e2c | |||
9811ec57df | |||
393e5f236c | |||
59ae9c6148 | |||
fd8e20bdeb | |||
737aced000 | |||
dc3559c7e9 | |||
02bd699917 | |||
5fccbd7c04 | |||
6fc92bd50c | |||
687f6d683a | |||
4a8329649c | |||
0c296efede | |||
112520fd88 | |||
ee648269f7 | |||
15be3f2461 | |||
ef9557c578 | |||
48700c0e9c | |||
18a48030a8 | |||
640d0a4a95 | |||
6b8782556c | |||
7f6f3b6602 | |||
3367ac0e08 | |||
d5ea0ffdc6 | |||
93f1638b39 | |||
37525175fa | |||
0db1e52f90 | |||
3e8620b686 | |||
6687ffc6d2 | |||
e265ee253b | |||
7763a3673c | |||
d99005e130 | |||
c61f96e770 | |||
83622dd934 | |||
2eebd0eaa1 | |||
b61d918c5c | |||
076a4f4772 | |||
b3872b35f8 | |||
f06534cdf0 | |||
c528a6c336 |
@ -1,16 +1,16 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 2024.10.5
|
current_version = 2024.12.2
|
||||||
tag = True
|
tag = True
|
||||||
commit = True
|
commit = True
|
||||||
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
|
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
|
||||||
serialize =
|
serialize =
|
||||||
{major}.{minor}.{patch}-{rc_t}{rc_n}
|
{major}.{minor}.{patch}-{rc_t}{rc_n}
|
||||||
{major}.{minor}.{patch}
|
{major}.{minor}.{patch}
|
||||||
message = release: {new_version}
|
message = release: {new_version}
|
||||||
tag_name = version/{new_version}
|
tag_name = version/{new_version}
|
||||||
|
|
||||||
[bumpversion:part:rc_t]
|
[bumpversion:part:rc_t]
|
||||||
values =
|
values =
|
||||||
rc
|
rc
|
||||||
final
|
final
|
||||||
optional_value = final
|
optional_value = final
|
||||||
@ -31,4 +31,4 @@ optional_value = final
|
|||||||
|
|
||||||
[bumpversion:file:web/src/common/constants.ts]
|
[bumpversion:file:web/src/common/constants.ts]
|
||||||
|
|
||||||
[bumpversion:file:website/docs/install-config/install/aws/template.yaml]
|
[bumpversion:file:lifecycle/aws/template.yaml]
|
||||||
|
@ -35,14 +35,6 @@ runs:
|
|||||||
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||||
```
|
```
|
||||||
|
|
||||||
For arm64, use these values:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
|
|
||||||
AUTHENTIK_TAG=${{ inputs.tag }}-arm64
|
|
||||||
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
|
||||||
```
|
|
||||||
|
|
||||||
Afterwards, run the upgrade commands from the latest release notes.
|
Afterwards, run the upgrade commands from the latest release notes.
|
||||||
</details>
|
</details>
|
||||||
<details>
|
<details>
|
||||||
@ -60,18 +52,6 @@ runs:
|
|||||||
tag: ${{ inputs.tag }}
|
tag: ${{ inputs.tag }}
|
||||||
```
|
```
|
||||||
|
|
||||||
For arm64, use these values:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
authentik:
|
|
||||||
outposts:
|
|
||||||
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
|
||||||
global:
|
|
||||||
image:
|
|
||||||
repository: ghcr.io/goauthentik/dev-server
|
|
||||||
tag: ${{ inputs.tag }}-arm64
|
|
||||||
```
|
|
||||||
|
|
||||||
Afterwards, run the upgrade commands from the latest release notes.
|
Afterwards, run the upgrade commands from the latest release notes.
|
||||||
</details>
|
</details>
|
||||||
edit-mode: replace
|
edit-mode: replace
|
||||||
|
@ -29,9 +29,15 @@ outputs:
|
|||||||
imageTags:
|
imageTags:
|
||||||
description: "Docker image tags"
|
description: "Docker image tags"
|
||||||
value: ${{ steps.ev.outputs.imageTags }}
|
value: ${{ steps.ev.outputs.imageTags }}
|
||||||
|
imageTagsJSON:
|
||||||
|
description: "Docker image tags, as a JSON array"
|
||||||
|
value: ${{ steps.ev.outputs.imageTagsJSON }}
|
||||||
attestImageNames:
|
attestImageNames:
|
||||||
description: "Docker image names used for attestation"
|
description: "Docker image names used for attestation"
|
||||||
value: ${{ steps.ev.outputs.attestImageNames }}
|
value: ${{ steps.ev.outputs.attestImageNames }}
|
||||||
|
cacheTo:
|
||||||
|
description: "cache-to value for the docker build step"
|
||||||
|
value: ${{ steps.ev.outputs.cacheTo }}
|
||||||
imageMainTag:
|
imageMainTag:
|
||||||
description: "Docker image main tag"
|
description: "Docker image main tag"
|
||||||
value: ${{ steps.ev.outputs.imageMainTag }}
|
value: ${{ steps.ev.outputs.imageMainTag }}
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import configparser
|
import configparser
|
||||||
import os
|
import os
|
||||||
|
from json import dumps
|
||||||
from time import time
|
from time import time
|
||||||
|
|
||||||
parser = configparser.ConfigParser()
|
parser = configparser.ConfigParser()
|
||||||
@ -48,7 +49,7 @@ if is_release:
|
|||||||
]
|
]
|
||||||
else:
|
else:
|
||||||
suffix = ""
|
suffix = ""
|
||||||
if image_arch and image_arch != "amd64":
|
if image_arch:
|
||||||
suffix = f"-{image_arch}"
|
suffix = f"-{image_arch}"
|
||||||
for name in image_names:
|
for name in image_names:
|
||||||
image_tags += [
|
image_tags += [
|
||||||
@ -70,12 +71,23 @@ def get_attest_image_names(image_with_tags: list[str]):
|
|||||||
return ",".join(set(image_tags))
|
return ",".join(set(image_tags))
|
||||||
|
|
||||||
|
|
||||||
|
# Generate `cache-to` param
|
||||||
|
cache_to = ""
|
||||||
|
if should_push:
|
||||||
|
_cache_tag = "buildcache"
|
||||||
|
if image_arch:
|
||||||
|
_cache_tag += f"-{image_arch}"
|
||||||
|
cache_to = f"type=registry,ref={get_attest_image_names(image_tags)}:{_cache_tag},mode=max"
|
||||||
|
|
||||||
|
|
||||||
with open(os.environ["GITHUB_OUTPUT"], "a+", encoding="utf-8") as _output:
|
with open(os.environ["GITHUB_OUTPUT"], "a+", encoding="utf-8") as _output:
|
||||||
print(f"shouldPush={str(should_push).lower()}", file=_output)
|
print(f"shouldPush={str(should_push).lower()}", file=_output)
|
||||||
print(f"sha={sha}", file=_output)
|
print(f"sha={sha}", file=_output)
|
||||||
print(f"version={version}", file=_output)
|
print(f"version={version}", file=_output)
|
||||||
print(f"prerelease={prerelease}", file=_output)
|
print(f"prerelease={prerelease}", file=_output)
|
||||||
print(f"imageTags={','.join(image_tags)}", file=_output)
|
print(f"imageTags={','.join(image_tags)}", file=_output)
|
||||||
|
print(f"imageTagsJSON={dumps(image_tags)}", file=_output)
|
||||||
print(f"attestImageNames={get_attest_image_names(image_tags)}", file=_output)
|
print(f"attestImageNames={get_attest_image_names(image_tags)}", file=_output)
|
||||||
print(f"imageMainTag={image_main_tag}", file=_output)
|
print(f"imageMainTag={image_main_tag}", file=_output)
|
||||||
print(f"imageMainName={image_tags[0]}", file=_output)
|
print(f"imageMainName={image_tags[0]}", file=_output)
|
||||||
|
print(f"cacheTo={cache_to}", file=_output)
|
||||||
|
11
.github/actions/docker-push-variables/test.sh
vendored
11
.github/actions/docker-push-variables/test.sh
vendored
@ -1,7 +1,18 @@
|
|||||||
#!/bin/bash -x
|
#!/bin/bash -x
|
||||||
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
|
||||||
|
# Non-pushing PR
|
||||||
GITHUB_OUTPUT=/dev/stdout \
|
GITHUB_OUTPUT=/dev/stdout \
|
||||||
GITHUB_REF=ref \
|
GITHUB_REF=ref \
|
||||||
GITHUB_SHA=sha \
|
GITHUB_SHA=sha \
|
||||||
IMAGE_NAME=ghcr.io/goauthentik/server,beryju/authentik \
|
IMAGE_NAME=ghcr.io/goauthentik/server,beryju/authentik \
|
||||||
|
GITHUB_REPOSITORY=goauthentik/authentik \
|
||||||
|
python $SCRIPT_DIR/push_vars.py
|
||||||
|
|
||||||
|
# Pushing PR/main
|
||||||
|
GITHUB_OUTPUT=/dev/stdout \
|
||||||
|
GITHUB_REF=ref \
|
||||||
|
GITHUB_SHA=sha \
|
||||||
|
IMAGE_NAME=ghcr.io/goauthentik/server,beryju/authentik \
|
||||||
|
GITHUB_REPOSITORY=goauthentik/authentik \
|
||||||
|
DOCKER_USERNAME=foo \
|
||||||
python $SCRIPT_DIR/push_vars.py
|
python $SCRIPT_DIR/push_vars.py
|
||||||
|
10
.github/dependabot.yml
vendored
10
.github/dependabot.yml
vendored
@ -82,6 +82,16 @@ updates:
|
|||||||
docusaurus:
|
docusaurus:
|
||||||
patterns:
|
patterns:
|
||||||
- "@docusaurus/*"
|
- "@docusaurus/*"
|
||||||
|
- package-ecosystem: npm
|
||||||
|
directory: "/lifecycle/aws"
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
time: "04:00"
|
||||||
|
open-pull-requests-limit: 10
|
||||||
|
commit-message:
|
||||||
|
prefix: "lifecycle/aws:"
|
||||||
|
labels:
|
||||||
|
- dependencies
|
||||||
- package-ecosystem: pip
|
- package-ecosystem: pip
|
||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
|
94
.github/workflows/_reusable-docker-build-single.yaml
vendored
Normal file
94
.github/workflows/_reusable-docker-build-single.yaml
vendored
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
# Re-usable workflow for a single-architecture build
|
||||||
|
name: Single-arch Container build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
image_name:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
image_arch:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
runs-on:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
registry_dockerhub:
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
registry_ghcr:
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
release:
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
outputs:
|
||||||
|
image-digest:
|
||||||
|
value: ${{ jobs.build.outputs.image-digest }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build ${{ inputs.image_arch }}
|
||||||
|
runs-on: ${{ inputs.runs-on }}
|
||||||
|
outputs:
|
||||||
|
image-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
permissions:
|
||||||
|
# Needed to upload container images to ghcr.io
|
||||||
|
packages: write
|
||||||
|
# Needed for attestation
|
||||||
|
id-token: write
|
||||||
|
attestations: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: docker/setup-qemu-action@v3.3.0
|
||||||
|
- uses: docker/setup-buildx-action@v3
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
with:
|
||||||
|
image-name: ${{ inputs.image_name }}
|
||||||
|
image-arch: ${{ inputs.image_arch }}
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
if: ${{ inputs.registry_dockerhub }}
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
if: ${{ inputs.registry_ghcr }}
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: make empty clients
|
||||||
|
if: ${{ inputs.release }}
|
||||||
|
run: |
|
||||||
|
mkdir -p ./gen-ts-api
|
||||||
|
mkdir -p ./gen-go-api
|
||||||
|
- name: generate ts client
|
||||||
|
if: ${{ !inputs.release }}
|
||||||
|
run: make gen-client-ts
|
||||||
|
- name: Build Docker Image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
id: push
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
secrets: |
|
||||||
|
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
|
||||||
|
GEOIPUPDATE_LICENSE_KEY=${{ secrets.GEOIPUPDATE_LICENSE_KEY }}
|
||||||
|
build-args: |
|
||||||
|
VERSION=${{ github.ref }}
|
||||||
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
|
platforms: linux/${{ inputs.image_arch }}
|
||||||
|
cache-from: type=registry,ref=${{ steps.ev.outputs.attestImageNames }}:buildcache-${{ inputs.image_arch }}
|
||||||
|
cache-to: ${{ steps.ev.outputs.cacheTo }}
|
||||||
|
- uses: actions/attest-build-provenance@v2
|
||||||
|
id: attest
|
||||||
|
with:
|
||||||
|
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
||||||
|
subject-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
push-to-registry: true
|
102
.github/workflows/_reusable-docker-build.yaml
vendored
Normal file
102
.github/workflows/_reusable-docker-build.yaml
vendored
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
# Re-usable workflow for a multi-architecture build
|
||||||
|
name: Multi-arch container build
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
image_name:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
registry_dockerhub:
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
registry_ghcr:
|
||||||
|
default: true
|
||||||
|
type: boolean
|
||||||
|
release:
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
outputs: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-server-amd64:
|
||||||
|
uses: ./.github/workflows/_reusable-docker-build-single.yaml
|
||||||
|
secrets: inherit
|
||||||
|
with:
|
||||||
|
image_name: ${{ inputs.image_name }}
|
||||||
|
image_arch: amd64
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
registry_dockerhub: ${{ inputs.registry_dockerhub }}
|
||||||
|
registry_ghcr: ${{ inputs.registry_ghcr }}
|
||||||
|
release: ${{ inputs.release }}
|
||||||
|
build-server-arm64:
|
||||||
|
uses: ./.github/workflows/_reusable-docker-build-single.yaml
|
||||||
|
secrets: inherit
|
||||||
|
with:
|
||||||
|
image_name: ${{ inputs.image_name }}
|
||||||
|
image_arch: arm64
|
||||||
|
runs-on: ubuntu-22.04-arm
|
||||||
|
registry_dockerhub: ${{ inputs.registry_dockerhub }}
|
||||||
|
registry_ghcr: ${{ inputs.registry_ghcr }}
|
||||||
|
release: ${{ inputs.release }}
|
||||||
|
get-tags:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs:
|
||||||
|
- build-server-amd64
|
||||||
|
- build-server-arm64
|
||||||
|
outputs:
|
||||||
|
tags: ${{ steps.ev.outputs.imageTagsJSON }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
with:
|
||||||
|
image-name: ${{ inputs.image_name }}
|
||||||
|
merge-server:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs:
|
||||||
|
- get-tags
|
||||||
|
- build-server-amd64
|
||||||
|
- build-server-arm64
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
tag: ${{ fromJson(needs.get-tags.outputs.tags) }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
with:
|
||||||
|
image-name: ${{ inputs.image_name }}
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
if: ${{ inputs.registry_dockerhub }}
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
if: ${{ inputs.registry_ghcr }}
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- uses: int128/docker-manifest-create-action@v2
|
||||||
|
id: build
|
||||||
|
with:
|
||||||
|
tags: ${{ matrix.tag }}
|
||||||
|
sources: |
|
||||||
|
${{ steps.ev.outputs.attestImageNames }}@${{ needs.build-server-amd64.outputs.image-digest }}
|
||||||
|
${{ steps.ev.outputs.attestImageNames }}@${{ needs.build-server-arm64.outputs.image-digest }}
|
||||||
|
- uses: actions/attest-build-provenance@v2
|
||||||
|
id: attest
|
||||||
|
with:
|
||||||
|
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
||||||
|
subject-digest: ${{ steps.build.outputs.digest }}
|
||||||
|
push-to-registry: true
|
6
.github/workflows/ci-aws-cfn.yml
vendored
6
.github/workflows/ci-aws-cfn.yml
vendored
@ -25,10 +25,10 @@ jobs:
|
|||||||
uses: ./.github/actions/setup
|
uses: ./.github/actions/setup
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version-file: website/package.json
|
node-version-file: lifecycle/aws/package.json
|
||||||
cache: "npm"
|
cache: "npm"
|
||||||
cache-dependency-path: website/package-lock.json
|
cache-dependency-path: lifecycle/aws/package-lock.json
|
||||||
- working-directory: website/
|
- working-directory: lifecycle/aws/
|
||||||
run: |
|
run: |
|
||||||
npm ci
|
npm ci
|
||||||
- name: Check changes have been applied
|
- name: Check changes have been applied
|
||||||
|
66
.github/workflows/ci-main.yml
vendored
66
.github/workflows/ci-main.yml
vendored
@ -134,7 +134,7 @@ jobs:
|
|||||||
- name: Setup authentik env
|
- name: Setup authentik env
|
||||||
uses: ./.github/actions/setup
|
uses: ./.github/actions/setup
|
||||||
- name: Create k8s Kind Cluster
|
- name: Create k8s Kind Cluster
|
||||||
uses: helm/kind-action@v1.11.0
|
uses: helm/kind-action@v1.12.0
|
||||||
- name: run integration
|
- name: run integration
|
||||||
run: |
|
run: |
|
||||||
poetry run coverage run manage.py test tests/integration
|
poetry run coverage run manage.py test tests/integration
|
||||||
@ -223,68 +223,18 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
jobs: ${{ toJSON(needs) }}
|
jobs: ${{ toJSON(needs) }}
|
||||||
build:
|
build:
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
arch:
|
|
||||||
- amd64
|
|
||||||
- arm64
|
|
||||||
needs: ci-core-mark
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
permissions:
|
||||||
# Needed to upload contianer images to ghcr.io
|
# Needed to upload container images to ghcr.io
|
||||||
packages: write
|
packages: write
|
||||||
# Needed for attestation
|
# Needed for attestation
|
||||||
id-token: write
|
id-token: write
|
||||||
attestations: write
|
attestations: write
|
||||||
timeout-minutes: 120
|
needs: ci-core-mark
|
||||||
steps:
|
uses: ./.github/workflows/_reusable-docker-build.yaml
|
||||||
- uses: actions/checkout@v4
|
secrets: inherit
|
||||||
with:
|
with:
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
image_name: ghcr.io/goauthentik/dev-server
|
||||||
- name: Set up QEMU
|
release: false
|
||||||
uses: docker/setup-qemu-action@v3.2.0
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
- name: prepare variables
|
|
||||||
uses: ./.github/actions/docker-push-variables
|
|
||||||
id: ev
|
|
||||||
env:
|
|
||||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
with:
|
|
||||||
image-name: ghcr.io/goauthentik/dev-server
|
|
||||||
image-arch: ${{ matrix.arch }}
|
|
||||||
- name: Login to Container Registry
|
|
||||||
if: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.repository_owner }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: generate ts client
|
|
||||||
run: make gen-client-ts
|
|
||||||
- name: Build Docker Image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
id: push
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
secrets: |
|
|
||||||
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
|
|
||||||
GEOIPUPDATE_LICENSE_KEY=${{ secrets.GEOIPUPDATE_LICENSE_KEY }}
|
|
||||||
tags: ${{ steps.ev.outputs.imageTags }}
|
|
||||||
push: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
|
||||||
build-args: |
|
|
||||||
GIT_BUILD_HASH=${{ steps.ev.outputs.sha }}
|
|
||||||
cache-from: type=registry,ref=ghcr.io/goauthentik/dev-server:buildcache
|
|
||||||
cache-to: ${{ steps.ev.outputs.shouldPush == 'true' && 'type=registry,ref=ghcr.io/goauthentik/dev-server:buildcache,mode=max' || '' }}
|
|
||||||
platforms: linux/${{ matrix.arch }}
|
|
||||||
- uses: actions/attest-build-provenance@v2
|
|
||||||
id: attest
|
|
||||||
if: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
|
||||||
with:
|
|
||||||
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
|
||||||
subject-digest: ${{ steps.push.outputs.digest }}
|
|
||||||
push-to-registry: true
|
|
||||||
pr-comment:
|
pr-comment:
|
||||||
needs:
|
needs:
|
||||||
- build
|
- build
|
||||||
|
4
.github/workflows/ci-outpost.yml
vendored
4
.github/workflows/ci-outpost.yml
vendored
@ -72,7 +72,7 @@ jobs:
|
|||||||
- rac
|
- rac
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
# Needed to upload contianer images to ghcr.io
|
# Needed to upload container images to ghcr.io
|
||||||
packages: write
|
packages: write
|
||||||
# Needed for attestation
|
# Needed for attestation
|
||||||
id-token: write
|
id-token: write
|
||||||
@ -82,7 +82,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
ref: ${{ github.event.pull_request.head.sha }}
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.2.0
|
uses: docker/setup-qemu-action@v3.3.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
|
67
.github/workflows/release-publish.yml
vendored
67
.github/workflows/release-publish.yml
vendored
@ -7,64 +7,15 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-server:
|
build-server:
|
||||||
runs-on: ubuntu-latest
|
uses: ./.github/workflows/_reusable-docker-build.yaml
|
||||||
permissions:
|
secrets: inherit
|
||||||
# Needed to upload contianer images to ghcr.io
|
with:
|
||||||
packages: write
|
image_name: ghcr.io/goauthentik/server,beryju/authentik
|
||||||
# Needed for attestation
|
release: true
|
||||||
id-token: write
|
|
||||||
attestations: write
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v3.2.0
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
- name: prepare variables
|
|
||||||
uses: ./.github/actions/docker-push-variables
|
|
||||||
id: ev
|
|
||||||
env:
|
|
||||||
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
with:
|
|
||||||
image-name: ghcr.io/goauthentik/server,beryju/authentik
|
|
||||||
- name: Docker Login Registry
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
- name: Login to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.repository_owner }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: make empty clients
|
|
||||||
run: |
|
|
||||||
mkdir -p ./gen-ts-api
|
|
||||||
mkdir -p ./gen-go-api
|
|
||||||
- name: Build Docker Image
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
id: push
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
push: true
|
|
||||||
secrets: |
|
|
||||||
GEOIPUPDATE_ACCOUNT_ID=${{ secrets.GEOIPUPDATE_ACCOUNT_ID }}
|
|
||||||
GEOIPUPDATE_LICENSE_KEY=${{ secrets.GEOIPUPDATE_LICENSE_KEY }}
|
|
||||||
build-args: |
|
|
||||||
VERSION=${{ github.ref }}
|
|
||||||
tags: ${{ steps.ev.outputs.imageTags }}
|
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
- uses: actions/attest-build-provenance@v2
|
|
||||||
id: attest
|
|
||||||
with:
|
|
||||||
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
|
||||||
subject-digest: ${{ steps.push.outputs.digest }}
|
|
||||||
push-to-registry: true
|
|
||||||
build-outpost:
|
build-outpost:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
# Needed to upload contianer images to ghcr.io
|
# Needed to upload container images to ghcr.io
|
||||||
packages: write
|
packages: write
|
||||||
# Needed for attestation
|
# Needed for attestation
|
||||||
id-token: write
|
id-token: write
|
||||||
@ -83,7 +34,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version-file: "go.mod"
|
go-version-file: "go.mod"
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v3.2.0
|
uses: docker/setup-qemu-action@v3.3.0
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: prepare variables
|
- name: prepare variables
|
||||||
@ -188,8 +139,8 @@ jobs:
|
|||||||
aws-region: ${{ env.AWS_REGION }}
|
aws-region: ${{ env.AWS_REGION }}
|
||||||
- name: Upload template
|
- name: Upload template
|
||||||
run: |
|
run: |
|
||||||
aws s3 cp website/docs/install-config/install/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ github.ref }}.yaml
|
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ github.ref }}.yaml
|
||||||
aws s3 cp website/docs/install-config/install/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.latest.yaml
|
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.latest.yaml
|
||||||
test-release:
|
test-release:
|
||||||
needs:
|
needs:
|
||||||
- build-server
|
- build-server
|
||||||
|
@ -15,6 +15,7 @@ go.mod @goauthentik/backend
|
|||||||
go.sum @goauthentik/backend
|
go.sum @goauthentik/backend
|
||||||
# Infrastructure
|
# Infrastructure
|
||||||
.github/ @goauthentik/infrastructure
|
.github/ @goauthentik/infrastructure
|
||||||
|
lifecycle/aws/ @goauthentik/infrastructure
|
||||||
Dockerfile @goauthentik/infrastructure
|
Dockerfile @goauthentik/infrastructure
|
||||||
*Dockerfile @goauthentik/infrastructure
|
*Dockerfile @goauthentik/infrastructure
|
||||||
.dockerignore @goauthentik/infrastructure
|
.dockerignore @goauthentik/infrastructure
|
||||||
|
64
Dockerfile
64
Dockerfile
@ -94,7 +94,7 @@ RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
|
|||||||
/bin/sh -c "/usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
/bin/sh -c "/usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
||||||
|
|
||||||
# Stage 5: Python dependencies
|
# Stage 5: Python dependencies
|
||||||
FROM ghcr.io/goauthentik/fips-python:3.12.7-slim-bookworm-fips-full AS python-deps
|
FROM ghcr.io/goauthentik/fips-python:3.12.7-slim-bookworm-fips AS python-deps
|
||||||
|
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
ARG TARGETVARIANT
|
ARG TARGETVARIANT
|
||||||
@ -116,15 +116,29 @@ RUN --mount=type=bind,target=./pyproject.toml,src=./pyproject.toml \
|
|||||||
--mount=type=bind,target=./poetry.lock,src=./poetry.lock \
|
--mount=type=bind,target=./poetry.lock,src=./poetry.lock \
|
||||||
--mount=type=cache,target=/root/.cache/pip \
|
--mount=type=cache,target=/root/.cache/pip \
|
||||||
--mount=type=cache,target=/root/.cache/pypoetry \
|
--mount=type=cache,target=/root/.cache/pypoetry \
|
||||||
|
pip install --no-cache cffi && \
|
||||||
|
apt-get update && \
|
||||||
|
apt-get install -y --no-install-recommends \
|
||||||
|
build-essential libffi-dev \
|
||||||
|
# Required for cryptography
|
||||||
|
curl pkg-config \
|
||||||
|
# Required for lxml
|
||||||
|
libxslt-dev zlib1g-dev \
|
||||||
|
# Required for xmlsec
|
||||||
|
libltdl-dev \
|
||||||
|
# Required for kadmin
|
||||||
|
sccache clang && \
|
||||||
|
curl https://sh.rustup.rs -sSf | sh -s -- -y && \
|
||||||
|
. "$HOME/.cargo/env" && \
|
||||||
python -m venv /ak-root/venv/ && \
|
python -m venv /ak-root/venv/ && \
|
||||||
bash -c "source ${VENV_PATH}/bin/activate && \
|
bash -c "source ${VENV_PATH}/bin/activate && \
|
||||||
pip3 install --upgrade pip && \
|
pip3 install --upgrade pip && \
|
||||||
pip3 install poetry && \
|
pip3 install poetry && \
|
||||||
poetry install --only=main --no-ansi --no-interaction --no-root && \
|
poetry config --local installer.no-binary cryptography,xmlsec,lxml,python-kadmin-rs && \
|
||||||
pip install --force-reinstall /wheels/*"
|
poetry install --only=main --no-ansi --no-interaction --no-root"
|
||||||
|
|
||||||
# Stage 6: Run
|
# Stage 6: Run
|
||||||
FROM ghcr.io/goauthentik/fips-python:3.12.7-slim-bookworm-fips-full AS final-image
|
FROM ghcr.io/goauthentik/fips-python:3.12.7-slim-bookworm-fips AS final-image
|
||||||
|
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
ARG GIT_BUILD_HASH
|
ARG GIT_BUILD_HASH
|
||||||
@ -136,37 +150,34 @@ LABEL org.opencontainers.image.source=https://github.com/goauthentik/authentik
|
|||||||
LABEL org.opencontainers.image.version=${VERSION}
|
LABEL org.opencontainers.image.version=${VERSION}
|
||||||
LABEL org.opencontainers.image.revision=${GIT_BUILD_HASH}
|
LABEL org.opencontainers.image.revision=${GIT_BUILD_HASH}
|
||||||
|
|
||||||
WORKDIR /
|
|
||||||
|
|
||||||
# We cannot cache this layer otherwise we'll end up with a bigger image
|
# We cannot cache this layer otherwise we'll end up with a bigger image
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
# Required for runtime
|
# Required for runtime
|
||||||
apt-get install -y --no-install-recommends libpq5 libmaxminddb0 ca-certificates libkrb5-3 libkadm5clnt-mit12 libkdb5-10 && \
|
apt-get install -y --no-install-recommends libpq5 libmaxminddb0 ca-certificates libkrb5-3 libkadm5clnt-mit12 libkdb5-10 libltdl7 libxslt1.1 && \
|
||||||
# Required for bootstrap & healtcheck
|
# Required for bootstrap & healtcheck
|
||||||
apt-get install -y --no-install-recommends runit && \
|
apt-get install -y --no-install-recommends runit && \
|
||||||
apt-get clean && \
|
apt-get clean && \
|
||||||
rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/ && \
|
rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/ && \
|
||||||
adduser --system --no-create-home --uid 1000 --group --home /authentik authentik && \
|
adduser --system --no-create-home --uid 1000 --group --home /ak-root authentik && \
|
||||||
mkdir -p /certs /media /blueprints && \
|
mkdir -p /certs /media /blueprints && \
|
||||||
mkdir -p /authentik/.ssh && \
|
mkdir -p /ak-root/authentik/.ssh && \
|
||||||
mkdir -p /ak-root && \
|
chown authentik:authentik /certs /media /ak-root/authentik/.ssh /ak-root
|
||||||
chown authentik:authentik /certs /media /authentik/.ssh /ak-root
|
|
||||||
|
|
||||||
COPY ./authentik/ /authentik
|
COPY ./authentik/ /ak-root/authentik
|
||||||
COPY ./pyproject.toml /
|
COPY ./pyproject.toml /ak-root
|
||||||
COPY ./poetry.lock /
|
COPY ./poetry.lock /ak-root
|
||||||
COPY ./schemas /schemas
|
COPY ./schemas /ak-root/schemas
|
||||||
COPY ./locale /locale
|
COPY ./locale /ak-root/locale
|
||||||
COPY ./tests /tests
|
COPY ./tests /ak-root/tests
|
||||||
COPY ./manage.py /
|
COPY ./manage.py /ak-root
|
||||||
COPY ./blueprints /blueprints
|
COPY ./blueprints /blueprints
|
||||||
COPY ./lifecycle/ /lifecycle
|
COPY ./lifecycle/ /ak-root/lifecycle
|
||||||
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
|
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
|
||||||
COPY --from=go-builder /go/authentik /bin/authentik
|
COPY --from=go-builder /go/authentik /bin/authentik
|
||||||
COPY --from=python-deps /ak-root/venv /ak-root/venv
|
COPY --from=python-deps /ak-root/venv /ak-root/venv
|
||||||
COPY --from=web-builder /work/web/dist/ /web/dist/
|
COPY --from=web-builder /work/web/dist/ /ak-root/web/dist/
|
||||||
COPY --from=web-builder /work/web/authentik/ /web/authentik/
|
COPY --from=web-builder /work/web/authentik/ /ak-root/web/authentik/
|
||||||
COPY --from=website-builder /work/website/build/ /website/help/
|
COPY --from=website-builder /work/website/build/ /ak-root/website/help/
|
||||||
COPY --from=geoip /usr/share/GeoIP /geoip
|
COPY --from=geoip /usr/share/GeoIP /geoip
|
||||||
|
|
||||||
USER 1000
|
USER 1000
|
||||||
@ -174,12 +185,13 @@ USER 1000
|
|||||||
ENV TMPDIR=/dev/shm/ \
|
ENV TMPDIR=/dev/shm/ \
|
||||||
PYTHONDONTWRITEBYTECODE=1 \
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
PYTHONUNBUFFERED=1 \
|
PYTHONUNBUFFERED=1 \
|
||||||
PATH="/ak-root/venv/bin:/lifecycle:$PATH" \
|
PATH="/ak-root/venv/bin:/ak-root/lifecycle:$PATH" \
|
||||||
VENV_PATH="/ak-root/venv" \
|
VENV_PATH="/ak-root/venv" \
|
||||||
POETRY_VIRTUALENVS_CREATE=false
|
POETRY_VIRTUALENVS_CREATE=false \
|
||||||
|
GOFIPS=1
|
||||||
ENV GOFIPS=1
|
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "ak", "healthcheck" ]
|
HEALTHCHECK --interval=30s --timeout=30s --start-period=60s --retries=3 CMD [ "ak", "healthcheck" ]
|
||||||
|
|
||||||
|
WORKDIR /ak-root
|
||||||
|
|
||||||
ENTRYPOINT [ "dumb-init", "--", "ak" ]
|
ENTRYPOINT [ "dumb-init", "--", "ak" ]
|
||||||
|
8
Makefile
8
Makefile
@ -5,7 +5,7 @@ PWD = $(shell pwd)
|
|||||||
UID = $(shell id -u)
|
UID = $(shell id -u)
|
||||||
GID = $(shell id -g)
|
GID = $(shell id -g)
|
||||||
NPM_VERSION = $(shell python -m scripts.npm_version)
|
NPM_VERSION = $(shell python -m scripts.npm_version)
|
||||||
PY_SOURCES = authentik tests scripts lifecycle .github website/docs/install-config/install/aws
|
PY_SOURCES = authentik tests scripts lifecycle .github
|
||||||
DOCKER_IMAGE ?= "authentik:test"
|
DOCKER_IMAGE ?= "authentik:test"
|
||||||
|
|
||||||
GEN_API_TS = "gen-ts-api"
|
GEN_API_TS = "gen-ts-api"
|
||||||
@ -78,6 +78,9 @@ migrate: ## Run the Authentik Django server's migrations
|
|||||||
|
|
||||||
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
|
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
|
||||||
|
|
||||||
|
aws-cfn:
|
||||||
|
cd lifecycle/aws && npm run aws-cfn
|
||||||
|
|
||||||
core-i18n-extract:
|
core-i18n-extract:
|
||||||
ak makemessages \
|
ak makemessages \
|
||||||
--add-location file \
|
--add-location file \
|
||||||
@ -252,9 +255,6 @@ website-build:
|
|||||||
website-watch: ## Build and watch the documentation website, updating automatically
|
website-watch: ## Build and watch the documentation website, updating automatically
|
||||||
cd website && npm run watch
|
cd website && npm run watch
|
||||||
|
|
||||||
aws-cfn:
|
|
||||||
cd website && npm run aws-cfn
|
|
||||||
|
|
||||||
#########################
|
#########################
|
||||||
## Docker
|
## Docker
|
||||||
#########################
|
#########################
|
||||||
|
@ -20,8 +20,8 @@ Even if the issue is not a CVE, we still greatly appreciate your help in hardeni
|
|||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| --------- | --------- |
|
| --------- | --------- |
|
||||||
| 2024.8.x | ✅ |
|
|
||||||
| 2024.10.x | ✅ |
|
| 2024.10.x | ✅ |
|
||||||
|
| 2024.12.x | ✅ |
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from os import environ
|
from os import environ
|
||||||
|
|
||||||
__version__ = "2024.10.5"
|
__version__ = "2024.12.2"
|
||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||||
|
|
||||||
|
|
||||||
@ -16,5 +16,5 @@ def get_full_version() -> str:
|
|||||||
"""Get full version, with build hash appended"""
|
"""Get full version, with build hash appended"""
|
||||||
version = __version__
|
version = __version__
|
||||||
if (build_hash := get_build_hash()) != "":
|
if (build_hash := get_build_hash()) != "":
|
||||||
version += "." + build_hash
|
return f"{version}+{build_hash}"
|
||||||
return version
|
return version
|
||||||
|
@ -7,7 +7,9 @@ from sys import version as python_version
|
|||||||
from typing import TypedDict
|
from typing import TypedDict
|
||||||
|
|
||||||
from cryptography.hazmat.backends.openssl.backend import backend
|
from cryptography.hazmat.backends.openssl.backend import backend
|
||||||
|
from django.conf import settings
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
|
from django.views.debug import SafeExceptionReporterFilter
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from rest_framework.fields import SerializerMethodField
|
from rest_framework.fields import SerializerMethodField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
@ -52,10 +54,16 @@ class SystemInfoSerializer(PassiveSerializer):
|
|||||||
def get_http_headers(self, request: Request) -> dict[str, str]:
|
def get_http_headers(self, request: Request) -> dict[str, str]:
|
||||||
"""Get HTTP Request headers"""
|
"""Get HTTP Request headers"""
|
||||||
headers = {}
|
headers = {}
|
||||||
|
raw_session = request._request.COOKIES.get(settings.SESSION_COOKIE_NAME)
|
||||||
for key, value in request.META.items():
|
for key, value in request.META.items():
|
||||||
if not isinstance(value, str):
|
if not isinstance(value, str):
|
||||||
continue
|
continue
|
||||||
headers[key] = value
|
actual_value = value
|
||||||
|
if raw_session in actual_value:
|
||||||
|
actual_value = actual_value.replace(
|
||||||
|
raw_session, SafeExceptionReporterFilter.cleansed_substitute
|
||||||
|
)
|
||||||
|
headers[key] = actual_value
|
||||||
return headers
|
return headers
|
||||||
|
|
||||||
def get_http_host(self, request: Request) -> str:
|
def get_http_host(self, request: Request) -> str:
|
||||||
|
@ -1,12 +1,16 @@
|
|||||||
"""authentik administration overview"""
|
"""authentik administration overview"""
|
||||||
|
|
||||||
|
from socket import gethostname
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from drf_spectacular.utils import extend_schema, inline_serializer
|
from drf_spectacular.utils import extend_schema, inline_serializer
|
||||||
from rest_framework.fields import IntegerField
|
from packaging.version import parse
|
||||||
|
from rest_framework.fields import BooleanField, CharField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
|
from authentik import get_full_version
|
||||||
from authentik.rbac.permissions import HasPermission
|
from authentik.rbac.permissions import HasPermission
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
@ -16,11 +20,38 @@ class WorkerView(APIView):
|
|||||||
|
|
||||||
permission_classes = [HasPermission("authentik_rbac.view_system_info")]
|
permission_classes = [HasPermission("authentik_rbac.view_system_info")]
|
||||||
|
|
||||||
@extend_schema(responses=inline_serializer("Workers", fields={"count": IntegerField()}))
|
@extend_schema(
|
||||||
|
responses=inline_serializer(
|
||||||
|
"Worker",
|
||||||
|
fields={
|
||||||
|
"worker_id": CharField(),
|
||||||
|
"version": CharField(),
|
||||||
|
"version_matching": BooleanField(),
|
||||||
|
},
|
||||||
|
many=True,
|
||||||
|
)
|
||||||
|
)
|
||||||
def get(self, request: Request) -> Response:
|
def get(self, request: Request) -> Response:
|
||||||
"""Get currently connected worker count."""
|
"""Get currently connected worker count."""
|
||||||
count = len(CELERY_APP.control.ping(timeout=0.5))
|
raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
|
||||||
|
our_version = parse(get_full_version())
|
||||||
|
response = []
|
||||||
|
for worker in raw:
|
||||||
|
key = list(worker.keys())[0]
|
||||||
|
version = worker[key].get("version")
|
||||||
|
version_matching = False
|
||||||
|
if version:
|
||||||
|
version_matching = parse(version) == our_version
|
||||||
|
response.append(
|
||||||
|
{"worker_id": key, "version": version, "version_matching": version_matching}
|
||||||
|
)
|
||||||
# In debug we run with `task_always_eager`, so tasks are ran on the main process
|
# In debug we run with `task_always_eager`, so tasks are ran on the main process
|
||||||
if settings.DEBUG: # pragma: no cover
|
if settings.DEBUG: # pragma: no cover
|
||||||
count += 1
|
response.append(
|
||||||
return Response({"count": count})
|
{
|
||||||
|
"worker_id": f"authentik-debug@{gethostname()}",
|
||||||
|
"version": get_full_version(),
|
||||||
|
"version_matching": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return Response(response)
|
||||||
|
@ -1,11 +1,10 @@
|
|||||||
"""authentik admin app config"""
|
"""authentik admin app config"""
|
||||||
|
|
||||||
from prometheus_client import Gauge, Info
|
from prometheus_client import Info
|
||||||
|
|
||||||
from authentik.blueprints.apps import ManagedAppConfig
|
from authentik.blueprints.apps import ManagedAppConfig
|
||||||
|
|
||||||
PROM_INFO = Info("authentik_version", "Currently running authentik version")
|
PROM_INFO = Info("authentik_version", "Currently running authentik version")
|
||||||
GAUGE_WORKERS = Gauge("authentik_admin_workers", "Currently connected workers")
|
|
||||||
|
|
||||||
|
|
||||||
class AuthentikAdminConfig(ManagedAppConfig):
|
class AuthentikAdminConfig(ManagedAppConfig):
|
||||||
|
@ -1,14 +1,35 @@
|
|||||||
"""admin signals"""
|
"""admin signals"""
|
||||||
|
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
|
from packaging.version import parse
|
||||||
|
from prometheus_client import Gauge
|
||||||
|
|
||||||
from authentik.admin.apps import GAUGE_WORKERS
|
from authentik import get_full_version
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
from authentik.root.monitoring import monitoring_set
|
from authentik.root.monitoring import monitoring_set
|
||||||
|
|
||||||
|
GAUGE_WORKERS = Gauge(
|
||||||
|
"authentik_admin_workers",
|
||||||
|
"Currently connected workers, their versions and if they are the same version as authentik",
|
||||||
|
["version", "version_matched"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_version = parse(get_full_version())
|
||||||
|
|
||||||
|
|
||||||
@receiver(monitoring_set)
|
@receiver(monitoring_set)
|
||||||
def monitoring_set_workers(sender, **kwargs):
|
def monitoring_set_workers(sender, **kwargs):
|
||||||
"""Set worker gauge"""
|
"""Set worker gauge"""
|
||||||
count = len(CELERY_APP.control.ping(timeout=0.5))
|
raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
|
||||||
GAUGE_WORKERS.set(count)
|
worker_version_count = {}
|
||||||
|
for worker in raw:
|
||||||
|
key = list(worker.keys())[0]
|
||||||
|
version = worker[key].get("version")
|
||||||
|
version_matching = False
|
||||||
|
if version:
|
||||||
|
version_matching = parse(version) == _version
|
||||||
|
worker_version_count.setdefault(version, {"count": 0, "matching": version_matching})
|
||||||
|
worker_version_count[version]["count"] += 1
|
||||||
|
for version, stats in worker_version_count.items():
|
||||||
|
GAUGE_WORKERS.labels(version, stats["matching"]).set(stats["count"])
|
||||||
|
@ -34,7 +34,7 @@ class TestAdminAPI(TestCase):
|
|||||||
response = self.client.get(reverse("authentik_api:admin_workers"))
|
response = self.client.get(reverse("authentik_api:admin_workers"))
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
body = loads(response.content)
|
body = loads(response.content)
|
||||||
self.assertEqual(body["count"], 0)
|
self.assertEqual(len(body), 0)
|
||||||
|
|
||||||
def test_metrics(self):
|
def test_metrics(self):
|
||||||
"""Test metrics API"""
|
"""Test metrics API"""
|
||||||
|
@ -1,67 +0,0 @@
|
|||||||
"""API Authorization"""
|
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db.models import Model
|
|
||||||
from django.db.models.query import QuerySet
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from rest_framework.authentication import get_authorization_header
|
|
||||||
from rest_framework.filters import BaseFilterBackend
|
|
||||||
from rest_framework.permissions import BasePermission
|
|
||||||
from rest_framework.request import Request
|
|
||||||
|
|
||||||
from authentik.api.authentication import validate_auth
|
|
||||||
from authentik.rbac.filters import ObjectFilter
|
|
||||||
|
|
||||||
|
|
||||||
class OwnerFilter(BaseFilterBackend):
|
|
||||||
"""Filter objects by their owner"""
|
|
||||||
|
|
||||||
owner_key = "user"
|
|
||||||
|
|
||||||
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
|
||||||
if request.user.is_superuser:
|
|
||||||
return queryset
|
|
||||||
return queryset.filter(**{self.owner_key: request.user})
|
|
||||||
|
|
||||||
|
|
||||||
class SecretKeyFilter(DjangoFilterBackend):
|
|
||||||
"""Allow access to all objects when authenticated with secret key as token.
|
|
||||||
|
|
||||||
Replaces both DjangoFilterBackend and ObjectFilter"""
|
|
||||||
|
|
||||||
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
|
||||||
auth_header = get_authorization_header(request)
|
|
||||||
token = validate_auth(auth_header)
|
|
||||||
if token and token == settings.SECRET_KEY:
|
|
||||||
return queryset
|
|
||||||
queryset = ObjectFilter().filter_queryset(request, queryset, view)
|
|
||||||
return super().filter_queryset(request, queryset, view)
|
|
||||||
|
|
||||||
|
|
||||||
class OwnerPermissions(BasePermission):
|
|
||||||
"""Authorize requests by an object's owner matching the requesting user"""
|
|
||||||
|
|
||||||
owner_key = "user"
|
|
||||||
|
|
||||||
def has_permission(self, request: Request, view) -> bool:
|
|
||||||
"""If the user is authenticated, we allow all requests here. For listing, the
|
|
||||||
object-level permissions are done by the filter backend"""
|
|
||||||
return request.user.is_authenticated
|
|
||||||
|
|
||||||
def has_object_permission(self, request: Request, view, obj: Model) -> bool:
|
|
||||||
"""Check if the object's owner matches the currently logged in user"""
|
|
||||||
if not hasattr(obj, self.owner_key):
|
|
||||||
return False
|
|
||||||
owner = getattr(obj, self.owner_key)
|
|
||||||
if owner != request.user:
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
class OwnerSuperuserPermissions(OwnerPermissions):
|
|
||||||
"""Similar to OwnerPermissions, except always allow access for superusers"""
|
|
||||||
|
|
||||||
def has_object_permission(self, request: Request, view, obj: Model) -> bool:
|
|
||||||
if request.user.is_superuser:
|
|
||||||
return True
|
|
||||||
return super().has_object_permission(request, view, obj)
|
|
68
authentik/blueprints/management/commands/blueprint_shell.py
Normal file
68
authentik/blueprints/management/commands/blueprint_shell.py
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
"""Test and debug Blueprints"""
|
||||||
|
|
||||||
|
import atexit
|
||||||
|
import readline
|
||||||
|
from pathlib import Path
|
||||||
|
from pprint import pformat
|
||||||
|
from sys import exit as sysexit
|
||||||
|
from textwrap import indent
|
||||||
|
|
||||||
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
from yaml import load
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
"""Test and debug Blueprints"""
|
||||||
|
|
||||||
|
lines = []
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
histfolder = Path("~").expanduser() / Path(".local/share/authentik")
|
||||||
|
histfolder.mkdir(parents=True, exist_ok=True)
|
||||||
|
histfile = histfolder / Path("blueprint_shell_history")
|
||||||
|
readline.parse_and_bind("tab: complete")
|
||||||
|
readline.parse_and_bind("set editing-mode vi")
|
||||||
|
|
||||||
|
try:
|
||||||
|
readline.read_history_file(str(histfile))
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
atexit.register(readline.write_history_file, str(histfile))
|
||||||
|
|
||||||
|
@no_translations
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
"""Interactively debug blueprint files"""
|
||||||
|
self.stdout.write(get_banner_text("Blueprint shell"))
|
||||||
|
self.stdout.write("Type '.eval' to evaluate previously entered statement(s).")
|
||||||
|
|
||||||
|
def do_eval():
|
||||||
|
yaml_input = "\n".join([line for line in self.lines if line])
|
||||||
|
data = load(yaml_input, BlueprintLoader)
|
||||||
|
self.stdout.write(pformat(data))
|
||||||
|
self.lines = []
|
||||||
|
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
line = input("> ")
|
||||||
|
if line == ".eval":
|
||||||
|
do_eval()
|
||||||
|
else:
|
||||||
|
self.lines.append(line)
|
||||||
|
except EntryInvalidError as exc:
|
||||||
|
self.stdout.write("Failed to evaluate expression:")
|
||||||
|
self.stdout.write(indent(exception_to_string(exc), prefix=" "))
|
||||||
|
except EOFError:
|
||||||
|
break
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
self.stdout.write()
|
||||||
|
sysexit(0)
|
||||||
|
self.stdout.write()
|
@ -126,7 +126,7 @@ class Command(BaseCommand):
|
|||||||
def_name_perm = f"model_{model_path}_permissions"
|
def_name_perm = f"model_{model_path}_permissions"
|
||||||
def_path_perm = f"#/$defs/{def_name_perm}"
|
def_path_perm = f"#/$defs/{def_name_perm}"
|
||||||
self.schema["$defs"][def_name_perm] = self.model_permissions(model)
|
self.schema["$defs"][def_name_perm] = self.model_permissions(model)
|
||||||
return {
|
template = {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["model", "identifiers"],
|
"required": ["model", "identifiers"],
|
||||||
"properties": {
|
"properties": {
|
||||||
@ -143,6 +143,11 @@ class Command(BaseCommand):
|
|||||||
"identifiers": {"$ref": def_path},
|
"identifiers": {"$ref": def_path},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
# Meta models don't require identifiers, as there's no matching database model to find
|
||||||
|
if issubclass(model, BaseMetaModel):
|
||||||
|
del template["properties"]["identifiers"]
|
||||||
|
template["required"].remove("identifiers")
|
||||||
|
return template
|
||||||
|
|
||||||
def field_to_jsonschema(self, field: Field) -> dict:
|
def field_to_jsonschema(self, field: Field) -> dict:
|
||||||
"""Convert a single field to json schema"""
|
"""Convert a single field to json schema"""
|
||||||
|
@ -202,6 +202,9 @@ class Blueprint:
|
|||||||
class YAMLTag:
|
class YAMLTag:
|
||||||
"""Base class for all YAML Tags"""
|
"""Base class for all YAML Tags"""
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return str(self.resolve(BlueprintEntry(""), Blueprint()))
|
||||||
|
|
||||||
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
"""Implement yaml tag logic"""
|
"""Implement yaml tag logic"""
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
@ -14,10 +14,10 @@ from rest_framework.response import Response
|
|||||||
from rest_framework.validators import UniqueValidator
|
from rest_framework.validators import UniqueValidator
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import SecretKeyFilter
|
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
|
from authentik.rbac.filters import SecretKeyFilter
|
||||||
from authentik.tenants.utils import get_current_tenant
|
from authentik.tenants.utils import get_current_tenant
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,15 +1,16 @@
|
|||||||
"""Application Roles API Viewset"""
|
"""Application Roles API Viewset"""
|
||||||
|
|
||||||
|
from django.http import HttpRequest
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.core.models import (
|
from authentik.core.models import (
|
||||||
Application,
|
Application,
|
||||||
ApplicationEntitlement,
|
ApplicationEntitlement,
|
||||||
User,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -18,7 +19,10 @@ class ApplicationEntitlementSerializer(ModelSerializer):
|
|||||||
|
|
||||||
def validate_app(self, app: Application) -> Application:
|
def validate_app(self, app: Application) -> Application:
|
||||||
"""Ensure user has permission to view"""
|
"""Ensure user has permission to view"""
|
||||||
user: User = self._context["request"].user
|
request: HttpRequest = self.context.get("request")
|
||||||
|
if not request and SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
|
return app
|
||||||
|
user = request.user
|
||||||
if user.has_perm("view_application", app) or user.has_perm(
|
if user.has_perm("view_application", app) or user.has_perm(
|
||||||
"authentik_core.view_application"
|
"authentik_core.view_application"
|
||||||
):
|
):
|
||||||
|
@ -2,16 +2,12 @@
|
|||||||
|
|
||||||
from typing import TypedDict
|
from typing import TypedDict
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from guardian.utils import get_anonymous_user
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.fields import SerializerMethodField
|
from rest_framework.fields import SerializerMethodField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
from ua_parser import user_agent_parser
|
from ua_parser import user_agent_parser
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerSuperuserPermissions
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.core.models import AuthenticatedSession
|
from authentik.core.models import AuthenticatedSession
|
||||||
@ -110,11 +106,4 @@ class AuthenticatedSessionViewSet(
|
|||||||
search_fields = ["user__username", "last_ip", "last_user_agent"]
|
search_fields = ["user__username", "last_ip", "last_user_agent"]
|
||||||
filterset_fields = ["user__username", "last_ip", "last_user_agent"]
|
filterset_fields = ["user__username", "last_ip", "last_user_agent"]
|
||||||
ordering = ["user__username"]
|
ordering = ["user__username"]
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
user = self.request.user if self.request else get_anonymous_user()
|
|
||||||
if user.is_superuser:
|
|
||||||
return super().get_queryset()
|
|
||||||
return super().get_queryset().filter(user=user.pk)
|
|
||||||
|
@ -2,19 +2,16 @@
|
|||||||
|
|
||||||
from collections.abc import Iterable
|
from collections.abc import Iterable
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import CharField, ReadOnlyField, SerializerMethodField
|
from rest_framework.fields import CharField, ReadOnlyField, SerializerMethodField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.parsers import MultiPartParser
|
from rest_framework.parsers import MultiPartParser
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.object_types import TypesMixin
|
from authentik.core.api.object_types import TypesMixin
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
@ -189,11 +186,10 @@ class UserSourceConnectionViewSet(
|
|||||||
|
|
||||||
queryset = UserSourceConnection.objects.all()
|
queryset = UserSourceConnection.objects.all()
|
||||||
serializer_class = UserSourceConnectionSerializer
|
serializer_class = UserSourceConnectionSerializer
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
|
||||||
filterset_fields = ["user", "source__slug"]
|
filterset_fields = ["user", "source__slug"]
|
||||||
search_fields = ["source__slug"]
|
search_fields = ["source__slug"]
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
ordering = ["source__slug", "pk"]
|
ordering = ["source__slug", "pk"]
|
||||||
|
owner_field = "user"
|
||||||
|
|
||||||
|
|
||||||
class GroupSourceConnectionSerializer(SourceSerializer):
|
class GroupSourceConnectionSerializer(SourceSerializer):
|
||||||
@ -228,8 +224,7 @@ class GroupSourceConnectionViewSet(
|
|||||||
|
|
||||||
queryset = GroupSourceConnection.objects.all()
|
queryset = GroupSourceConnection.objects.all()
|
||||||
serializer_class = GroupSourceConnectionSerializer
|
serializer_class = GroupSourceConnectionSerializer
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
|
||||||
filterset_fields = ["group", "source__slug"]
|
filterset_fields = ["group", "source__slug"]
|
||||||
search_fields = ["source__slug"]
|
search_fields = ["source__slug"]
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
ordering = ["source__slug", "pk"]
|
ordering = ["source__slug", "pk"]
|
||||||
|
owner_field = "user"
|
||||||
|
@ -3,18 +3,15 @@
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
||||||
from guardian.shortcuts import assign_perm, get_anonymous_user
|
from guardian.shortcuts import assign_perm, get_anonymous_user
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.fields import CharField
|
from rest_framework.fields import CharField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerSuperuserPermissions
|
|
||||||
from authentik.blueprints.api import ManagedSerializer
|
from authentik.blueprints.api import ManagedSerializer
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
@ -138,8 +135,8 @@ class TokenViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"managed",
|
"managed",
|
||||||
]
|
]
|
||||||
ordering = ["identifier", "expires"]
|
ordering = ["identifier", "expires"]
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
|
rbac_allow_create_without_perm = True
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
user = self.request.user if self.request else get_anonymous_user()
|
user = self.request.user if self.request else get_anonymous_user()
|
||||||
|
@ -427,7 +427,7 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
queryset = User.objects.none()
|
queryset = User.objects.none()
|
||||||
ordering = ["username"]
|
ordering = ["username"]
|
||||||
serializer_class = UserSerializer
|
serializer_class = UserSerializer
|
||||||
search_fields = ["username", "name", "is_active", "email", "uuid"]
|
search_fields = ["username", "name", "is_active", "email", "uuid", "attributes"]
|
||||||
filterset_class = UsersFilter
|
filterset_class = UsersFilter
|
||||||
|
|
||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
@ -585,7 +585,7 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"""Set password for user"""
|
"""Set password for user"""
|
||||||
user: User = self.get_object()
|
user: User = self.get_object()
|
||||||
try:
|
try:
|
||||||
user.set_password(request.data.get("password"))
|
user.set_password(request.data.get("password"), request=request)
|
||||||
user.save()
|
user.save()
|
||||||
except (ValidationError, IntegrityError) as exc:
|
except (ValidationError, IntegrityError) as exc:
|
||||||
LOGGER.debug("Failed to set password", exc=exc)
|
LOGGER.debug("Failed to set password", exc=exc)
|
||||||
|
@ -44,13 +44,12 @@ class TokenBackend(InbuiltBackend):
|
|||||||
self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any
|
self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any
|
||||||
) -> User | None:
|
) -> User | None:
|
||||||
try:
|
try:
|
||||||
|
|
||||||
user = User._default_manager.get_by_natural_key(username)
|
user = User._default_manager.get_by_natural_key(username)
|
||||||
|
|
||||||
except User.DoesNotExist:
|
except User.DoesNotExist:
|
||||||
# Run the default password hasher once to reduce the timing
|
# Run the default password hasher once to reduce the timing
|
||||||
# difference between an existing and a nonexistent user (#20760).
|
# difference between an existing and a nonexistent user (#20760).
|
||||||
User().set_password(password)
|
User().set_password(password, request=request)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
tokens = Token.filter_not_expired(
|
tokens = Token.filter_not_expired(
|
||||||
|
@ -58,6 +58,7 @@ class PropertyMappingEvaluator(BaseEvaluator):
|
|||||||
self._context["user"] = user
|
self._context["user"] = user
|
||||||
if request:
|
if request:
|
||||||
req.http_request = request
|
req.http_request = request
|
||||||
|
self._context["http_request"] = request
|
||||||
req.context.update(**kwargs)
|
req.context.update(**kwargs)
|
||||||
self._context["request"] = req
|
self._context["request"] = req
|
||||||
self._context.update(**kwargs)
|
self._context.update(**kwargs)
|
||||||
|
@ -17,7 +17,9 @@ from authentik.events.middleware import should_log_model
|
|||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.events.utils import model_to_dict
|
from authentik.events.utils import model_to_dict
|
||||||
|
|
||||||
BANNER_TEXT = f"""### authentik shell ({get_full_version()})
|
|
||||||
|
def get_banner_text(shell_type="shell") -> str:
|
||||||
|
return f"""### authentik {shell_type} ({get_full_version()})
|
||||||
### Node {platform.node()} | Arch {platform.machine()} | Python {platform.python_version()} """
|
### Node {platform.node()} | Arch {platform.machine()} | Python {platform.python_version()} """
|
||||||
|
|
||||||
|
|
||||||
@ -114,4 +116,4 @@ class Command(BaseCommand):
|
|||||||
readline.parse_and_bind("tab: complete")
|
readline.parse_and_bind("tab: complete")
|
||||||
|
|
||||||
# Run interactive shell
|
# Run interactive shell
|
||||||
code.interact(banner=BANNER_TEXT, local=namespace)
|
code.interact(banner=get_banner_text(), local=namespace)
|
||||||
|
@ -0,0 +1,45 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0041_applicationentitlement"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authenticatedsession",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_c_expires_08251d_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authenticatedsession",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_c_expirin_9cd839_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authenticatedsession",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_c_expirin_195a84_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authenticatedsession",
|
||||||
|
index=models.Index(fields=["session_key"], name="authentik_c_session_d0f005_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="token",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_c_expires_a62b4b_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="token",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_c_expirin_a1b838_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="token",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_c_expirin_ba04d9_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -356,13 +356,13 @@ class User(SerializerModel, GuardianUserMixin, AttributesMixin, AbstractUser):
|
|||||||
"""superuser == staff user"""
|
"""superuser == staff user"""
|
||||||
return self.is_superuser # type: ignore
|
return self.is_superuser # type: ignore
|
||||||
|
|
||||||
def set_password(self, raw_password, signal=True, sender=None):
|
def set_password(self, raw_password, signal=True, sender=None, request=None):
|
||||||
if self.pk and signal:
|
if self.pk and signal:
|
||||||
from authentik.core.signals import password_changed
|
from authentik.core.signals import password_changed
|
||||||
|
|
||||||
if not sender:
|
if not sender:
|
||||||
sender = self
|
sender = self
|
||||||
password_changed.send(sender=sender, user=self, password=raw_password)
|
password_changed.send(sender=sender, user=self, password=raw_password, request=request)
|
||||||
self.password_change_date = now()
|
self.password_change_date = now()
|
||||||
return super().set_password(raw_password)
|
return super().set_password(raw_password)
|
||||||
|
|
||||||
@ -846,6 +846,11 @@ class ExpiringModel(models.Model):
|
|||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
abstract = True
|
abstract = True
|
||||||
|
indexes = [
|
||||||
|
models.Index(fields=["expires"]),
|
||||||
|
models.Index(fields=["expiring"]),
|
||||||
|
models.Index(fields=["expiring", "expires"]),
|
||||||
|
]
|
||||||
|
|
||||||
def expire_action(self, *args, **kwargs):
|
def expire_action(self, *args, **kwargs):
|
||||||
"""Handler which is called when this object is expired. By
|
"""Handler which is called when this object is expired. By
|
||||||
@ -901,7 +906,7 @@ class Token(SerializerModel, ManagedModel, ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Token")
|
verbose_name = _("Token")
|
||||||
verbose_name_plural = _("Tokens")
|
verbose_name_plural = _("Tokens")
|
||||||
indexes = [
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
models.Index(fields=["identifier"]),
|
models.Index(fields=["identifier"]),
|
||||||
models.Index(fields=["key"]),
|
models.Index(fields=["key"]),
|
||||||
]
|
]
|
||||||
@ -1001,6 +1006,9 @@ class AuthenticatedSession(ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Authenticated Session")
|
verbose_name = _("Authenticated Session")
|
||||||
verbose_name_plural = _("Authenticated Sessions")
|
verbose_name_plural = _("Authenticated Sessions")
|
||||||
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
|
models.Index(fields=["session_key"]),
|
||||||
|
]
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return f"Authenticated Session {self.session_key[:10]}"
|
return f"Authenticated Session {self.session_key[:10]}"
|
||||||
|
@ -28,7 +28,6 @@ from rest_framework.validators import UniqueValidator
|
|||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import SecretKeyFilter
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.crypto.apps import MANAGED_KEY
|
from authentik.crypto.apps import MANAGED_KEY
|
||||||
@ -36,7 +35,7 @@ from authentik.crypto.builder import CertificateBuilder, PrivateKeyAlg
|
|||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.rbac.decorators import permission_required
|
from authentik.rbac.decorators import permission_required
|
||||||
from authentik.rbac.filters import ObjectFilter
|
from authentik.rbac.filters import ObjectFilter, SecretKeyFilter
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
@ -0,0 +1,27 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_enterprise", "0003_remove_licenseusage_within_limits_and_more"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="licenseusage",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_e_expires_3f2956_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="licenseusage",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_e_expirin_11d3d7_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="licenseusage",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_e_expirin_4d558f_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -93,3 +93,4 @@ class LicenseUsage(ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("License Usage")
|
verbose_name = _("License Usage")
|
||||||
verbose_name_plural = _("License Usage Records")
|
verbose_name_plural = _("License Usage Records")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
@ -1,11 +1,8 @@
|
|||||||
"""RAC Provider API Views"""
|
"""RAC Provider API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
|
||||||
from authentik.core.api.groups import GroupMemberSerializer
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
@ -34,12 +31,6 @@ class ConnectionTokenSerializer(EnterpriseRequiredMixin, ModelSerializer):
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class ConnectionTokenOwnerFilter(OwnerFilter):
|
|
||||||
"""Owner filter for connection tokens (checks session's user)"""
|
|
||||||
|
|
||||||
owner_key = "session__user"
|
|
||||||
|
|
||||||
|
|
||||||
class ConnectionTokenViewSet(
|
class ConnectionTokenViewSet(
|
||||||
mixins.RetrieveModelMixin,
|
mixins.RetrieveModelMixin,
|
||||||
mixins.UpdateModelMixin,
|
mixins.UpdateModelMixin,
|
||||||
@ -55,10 +46,4 @@ class ConnectionTokenViewSet(
|
|||||||
filterset_fields = ["endpoint", "session__user", "provider"]
|
filterset_fields = ["endpoint", "session__user", "provider"]
|
||||||
search_fields = ["endpoint__name", "provider__name"]
|
search_fields = ["endpoint__name", "provider__name"]
|
||||||
ordering = ["endpoint__name", "provider__name"]
|
ordering = ["endpoint__name", "provider__name"]
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
owner_field = "session__user"
|
||||||
filter_backends = [
|
|
||||||
ConnectionTokenOwnerFilter,
|
|
||||||
DjangoFilterBackend,
|
|
||||||
OrderingFilter,
|
|
||||||
SearchFilter,
|
|
||||||
]
|
|
||||||
|
@ -0,0 +1,28 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0042_authenticatedsession_authentik_c_expires_08251d_idx_and_more"),
|
||||||
|
("authentik_providers_rac", "0005_alter_racpropertymapping_options"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="connectiontoken",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_91f148_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="connectiontoken",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_59a5a7_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="connectiontoken",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_aed3ca_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -159,9 +159,9 @@ class ConnectionToken(ExpiringModel):
|
|||||||
default_settings["port"] = str(port)
|
default_settings["port"] = str(port)
|
||||||
else:
|
else:
|
||||||
default_settings["hostname"] = self.endpoint.host
|
default_settings["hostname"] = self.endpoint.host
|
||||||
default_settings["client-name"] = "authentik"
|
if self.endpoint.protocol == Protocols.RDP:
|
||||||
# default_settings["enable-drive"] = "true"
|
default_settings["resize-method"] = "display-update"
|
||||||
# default_settings["drive-name"] = "authentik"
|
default_settings["client-name"] = f"authentik - {self.session.user}"
|
||||||
settings = {}
|
settings = {}
|
||||||
always_merger.merge(settings, default_settings)
|
always_merger.merge(settings, default_settings)
|
||||||
always_merger.merge(settings, self.endpoint.provider.settings)
|
always_merger.merge(settings, self.endpoint.provider.settings)
|
||||||
@ -211,3 +211,4 @@ class ConnectionToken(ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("RAC Connection token")
|
verbose_name = _("RAC Connection token")
|
||||||
verbose_name_plural = _("RAC Connection tokens")
|
verbose_name_plural = _("RAC Connection tokens")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
@ -50,9 +50,10 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Set settings in provider
|
# Set settings in provider
|
||||||
@ -63,10 +64,11 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
"level": "provider",
|
"level": "provider",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Set settings in endpoint
|
# Set settings in endpoint
|
||||||
@ -79,10 +81,11 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
"level": "endpoint",
|
"level": "endpoint",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Set settings in token
|
# Set settings in token
|
||||||
@ -95,10 +98,11 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
"level": "token",
|
"level": "token",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Set settings in property mapping (provider)
|
# Set settings in property mapping (provider)
|
||||||
@ -114,10 +118,11 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
"level": "property_mapping_provider",
|
"level": "property_mapping_provider",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
# Set settings in property mapping (endpoint)
|
# Set settings in property mapping (endpoint)
|
||||||
@ -135,11 +140,12 @@ class TestModels(TransactionTestCase):
|
|||||||
{
|
{
|
||||||
"hostname": self.endpoint.host.split(":")[0],
|
"hostname": self.endpoint.host.split(":")[0],
|
||||||
"port": "1324",
|
"port": "1324",
|
||||||
"client-name": "authentik",
|
"client-name": f"authentik - {self.user}",
|
||||||
"drive-path": path,
|
"drive-path": path,
|
||||||
"create-drive-path": "true",
|
"create-drive-path": "true",
|
||||||
"level": "property_mapping_endpoint",
|
"level": "property_mapping_endpoint",
|
||||||
"foo": "true",
|
"foo": "true",
|
||||||
"bar": "6",
|
"bar": "6",
|
||||||
|
"resize-method": "display-update",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
@ -1,14 +1,11 @@
|
|||||||
"""AuthenticatorEndpointGDTCStage API Views"""
|
"""AuthenticatorEndpointGDTCStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.permissions import IsAdminUser
|
from rest_framework.permissions import IsAdminUser
|
||||||
from rest_framework.serializers import ModelSerializer
|
from rest_framework.serializers import ModelSerializer
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.enterprise.api import EnterpriseRequiredMixin
|
from authentik.enterprise.api import EnterpriseRequiredMixin
|
||||||
from authentik.enterprise.stages.authenticator_endpoint_gdtc.models import (
|
from authentik.enterprise.stages.authenticator_endpoint_gdtc.models import (
|
||||||
@ -67,8 +64,7 @@ class EndpointDeviceViewSet(
|
|||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
permission_classes = [OwnerPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
|
|
||||||
class EndpointAdminDeviceViewSet(ModelViewSet):
|
class EndpointAdminDeviceViewSet(ModelViewSet):
|
||||||
|
@ -1,17 +1,15 @@
|
|||||||
"""Notification API Views"""
|
"""Notification API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
from drf_spectacular.utils import OpenApiResponse, extend_schema
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import ReadOnlyField
|
from rest_framework.fields import ReadOnlyField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import GenericViewSet
|
from rest_framework.viewsets import GenericViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.events.api.events import EventSerializer
|
from authentik.events.api.events import EventSerializer
|
||||||
@ -57,8 +55,7 @@ class NotificationViewSet(
|
|||||||
"seen",
|
"seen",
|
||||||
"user",
|
"user",
|
||||||
]
|
]
|
||||||
permission_classes = [OwnerPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
request=OpenApiTypes.NONE,
|
request=OpenApiTypes.NONE,
|
||||||
@ -66,7 +63,7 @@ class NotificationViewSet(
|
|||||||
204: OpenApiResponse(description="Marked tasks as read successfully."),
|
204: OpenApiResponse(description="Marked tasks as read successfully."),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@action(detail=False, methods=["post"])
|
@action(detail=False, methods=["post"], permission_classes=[IsAuthenticated])
|
||||||
def mark_all_seen(self, request: Request) -> Response:
|
def mark_all_seen(self, request: Request) -> Response:
|
||||||
"""Mark all the user's notifications as seen"""
|
"""Mark all the user's notifications as seen"""
|
||||||
Notification.objects.filter(user=request.user, seen=False).update(seen=True)
|
Notification.objects.filter(user=request.user, seen=False).update(seen=True)
|
||||||
|
@ -0,0 +1,41 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_events", "0007_event_authentik_e_action_9a9dd9_idx_and_more"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="event",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_e_expires_8c73a8_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="event",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_e_expirin_b5cb5e_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="event",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_e_expirin_e37180_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="systemtask",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_e_expires_4d3985_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="systemtask",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_e_expirin_81d649_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="systemtask",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_e_expirin_eb3598_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -306,7 +306,7 @@ class Event(SerializerModel, ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Event")
|
verbose_name = _("Event")
|
||||||
verbose_name_plural = _("Events")
|
verbose_name_plural = _("Events")
|
||||||
indexes = [
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
models.Index(fields=["action"]),
|
models.Index(fields=["action"]),
|
||||||
models.Index(fields=["user"]),
|
models.Index(fields=["user"]),
|
||||||
models.Index(fields=["app"]),
|
models.Index(fields=["app"]),
|
||||||
@ -694,3 +694,4 @@ class SystemTask(SerializerModel, ExpiringModel):
|
|||||||
permissions = [("run_task", _("Run task"))]
|
permissions = [("run_task", _("Run task"))]
|
||||||
verbose_name = _("System Task")
|
verbose_name = _("System Task")
|
||||||
verbose_name_plural = _("System Tasks")
|
verbose_name_plural = _("System Tasks")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
@ -106,9 +106,9 @@ def on_invitation_used(sender, request: HttpRequest, invitation: Invitation, **_
|
|||||||
|
|
||||||
|
|
||||||
@receiver(password_changed)
|
@receiver(password_changed)
|
||||||
def on_password_changed(sender, user: User, password: str, **_):
|
def on_password_changed(sender, user: User, password: str, request: HttpRequest | None, **_):
|
||||||
"""Log password change"""
|
"""Log password change"""
|
||||||
Event.new(EventAction.PASSWORD_SET).from_http(None, user=user)
|
Event.new(EventAction.PASSWORD_SET).from_http(request, user=user)
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save, sender=Event)
|
@receiver(post_save, sender=Event)
|
||||||
|
@ -138,7 +138,6 @@ def notification_cleanup(self: SystemTask):
|
|||||||
"""Cleanup seen notifications and notifications whose event expired."""
|
"""Cleanup seen notifications and notifications whose event expired."""
|
||||||
notifications = Notification.objects.filter(Q(event=None) | Q(seen=True))
|
notifications = Notification.objects.filter(Q(event=None) | Q(seen=True))
|
||||||
amount = notifications.count()
|
amount = notifications.count()
|
||||||
for notification in notifications:
|
notifications.delete()
|
||||||
notification.delete()
|
|
||||||
LOGGER.debug("Expired notifications", amount=amount)
|
LOGGER.debug("Expired notifications", amount=amount)
|
||||||
self.set_status(TaskStatus.SUCCESSFUL, f"Expired {amount} Notifications")
|
self.set_status(TaskStatus.SUCCESSFUL, f"Expired {amount} Notifications")
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
"""Flow Stage API Views"""
|
"""Flow Stage API Views"""
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
from django.urls.base import reverse
|
from django.urls.base import reverse
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
@ -27,6 +29,11 @@ class StageSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
component = SerializerMethodField()
|
component = SerializerMethodField()
|
||||||
flow_set = FlowSetSerializer(many=True, required=False)
|
flow_set = FlowSetSerializer(many=True, required=False)
|
||||||
|
|
||||||
|
def to_representation(self, instance: Stage):
|
||||||
|
if isinstance(instance, Stage) and instance.is_in_memory:
|
||||||
|
instance.stage_uuid = uuid4()
|
||||||
|
return super().to_representation(instance)
|
||||||
|
|
||||||
def get_component(self, obj: Stage) -> str:
|
def get_component(self, obj: Stage) -> str:
|
||||||
"""Get object type so that we know how to edit the object"""
|
"""Get object type so that we know how to edit the object"""
|
||||||
if obj.__class__ == Stage:
|
if obj.__class__ == Stage:
|
||||||
|
@ -88,7 +88,8 @@ class Migration(migrations.Migration):
|
|||||||
model_name="flowstagebinding",
|
model_name="flowstagebinding",
|
||||||
name="re_evaluate_policies",
|
name="re_evaluate_policies",
|
||||||
field=models.BooleanField(
|
field=models.BooleanField(
|
||||||
default=False, help_text="Evaluate policies when the Stage is present to the user."
|
default=False,
|
||||||
|
help_text="Evaluate policies when the Stage is presented to the user.",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
migrations.AddField(
|
migrations.AddField(
|
||||||
|
@ -20,7 +20,7 @@ class Migration(migrations.Migration):
|
|||||||
model_name="flowstagebinding",
|
model_name="flowstagebinding",
|
||||||
name="re_evaluate_policies",
|
name="re_evaluate_policies",
|
||||||
field=models.BooleanField(
|
field=models.BooleanField(
|
||||||
default=True, help_text="Evaluate policies when the Stage is present to the user."
|
default=True, help_text="Evaluate policies when the Stage is presented to the user."
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
@ -102,8 +102,12 @@ class Stage(SerializerModel):
|
|||||||
user settings are available, or a challenge."""
|
user settings are available, or a challenge."""
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_in_memory(self):
|
||||||
|
return hasattr(self, "__in_memory_type")
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
if hasattr(self, "__in_memory_type"):
|
if self.is_in_memory:
|
||||||
return f"In-memory Stage {getattr(self, '__in_memory_type')}"
|
return f"In-memory Stage {getattr(self, '__in_memory_type')}"
|
||||||
return f"Stage {self.name}"
|
return f"Stage {self.name}"
|
||||||
|
|
||||||
@ -227,7 +231,7 @@ class FlowStageBinding(SerializerModel, PolicyBindingModel):
|
|||||||
)
|
)
|
||||||
re_evaluate_policies = models.BooleanField(
|
re_evaluate_policies = models.BooleanField(
|
||||||
default=True,
|
default=True,
|
||||||
help_text=_("Evaluate policies when the Stage is present to the user."),
|
help_text=_("Evaluate policies when the Stage is presented to the user."),
|
||||||
)
|
)
|
||||||
|
|
||||||
invalid_response_action = models.TextField(
|
invalid_response_action = models.TextField(
|
||||||
|
@ -159,9 +159,17 @@ class FlowPlan:
|
|||||||
stage = final_stage(request=request, executor=temp_exec)
|
stage = final_stage(request=request, executor=temp_exec)
|
||||||
return stage.dispatch(request)
|
return stage.dispatch(request)
|
||||||
|
|
||||||
|
get_qs = request.GET.copy()
|
||||||
|
if request.user.is_authenticated and (
|
||||||
|
# Object-scoped permission or global permission
|
||||||
|
request.user.has_perm("authentik_flows.inspect_flow", flow)
|
||||||
|
or request.user.has_perm("authentik_flows.inspect_flow")
|
||||||
|
):
|
||||||
|
get_qs["inspector"] = "available"
|
||||||
|
|
||||||
return redirect_with_qs(
|
return redirect_with_qs(
|
||||||
"authentik_core:if-flow",
|
"authentik_core:if-flow",
|
||||||
request.GET,
|
get_qs,
|
||||||
flow_slug=flow.slug,
|
flow_slug=flow.slug,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -7,8 +7,8 @@ from django.http import HttpRequest, HttpResponse
|
|||||||
from django.test.client import RequestFactory
|
from django.test.client import RequestFactory
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
from authentik.core.models import User
|
from authentik.core.models import Group, User
|
||||||
from authentik.core.tests.utils import create_test_flow
|
from authentik.core.tests.utils import create_test_flow, create_test_user
|
||||||
from authentik.flows.markers import ReevaluateMarker, StageMarker
|
from authentik.flows.markers import ReevaluateMarker, StageMarker
|
||||||
from authentik.flows.models import (
|
from authentik.flows.models import (
|
||||||
FlowDeniedAction,
|
FlowDeniedAction,
|
||||||
@ -255,7 +255,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
binding = FlowStageBinding.objects.create(
|
binding = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=0,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
binding2 = FlowStageBinding.objects.create(
|
binding2 = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
@ -278,8 +282,8 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[0], binding)
|
self.assertEqual(plan.bindings[0], binding)
|
||||||
self.assertEqual(plan.bindings[1], binding2)
|
self.assertEqual(plan.bindings[1], binding2)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
self.assertEqual(plan.markers[1].__class__, ReevaluateMarker)
|
||||||
|
|
||||||
# Second request, this passes the first dummy stage
|
# Second request, this passes the first dummy stage
|
||||||
response = self.client.post(exec_url)
|
response = self.client.post(exec_url)
|
||||||
@ -301,7 +305,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
binding = FlowStageBinding.objects.create(
|
binding = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=0,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
binding2 = FlowStageBinding.objects.create(
|
binding2 = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
@ -310,7 +318,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
re_evaluate_policies=True,
|
re_evaluate_policies=True,
|
||||||
)
|
)
|
||||||
binding3 = FlowStageBinding.objects.create(
|
binding3 = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=2
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=2,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0)
|
PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0)
|
||||||
@ -328,9 +340,9 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[1], binding2)
|
self.assertEqual(plan.bindings[1], binding2)
|
||||||
self.assertEqual(plan.bindings[2], binding3)
|
self.assertEqual(plan.bindings[2], binding3)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
self.assertEqual(plan.markers[1].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[2], StageMarker)
|
self.assertEqual(plan.markers[2].__class__, StageMarker)
|
||||||
|
|
||||||
# Second request, this passes the first dummy stage
|
# Second request, this passes the first dummy stage
|
||||||
response = self.client.post(exec_url)
|
response = self.client.post(exec_url)
|
||||||
@ -341,8 +353,8 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[0], binding2)
|
self.assertEqual(plan.bindings[0], binding2)
|
||||||
self.assertEqual(plan.bindings[1], binding3)
|
self.assertEqual(plan.bindings[1], binding3)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[1], StageMarker)
|
self.assertEqual(plan.markers[1].__class__, StageMarker)
|
||||||
|
|
||||||
# third request, this should trigger the re-evaluate
|
# third request, this should trigger the re-evaluate
|
||||||
# We do this request without the patch, so the policy results in false
|
# We do this request without the patch, so the policy results in false
|
||||||
@ -360,7 +372,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
binding = FlowStageBinding.objects.create(
|
binding = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=0,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
binding2 = FlowStageBinding.objects.create(
|
binding2 = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
@ -369,7 +385,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
re_evaluate_policies=True,
|
re_evaluate_policies=True,
|
||||||
)
|
)
|
||||||
binding3 = FlowStageBinding.objects.create(
|
binding3 = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=2
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=2,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
PolicyBinding.objects.create(policy=true_policy, target=binding2, order=0)
|
PolicyBinding.objects.create(policy=true_policy, target=binding2, order=0)
|
||||||
@ -387,9 +407,9 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[1], binding2)
|
self.assertEqual(plan.bindings[1], binding2)
|
||||||
self.assertEqual(plan.bindings[2], binding3)
|
self.assertEqual(plan.bindings[2], binding3)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
self.assertEqual(plan.markers[1].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[2], StageMarker)
|
self.assertEqual(plan.markers[2].__class__, StageMarker)
|
||||||
|
|
||||||
# Second request, this passes the first dummy stage
|
# Second request, this passes the first dummy stage
|
||||||
response = self.client.post(exec_url)
|
response = self.client.post(exec_url)
|
||||||
@ -400,8 +420,8 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[0], binding2)
|
self.assertEqual(plan.bindings[0], binding2)
|
||||||
self.assertEqual(plan.bindings[1], binding3)
|
self.assertEqual(plan.bindings[1], binding3)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[1], StageMarker)
|
self.assertEqual(plan.markers[1].__class__, StageMarker)
|
||||||
|
|
||||||
# Third request, this passes the first dummy stage
|
# Third request, this passes the first dummy stage
|
||||||
response = self.client.post(exec_url)
|
response = self.client.post(exec_url)
|
||||||
@ -411,7 +431,7 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
|
|
||||||
self.assertEqual(plan.bindings[0], binding3)
|
self.assertEqual(plan.bindings[0], binding3)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
|
|
||||||
# third request, this should trigger the re-evaluate
|
# third request, this should trigger the re-evaluate
|
||||||
# We do this request without the patch, so the policy results in false
|
# We do this request without the patch, so the policy results in false
|
||||||
@ -429,7 +449,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
binding = FlowStageBinding.objects.create(
|
binding = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=0,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
binding2 = FlowStageBinding.objects.create(
|
binding2 = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
@ -444,7 +468,11 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
re_evaluate_policies=True,
|
re_evaluate_policies=True,
|
||||||
)
|
)
|
||||||
binding4 = FlowStageBinding.objects.create(
|
binding4 = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=2
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=2,
|
||||||
|
evaluate_on_plan=True,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0)
|
PolicyBinding.objects.create(policy=false_policy, target=binding2, order=0)
|
||||||
@ -465,10 +493,10 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
self.assertEqual(plan.bindings[2], binding3)
|
self.assertEqual(plan.bindings[2], binding3)
|
||||||
self.assertEqual(plan.bindings[3], binding4)
|
self.assertEqual(plan.bindings[3], binding4)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
self.assertEqual(plan.markers[1].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[2], ReevaluateMarker)
|
self.assertEqual(plan.markers[2].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[3], StageMarker)
|
self.assertEqual(plan.markers[3].__class__, StageMarker)
|
||||||
|
|
||||||
# Second request, this passes the first dummy stage
|
# Second request, this passes the first dummy stage
|
||||||
response = self.client.post(exec_url)
|
response = self.client.post(exec_url)
|
||||||
@ -519,9 +547,9 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
# Stage 0 is a deny stage that is added dynamically
|
# Stage 0 is a deny stage that is added dynamically
|
||||||
# when the reputation policy says so
|
# when the reputation policy says so
|
||||||
deny_stage = DenyStage.objects.create(name="deny")
|
deny_stage = DenyStage.objects.create(name=generate_id())
|
||||||
reputation_policy = ReputationPolicy.objects.create(
|
reputation_policy = ReputationPolicy.objects.create(
|
||||||
name="reputation", threshold=-1, check_ip=False
|
name=generate_id(), threshold=-1, check_ip=False
|
||||||
)
|
)
|
||||||
deny_binding = FlowStageBinding.objects.create(
|
deny_binding = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
@ -534,7 +562,7 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
|
|
||||||
# Stage 1 is an identification stage
|
# Stage 1 is an identification stage
|
||||||
ident_stage = IdentificationStage.objects.create(
|
ident_stage = IdentificationStage.objects.create(
|
||||||
name="ident",
|
name=generate_id(),
|
||||||
user_fields=[UserFields.E_MAIL],
|
user_fields=[UserFields.E_MAIL],
|
||||||
pretend_user_exists=False,
|
pretend_user_exists=False,
|
||||||
)
|
)
|
||||||
@ -559,3 +587,64 @@ class TestFlowExecutor(FlowTestCase):
|
|||||||
)
|
)
|
||||||
response = self.client.post(exec_url, {"uid_field": "invalid-string"}, follow=True)
|
response = self.client.post(exec_url, {"uid_field": "invalid-string"}, follow=True)
|
||||||
self.assertStageResponse(response, flow, component="ak-stage-access-denied")
|
self.assertStageResponse(response, flow, component="ak-stage-access-denied")
|
||||||
|
|
||||||
|
def test_re_evaluate_group_binding(self):
|
||||||
|
"""Test re-evaluate stage binding that has a policy binding to a group"""
|
||||||
|
flow = create_test_flow()
|
||||||
|
|
||||||
|
user_group_membership = create_test_user()
|
||||||
|
user_direct_binding = create_test_user()
|
||||||
|
user_other = create_test_user()
|
||||||
|
|
||||||
|
group_a = Group.objects.create(name=generate_id())
|
||||||
|
user_group_membership.ak_groups.add(group_a)
|
||||||
|
|
||||||
|
# Stage 0 is an identification stage
|
||||||
|
ident_stage = IdentificationStage.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
user_fields=[UserFields.USERNAME],
|
||||||
|
pretend_user_exists=False,
|
||||||
|
)
|
||||||
|
FlowStageBinding.objects.create(
|
||||||
|
target=flow,
|
||||||
|
stage=ident_stage,
|
||||||
|
order=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stage 1 is a dummy stage that is only shown for users in group_a
|
||||||
|
dummy_stage = DummyStage.objects.create(name=generate_id())
|
||||||
|
dummy_binding = FlowStageBinding.objects.create(target=flow, stage=dummy_stage, order=1)
|
||||||
|
PolicyBinding.objects.create(group=group_a, target=dummy_binding, order=0)
|
||||||
|
PolicyBinding.objects.create(user=user_direct_binding, target=dummy_binding, order=0)
|
||||||
|
|
||||||
|
# Stage 2 is a deny stage that (in this case) only user_b will see
|
||||||
|
deny_stage = DenyStage.objects.create(name=generate_id())
|
||||||
|
FlowStageBinding.objects.create(target=flow, stage=deny_stage, order=2)
|
||||||
|
|
||||||
|
exec_url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug})
|
||||||
|
|
||||||
|
with self.subTest(f"Test user access through group: {user_group_membership}"):
|
||||||
|
self.client.logout()
|
||||||
|
# First request, run the planner
|
||||||
|
response = self.client.get(exec_url)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-identification")
|
||||||
|
response = self.client.post(
|
||||||
|
exec_url, {"uid_field": user_group_membership.username}, follow=True
|
||||||
|
)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-dummy")
|
||||||
|
with self.subTest(f"Test user access through user: {user_direct_binding}"):
|
||||||
|
self.client.logout()
|
||||||
|
# First request, run the planner
|
||||||
|
response = self.client.get(exec_url)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-identification")
|
||||||
|
response = self.client.post(
|
||||||
|
exec_url, {"uid_field": user_direct_binding.username}, follow=True
|
||||||
|
)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-dummy")
|
||||||
|
with self.subTest(f"Test user has no access: {user_other}"):
|
||||||
|
self.client.logout()
|
||||||
|
# First request, run the planner
|
||||||
|
response = self.client.get(exec_url)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-identification")
|
||||||
|
response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True)
|
||||||
|
self.assertStageResponse(response, flow, component="ak-stage-access-denied")
|
||||||
|
@ -8,6 +8,7 @@ from rest_framework.test import APITestCase
|
|||||||
|
|
||||||
from authentik.core.tests.utils import create_test_admin_user, create_test_flow
|
from authentik.core.tests.utils import create_test_admin_user, create_test_flow
|
||||||
from authentik.flows.models import FlowDesignation, FlowStageBinding, InvalidResponseAction
|
from authentik.flows.models import FlowDesignation, FlowStageBinding, InvalidResponseAction
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.stages.dummy.models import DummyStage
|
from authentik.stages.dummy.models import DummyStage
|
||||||
from authentik.stages.identification.models import IdentificationStage, UserFields
|
from authentik.stages.identification.models import IdentificationStage, UserFields
|
||||||
|
|
||||||
@ -26,7 +27,7 @@ class TestFlowInspector(APITestCase):
|
|||||||
|
|
||||||
# Stage 1 is an identification stage
|
# Stage 1 is an identification stage
|
||||||
ident_stage = IdentificationStage.objects.create(
|
ident_stage = IdentificationStage.objects.create(
|
||||||
name="ident",
|
name=generate_id(),
|
||||||
user_fields=[UserFields.USERNAME],
|
user_fields=[UserFields.USERNAME],
|
||||||
)
|
)
|
||||||
FlowStageBinding.objects.create(
|
FlowStageBinding.objects.create(
|
||||||
@ -35,9 +36,8 @@ class TestFlowInspector(APITestCase):
|
|||||||
order=1,
|
order=1,
|
||||||
invalid_response_action=InvalidResponseAction.RESTART_WITH_CONTEXT,
|
invalid_response_action=InvalidResponseAction.RESTART_WITH_CONTEXT,
|
||||||
)
|
)
|
||||||
FlowStageBinding.objects.create(
|
dummy_stage = DummyStage.objects.create(name=generate_id())
|
||||||
target=flow, stage=DummyStage.objects.create(name="dummy2"), order=1
|
FlowStageBinding.objects.create(target=flow, stage=dummy_stage, order=1)
|
||||||
)
|
|
||||||
|
|
||||||
res = self.client.get(
|
res = self.client.get(
|
||||||
reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
|
reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
|
||||||
@ -68,9 +68,11 @@ class TestFlowInspector(APITestCase):
|
|||||||
)
|
)
|
||||||
content = loads(ins.content)
|
content = loads(ins.content)
|
||||||
self.assertEqual(content["is_completed"], False)
|
self.assertEqual(content["is_completed"], False)
|
||||||
self.assertEqual(content["current_plan"]["current_stage"]["stage_obj"]["name"], "ident")
|
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
content["current_plan"]["next_planned_stage"]["stage_obj"]["name"], "dummy2"
|
content["current_plan"]["current_stage"]["stage_obj"]["name"], ident_stage.name
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
content["current_plan"]["next_planned_stage"]["stage_obj"]["name"], dummy_stage.name
|
||||||
)
|
)
|
||||||
|
|
||||||
self.client.post(
|
self.client.post(
|
||||||
@ -84,8 +86,12 @@ class TestFlowInspector(APITestCase):
|
|||||||
)
|
)
|
||||||
content = loads(ins.content)
|
content = loads(ins.content)
|
||||||
self.assertEqual(content["is_completed"], False)
|
self.assertEqual(content["is_completed"], False)
|
||||||
self.assertEqual(content["plans"][0]["current_stage"]["stage_obj"]["name"], "ident")
|
self.assertEqual(
|
||||||
self.assertEqual(content["current_plan"]["current_stage"]["stage_obj"]["name"], "dummy2")
|
content["plans"][0]["current_stage"]["stage_obj"]["name"], ident_stage.name
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
content["current_plan"]["current_stage"]["stage_obj"]["name"], dummy_stage.name
|
||||||
|
)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
content["current_plan"]["plan_context"]["pending_user"]["username"], self.admin.username
|
content["current_plan"]["plan_context"]["pending_user"]["username"], self.admin.username
|
||||||
)
|
)
|
||||||
|
@ -29,6 +29,7 @@ from authentik.flows.planner import (
|
|||||||
cache_key,
|
cache_key,
|
||||||
)
|
)
|
||||||
from authentik.flows.stage import StageView
|
from authentik.flows.stage import StageView
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.tests.utils import dummy_get_response
|
from authentik.lib.tests.utils import dummy_get_response
|
||||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
from authentik.outposts.models import Outpost
|
from authentik.outposts.models import Outpost
|
||||||
@ -153,7 +154,7 @@ class TestFlowPlanner(TestCase):
|
|||||||
"""Test planner cache"""
|
"""Test planner cache"""
|
||||||
flow = create_test_flow(FlowDesignation.AUTHENTICATION)
|
flow = create_test_flow(FlowDesignation.AUTHENTICATION)
|
||||||
FlowStageBinding.objects.create(
|
FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name="dummy"), order=0
|
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
||||||
)
|
)
|
||||||
request = self.request_factory.get(
|
request = self.request_factory.get(
|
||||||
reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
|
reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}),
|
||||||
@ -172,7 +173,7 @@ class TestFlowPlanner(TestCase):
|
|||||||
"""Test planner with default_context"""
|
"""Test planner with default_context"""
|
||||||
flow = create_test_flow()
|
flow = create_test_flow()
|
||||||
FlowStageBinding.objects.create(
|
FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name="dummy"), order=0
|
target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
|
||||||
)
|
)
|
||||||
|
|
||||||
user = User.objects.create(username="test-user")
|
user = User.objects.create(username="test-user")
|
||||||
@ -191,7 +192,7 @@ class TestFlowPlanner(TestCase):
|
|||||||
|
|
||||||
FlowStageBinding.objects.create(
|
FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
stage=DummyStage.objects.create(name="dummy1"),
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
order=0,
|
order=0,
|
||||||
re_evaluate_policies=True,
|
re_evaluate_policies=True,
|
||||||
)
|
)
|
||||||
@ -204,7 +205,7 @@ class TestFlowPlanner(TestCase):
|
|||||||
planner = FlowPlanner(flow)
|
planner = FlowPlanner(flow)
|
||||||
plan = planner.plan(request)
|
plan = planner.plan(request)
|
||||||
|
|
||||||
self.assertIsInstance(plan.markers[0], ReevaluateMarker)
|
self.assertEqual(plan.markers[0].__class__, ReevaluateMarker)
|
||||||
|
|
||||||
def test_planner_reevaluate_actual(self):
|
def test_planner_reevaluate_actual(self):
|
||||||
"""Test planner with re-evaluate"""
|
"""Test planner with re-evaluate"""
|
||||||
@ -212,11 +213,14 @@ class TestFlowPlanner(TestCase):
|
|||||||
false_policy = DummyPolicy.objects.create(result=False, wait_min=1, wait_max=2)
|
false_policy = DummyPolicy.objects.create(result=False, wait_min=1, wait_max=2)
|
||||||
|
|
||||||
binding = FlowStageBinding.objects.create(
|
binding = FlowStageBinding.objects.create(
|
||||||
target=flow, stage=DummyStage.objects.create(name="dummy1"), order=0
|
target=flow,
|
||||||
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
|
order=0,
|
||||||
|
re_evaluate_policies=False,
|
||||||
)
|
)
|
||||||
binding2 = FlowStageBinding.objects.create(
|
binding2 = FlowStageBinding.objects.create(
|
||||||
target=flow,
|
target=flow,
|
||||||
stage=DummyStage.objects.create(name="dummy2"),
|
stage=DummyStage.objects.create(name=generate_id()),
|
||||||
order=1,
|
order=1,
|
||||||
re_evaluate_policies=True,
|
re_evaluate_policies=True,
|
||||||
)
|
)
|
||||||
@ -240,6 +244,8 @@ class TestFlowPlanner(TestCase):
|
|||||||
self.assertEqual(plan.bindings[0], binding)
|
self.assertEqual(plan.bindings[0], binding)
|
||||||
self.assertEqual(plan.bindings[1], binding2)
|
self.assertEqual(plan.bindings[1], binding2)
|
||||||
|
|
||||||
|
self.assertEqual(plan.markers[0].__class__, StageMarker)
|
||||||
|
self.assertEqual(plan.markers[1].__class__, ReevaluateMarker)
|
||||||
self.assertIsInstance(plan.markers[0], StageMarker)
|
self.assertIsInstance(plan.markers[0], StageMarker)
|
||||||
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
self.assertIsInstance(plan.markers[1], ReevaluateMarker)
|
||||||
|
|
||||||
|
@ -78,7 +78,9 @@ class FlowInspectorView(APIView):
|
|||||||
self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
|
self.flow = get_object_or_404(Flow.objects.select_related(), slug=flow_slug)
|
||||||
if settings.DEBUG:
|
if settings.DEBUG:
|
||||||
return
|
return
|
||||||
if request.user.has_perm("authentik_flow.inspect_flow", self.flow):
|
if request.user.has_perm(
|
||||||
|
"authentik_flows.inspect_flow", self.flow
|
||||||
|
) or request.user.has_perm("authentik_flows.inspect_flow"):
|
||||||
return
|
return
|
||||||
raise Http404
|
raise Http404
|
||||||
|
|
||||||
@ -94,6 +96,9 @@ class FlowInspectorView(APIView):
|
|||||||
"""Get current flow state and record it"""
|
"""Get current flow state and record it"""
|
||||||
plans = []
|
plans = []
|
||||||
for plan in request.session.get(SESSION_KEY_HISTORY, []):
|
for plan in request.session.get(SESSION_KEY_HISTORY, []):
|
||||||
|
plan: FlowPlan
|
||||||
|
if plan.flow_pk != self.flow.pk.hex:
|
||||||
|
continue
|
||||||
plan_serializer = FlowInspectorPlanSerializer(
|
plan_serializer = FlowInspectorPlanSerializer(
|
||||||
instance=plan, context={"request": request}
|
instance=plan, context={"request": request}
|
||||||
)
|
)
|
||||||
|
@ -280,9 +280,24 @@ class ConfigLoader:
|
|||||||
self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
|
self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
def get_optional_int(self, path: str, default=None) -> int | None:
|
||||||
|
"""Wrapper for get that converts value into int or None if set"""
|
||||||
|
value = self.get(path, default)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (ValueError, TypeError) as exc:
|
||||||
|
if value is None or (isinstance(value, str) and value.lower() == "null"):
|
||||||
|
return None
|
||||||
|
self.log("warning", "Failed to parse config as int", path=path, exc=str(exc))
|
||||||
|
return default
|
||||||
|
|
||||||
def get_bool(self, path: str, default=False) -> bool:
|
def get_bool(self, path: str, default=False) -> bool:
|
||||||
"""Wrapper for get that converts value into boolean"""
|
"""Wrapper for get that converts value into boolean"""
|
||||||
return str(self.get(path, default)).lower() == "true"
|
value = self.get(path, UNSET)
|
||||||
|
if value is UNSET:
|
||||||
|
return default
|
||||||
|
return str(self.get(path)).lower() == "true"
|
||||||
|
|
||||||
def get_keys(self, path: str, sep=".") -> list[str]:
|
def get_keys(self, path: str, sep=".") -> list[str]:
|
||||||
"""List attribute keys by using yaml path"""
|
"""List attribute keys by using yaml path"""
|
||||||
@ -354,20 +369,33 @@ def django_db_config(config: ConfigLoader | None = None) -> dict:
|
|||||||
"sslcert": config.get("postgresql.sslcert"),
|
"sslcert": config.get("postgresql.sslcert"),
|
||||||
"sslkey": config.get("postgresql.sslkey"),
|
"sslkey": config.get("postgresql.sslkey"),
|
||||||
},
|
},
|
||||||
|
"CONN_MAX_AGE": CONFIG.get_optional_int("postgresql.conn_max_age", 0),
|
||||||
|
"CONN_HEALTH_CHECKS": CONFIG.get_bool("postgresql.conn_health_checks", False),
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": CONFIG.get_bool(
|
||||||
|
"postgresql.disable_server_side_cursors", False
|
||||||
|
),
|
||||||
"TEST": {
|
"TEST": {
|
||||||
"NAME": config.get("postgresql.test.name"),
|
"NAME": config.get("postgresql.test.name"),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
conn_max_age = CONFIG.get_optional_int("postgresql.conn_max_age", UNSET)
|
||||||
|
disable_server_side_cursors = CONFIG.get_bool("postgresql.disable_server_side_cursors", UNSET)
|
||||||
if config.get_bool("postgresql.use_pgpool", False):
|
if config.get_bool("postgresql.use_pgpool", False):
|
||||||
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
|
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
|
||||||
|
if disable_server_side_cursors is not UNSET:
|
||||||
|
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
|
||||||
|
|
||||||
if config.get_bool("postgresql.use_pgbouncer", False):
|
if config.get_bool("postgresql.use_pgbouncer", False):
|
||||||
# https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
|
# https://docs.djangoproject.com/en/4.0/ref/databases/#transaction-pooling-server-side-cursors
|
||||||
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
|
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = True
|
||||||
# https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
|
# https://docs.djangoproject.com/en/4.0/ref/databases/#persistent-connections
|
||||||
db["default"]["CONN_MAX_AGE"] = None # persistent
|
db["default"]["CONN_MAX_AGE"] = None # persistent
|
||||||
|
if disable_server_side_cursors is not UNSET:
|
||||||
|
db["default"]["DISABLE_SERVER_SIDE_CURSORS"] = disable_server_side_cursors
|
||||||
|
if conn_max_age is not UNSET:
|
||||||
|
db["default"]["CONN_MAX_AGE"] = conn_max_age
|
||||||
|
|
||||||
for replica in config.get_keys("postgresql.read_replicas"):
|
for replica in config.get_keys("postgresql.read_replicas"):
|
||||||
_database = deepcopy(db["default"])
|
_database = deepcopy(db["default"])
|
||||||
|
@ -6,8 +6,6 @@ postgresql:
|
|||||||
user: authentik
|
user: authentik
|
||||||
port: 5432
|
port: 5432
|
||||||
password: "env://POSTGRES_PASSWORD"
|
password: "env://POSTGRES_PASSWORD"
|
||||||
use_pgbouncer: false
|
|
||||||
use_pgpool: false
|
|
||||||
test:
|
test:
|
||||||
name: test_authentik
|
name: test_authentik
|
||||||
read_replicas: {}
|
read_replicas: {}
|
||||||
|
@ -9,20 +9,25 @@ from typing import Any
|
|||||||
|
|
||||||
from cachetools import TLRUCache, cached
|
from cachetools import TLRUCache, cached
|
||||||
from django.core.exceptions import FieldError
|
from django.core.exceptions import FieldError
|
||||||
|
from django.http import HttpRequest
|
||||||
from django.utils.text import slugify
|
from django.utils.text import slugify
|
||||||
|
from django.utils.timezone import now
|
||||||
from guardian.shortcuts import get_anonymous_user
|
from guardian.shortcuts import get_anonymous_user
|
||||||
from rest_framework.serializers import ValidationError
|
from rest_framework.serializers import ValidationError
|
||||||
from sentry_sdk import start_span
|
from sentry_sdk import start_span
|
||||||
from sentry_sdk.tracing import Span
|
from sentry_sdk.tracing import Span
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.core.models import User
|
from authentik.core.models import AuthenticatedSession, User
|
||||||
from authentik.events.models import Event
|
from authentik.events.models import Event
|
||||||
from authentik.lib.expression.exceptions import ControlFlowException
|
from authentik.lib.expression.exceptions import ControlFlowException
|
||||||
from authentik.lib.utils.http import get_http_session
|
from authentik.lib.utils.http import get_http_session
|
||||||
|
from authentik.lib.utils.time import timedelta_from_string
|
||||||
from authentik.policies.models import Policy, PolicyBinding
|
from authentik.policies.models import Policy, PolicyBinding
|
||||||
from authentik.policies.process import PolicyProcess
|
from authentik.policies.process import PolicyProcess
|
||||||
from authentik.policies.types import PolicyRequest, PolicyResult
|
from authentik.policies.types import PolicyRequest, PolicyResult
|
||||||
|
from authentik.providers.oauth2.id_token import IDToken
|
||||||
|
from authentik.providers.oauth2.models import AccessToken, OAuth2Provider
|
||||||
from authentik.stages.authenticator import devices_for_user
|
from authentik.stages.authenticator import devices_for_user
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
@ -56,6 +61,7 @@ class BaseEvaluator:
|
|||||||
"ak_logger": get_logger(self._filename).bind(),
|
"ak_logger": get_logger(self._filename).bind(),
|
||||||
"ak_user_by": BaseEvaluator.expr_user_by,
|
"ak_user_by": BaseEvaluator.expr_user_by,
|
||||||
"ak_user_has_authenticator": BaseEvaluator.expr_func_user_has_authenticator,
|
"ak_user_has_authenticator": BaseEvaluator.expr_func_user_has_authenticator,
|
||||||
|
"ak_create_jwt": self.expr_create_jwt,
|
||||||
"ip_address": ip_address,
|
"ip_address": ip_address,
|
||||||
"ip_network": ip_network,
|
"ip_network": ip_network,
|
||||||
"list_flatten": BaseEvaluator.expr_flatten,
|
"list_flatten": BaseEvaluator.expr_flatten,
|
||||||
@ -182,6 +188,36 @@ class BaseEvaluator:
|
|||||||
proc = PolicyProcess(PolicyBinding(policy=policy), request=req, connection=None)
|
proc = PolicyProcess(PolicyBinding(policy=policy), request=req, connection=None)
|
||||||
return proc.profiling_wrapper()
|
return proc.profiling_wrapper()
|
||||||
|
|
||||||
|
def expr_create_jwt(
|
||||||
|
self,
|
||||||
|
user: User,
|
||||||
|
provider: OAuth2Provider | str,
|
||||||
|
scopes: list[str],
|
||||||
|
validity: str = "seconds=60",
|
||||||
|
) -> str | None:
|
||||||
|
"""Issue a JWT for a given provider"""
|
||||||
|
request: HttpRequest = self._context.get("http_request")
|
||||||
|
if not request:
|
||||||
|
return None
|
||||||
|
if not isinstance(provider, OAuth2Provider):
|
||||||
|
provider = OAuth2Provider.objects.get(name=provider)
|
||||||
|
session = None
|
||||||
|
if hasattr(request, "session") and request.session.session_key:
|
||||||
|
session = AuthenticatedSession.objects.filter(
|
||||||
|
session_key=request.session.session_key
|
||||||
|
).first()
|
||||||
|
access_token = AccessToken(
|
||||||
|
provider=provider,
|
||||||
|
user=user,
|
||||||
|
expires=now() + timedelta_from_string(validity),
|
||||||
|
scope=scopes,
|
||||||
|
auth_time=now(),
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
access_token.id_token = IDToken.new(provider, access_token, request)
|
||||||
|
access_token.save()
|
||||||
|
return access_token.token
|
||||||
|
|
||||||
def wrap_expression(self, expression: str) -> str:
|
def wrap_expression(self, expression: str) -> str:
|
||||||
"""Wrap expression in a function, call it, and save the result as `result`"""
|
"""Wrap expression in a function, call it, and save the result as `result`"""
|
||||||
handler_signature = ",".join(sanitize_arg(x) for x in self._context.keys())
|
handler_signature = ",".join(sanitize_arg(x) for x in self._context.keys())
|
||||||
|
@ -214,6 +214,9 @@ class TestConfig(TestCase):
|
|||||||
"PORT": "foo",
|
"PORT": "foo",
|
||||||
"TEST": {"NAME": "foo"},
|
"TEST": {"NAME": "foo"},
|
||||||
"USER": "foo",
|
"USER": "foo",
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": False,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@ -251,6 +254,9 @@ class TestConfig(TestCase):
|
|||||||
"PORT": "foo",
|
"PORT": "foo",
|
||||||
"TEST": {"NAME": "foo"},
|
"TEST": {"NAME": "foo"},
|
||||||
"USER": "foo",
|
"USER": "foo",
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": False,
|
||||||
},
|
},
|
||||||
"replica_0": {
|
"replica_0": {
|
||||||
"ENGINE": "authentik.root.db",
|
"ENGINE": "authentik.root.db",
|
||||||
@ -266,6 +272,72 @@ class TestConfig(TestCase):
|
|||||||
"PORT": "foo",
|
"PORT": "foo",
|
||||||
"TEST": {"NAME": "foo"},
|
"TEST": {"NAME": "foo"},
|
||||||
"USER": "foo",
|
"USER": "foo",
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": False,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_db_read_replicas_pgbouncer(self):
|
||||||
|
"""Test read replicas"""
|
||||||
|
config = ConfigLoader()
|
||||||
|
config.set("postgresql.host", "foo")
|
||||||
|
config.set("postgresql.name", "foo")
|
||||||
|
config.set("postgresql.user", "foo")
|
||||||
|
config.set("postgresql.password", "foo")
|
||||||
|
config.set("postgresql.port", "foo")
|
||||||
|
config.set("postgresql.sslmode", "foo")
|
||||||
|
config.set("postgresql.sslrootcert", "foo")
|
||||||
|
config.set("postgresql.sslcert", "foo")
|
||||||
|
config.set("postgresql.sslkey", "foo")
|
||||||
|
config.set("postgresql.test.name", "foo")
|
||||||
|
config.set("postgresql.use_pgbouncer", True)
|
||||||
|
# Read replica
|
||||||
|
config.set("postgresql.read_replicas.0.host", "bar")
|
||||||
|
# Override conn_max_age
|
||||||
|
config.set("postgresql.read_replicas.0.conn_max_age", 10)
|
||||||
|
# This isn't supported
|
||||||
|
config.set("postgresql.read_replicas.0.use_pgbouncer", False)
|
||||||
|
conf = django_db_config(config)
|
||||||
|
self.assertEqual(
|
||||||
|
conf,
|
||||||
|
{
|
||||||
|
"default": {
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": True,
|
||||||
|
"CONN_MAX_AGE": None,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
|
"ENGINE": "authentik.root.db",
|
||||||
|
"HOST": "foo",
|
||||||
|
"NAME": "foo",
|
||||||
|
"OPTIONS": {
|
||||||
|
"sslcert": "foo",
|
||||||
|
"sslkey": "foo",
|
||||||
|
"sslmode": "foo",
|
||||||
|
"sslrootcert": "foo",
|
||||||
|
},
|
||||||
|
"PASSWORD": "foo",
|
||||||
|
"PORT": "foo",
|
||||||
|
"TEST": {"NAME": "foo"},
|
||||||
|
"USER": "foo",
|
||||||
|
},
|
||||||
|
"replica_0": {
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": True,
|
||||||
|
"CONN_MAX_AGE": 10,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
|
"ENGINE": "authentik.root.db",
|
||||||
|
"HOST": "bar",
|
||||||
|
"NAME": "foo",
|
||||||
|
"OPTIONS": {
|
||||||
|
"sslcert": "foo",
|
||||||
|
"sslkey": "foo",
|
||||||
|
"sslmode": "foo",
|
||||||
|
"sslrootcert": "foo",
|
||||||
|
},
|
||||||
|
"PASSWORD": "foo",
|
||||||
|
"PORT": "foo",
|
||||||
|
"TEST": {"NAME": "foo"},
|
||||||
|
"USER": "foo",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@ -294,6 +366,8 @@ class TestConfig(TestCase):
|
|||||||
{
|
{
|
||||||
"default": {
|
"default": {
|
||||||
"DISABLE_SERVER_SIDE_CURSORS": True,
|
"DISABLE_SERVER_SIDE_CURSORS": True,
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
"ENGINE": "authentik.root.db",
|
"ENGINE": "authentik.root.db",
|
||||||
"HOST": "foo",
|
"HOST": "foo",
|
||||||
"NAME": "foo",
|
"NAME": "foo",
|
||||||
@ -310,6 +384,8 @@ class TestConfig(TestCase):
|
|||||||
},
|
},
|
||||||
"replica_0": {
|
"replica_0": {
|
||||||
"DISABLE_SERVER_SIDE_CURSORS": True,
|
"DISABLE_SERVER_SIDE_CURSORS": True,
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
"ENGINE": "authentik.root.db",
|
"ENGINE": "authentik.root.db",
|
||||||
"HOST": "bar",
|
"HOST": "bar",
|
||||||
"NAME": "foo",
|
"NAME": "foo",
|
||||||
@ -362,6 +438,9 @@ class TestConfig(TestCase):
|
|||||||
"PORT": "foo",
|
"PORT": "foo",
|
||||||
"TEST": {"NAME": "foo"},
|
"TEST": {"NAME": "foo"},
|
||||||
"USER": "foo",
|
"USER": "foo",
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": False,
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
},
|
},
|
||||||
"replica_0": {
|
"replica_0": {
|
||||||
"ENGINE": "authentik.root.db",
|
"ENGINE": "authentik.root.db",
|
||||||
@ -377,6 +456,9 @@ class TestConfig(TestCase):
|
|||||||
"PORT": "foo",
|
"PORT": "foo",
|
||||||
"TEST": {"NAME": "foo"},
|
"TEST": {"NAME": "foo"},
|
||||||
"USER": "foo",
|
"USER": "foo",
|
||||||
|
"DISABLE_SERVER_SIDE_CURSORS": False,
|
||||||
|
"CONN_MAX_AGE": 0,
|
||||||
|
"CONN_HEALTH_CHECKS": False,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
@ -1,11 +1,15 @@
|
|||||||
"""Test Evaluator base functions"""
|
"""Test Evaluator base functions"""
|
||||||
|
|
||||||
from django.test import TestCase
|
from django.test import RequestFactory, TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
from jwt import decode
|
||||||
|
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.blueprints.tests import apply_blueprint
|
||||||
|
from authentik.core.tests.utils import create_test_admin_user, create_test_flow, create_test_user
|
||||||
from authentik.events.models import Event
|
from authentik.events.models import Event
|
||||||
from authentik.lib.expression.evaluator import BaseEvaluator
|
from authentik.lib.expression.evaluator import BaseEvaluator
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
|
from authentik.providers.oauth2.models import OAuth2Provider, ScopeMapping
|
||||||
|
|
||||||
|
|
||||||
class TestEvaluator(TestCase):
|
class TestEvaluator(TestCase):
|
||||||
@ -41,3 +45,35 @@ class TestEvaluator(TestCase):
|
|||||||
event = Event.objects.filter(action="custom_foo").first()
|
event = Event.objects.filter(action="custom_foo").first()
|
||||||
self.assertIsNotNone(event)
|
self.assertIsNotNone(event)
|
||||||
self.assertEqual(event.context, {"bar": "baz", "foo": "bar"})
|
self.assertEqual(event.context, {"bar": "baz", "foo": "bar"})
|
||||||
|
|
||||||
|
@apply_blueprint("system/providers-oauth2.yaml")
|
||||||
|
def test_expr_create_jwt(self):
|
||||||
|
"""Test expr_create_jwt"""
|
||||||
|
rf = RequestFactory()
|
||||||
|
user = create_test_user()
|
||||||
|
provider = OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
authorization_flow=create_test_flow(),
|
||||||
|
)
|
||||||
|
provider.property_mappings.set(
|
||||||
|
ScopeMapping.objects.filter(
|
||||||
|
managed__in=[
|
||||||
|
"goauthentik.io/providers/oauth2/scope-openid",
|
||||||
|
"goauthentik.io/providers/oauth2/scope-email",
|
||||||
|
"goauthentik.io/providers/oauth2/scope-profile",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
evaluator = BaseEvaluator(generate_id())
|
||||||
|
evaluator._context = {
|
||||||
|
"http_request": rf.get(reverse("authentik_core:root-redirect")),
|
||||||
|
"user": user,
|
||||||
|
"provider": provider.name,
|
||||||
|
}
|
||||||
|
jwt = evaluator.evaluate(
|
||||||
|
"return ak_create_jwt(user, provider, ['openid', 'email', 'profile'])"
|
||||||
|
)
|
||||||
|
decoded = decode(
|
||||||
|
jwt, provider.client_secret, algorithms=["HS256"], audience=provider.client_id
|
||||||
|
)
|
||||||
|
self.assertEqual(decoded["preferred_username"], user.username)
|
||||||
|
@ -207,7 +207,7 @@ class KubernetesObjectReconciler(Generic[T]):
|
|||||||
"app.kubernetes.io/instance": slugify(self.controller.outpost.name),
|
"app.kubernetes.io/instance": slugify(self.controller.outpost.name),
|
||||||
"app.kubernetes.io/managed-by": "goauthentik.io",
|
"app.kubernetes.io/managed-by": "goauthentik.io",
|
||||||
"app.kubernetes.io/name": f"authentik-{self.controller.outpost.type.lower()}",
|
"app.kubernetes.io/name": f"authentik-{self.controller.outpost.type.lower()}",
|
||||||
"app.kubernetes.io/version": get_version(),
|
"app.kubernetes.io/version": get_version().replace("+", "-"),
|
||||||
"goauthentik.io/outpost-name": slugify(self.controller.outpost.name),
|
"goauthentik.io/outpost-name": slugify(self.controller.outpost.name),
|
||||||
"goauthentik.io/outpost-type": str(self.controller.outpost.type),
|
"goauthentik.io/outpost-type": str(self.controller.outpost.type),
|
||||||
"goauthentik.io/outpost-uuid": self.controller.outpost.uuid.hex,
|
"goauthentik.io/outpost-uuid": self.controller.outpost.uuid.hex,
|
||||||
|
@ -94,7 +94,7 @@ class DeploymentReconciler(KubernetesObjectReconciler[V1Deployment]):
|
|||||||
meta = self.get_object_meta(name=self.name)
|
meta = self.get_object_meta(name=self.name)
|
||||||
image_name = self.controller.get_container_image()
|
image_name = self.controller.get_container_image()
|
||||||
image_pull_secrets = self.outpost.config.kubernetes_image_pull_secrets
|
image_pull_secrets = self.outpost.config.kubernetes_image_pull_secrets
|
||||||
version = get_full_version()
|
version = get_full_version().replace("+", "-")
|
||||||
return V1Deployment(
|
return V1Deployment(
|
||||||
metadata=meta,
|
metadata=meta,
|
||||||
spec=V1DeploymentSpec(
|
spec=V1DeploymentSpec(
|
||||||
|
@ -13,7 +13,7 @@ if TYPE_CHECKING:
|
|||||||
from authentik.outposts.controllers.kubernetes import KubernetesController
|
from authentik.outposts.controllers.kubernetes import KubernetesController
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class PrometheusServiceMonitorSpecEndpoint:
|
class PrometheusServiceMonitorSpecEndpoint:
|
||||||
"""Prometheus ServiceMonitor endpoint spec"""
|
"""Prometheus ServiceMonitor endpoint spec"""
|
||||||
|
|
||||||
@ -21,14 +21,14 @@ class PrometheusServiceMonitorSpecEndpoint:
|
|||||||
path: str = field(default="/metrics")
|
path: str = field(default="/metrics")
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class PrometheusServiceMonitorSpecSelector:
|
class PrometheusServiceMonitorSpecSelector:
|
||||||
"""Prometheus ServiceMonitor selector spec"""
|
"""Prometheus ServiceMonitor selector spec"""
|
||||||
|
|
||||||
matchLabels: dict
|
matchLabels: dict
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class PrometheusServiceMonitorSpec:
|
class PrometheusServiceMonitorSpec:
|
||||||
"""Prometheus ServiceMonitor spec"""
|
"""Prometheus ServiceMonitor spec"""
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ class PrometheusServiceMonitorSpec:
|
|||||||
selector: PrometheusServiceMonitorSpecSelector
|
selector: PrometheusServiceMonitorSpecSelector
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class PrometheusServiceMonitorMetadata:
|
class PrometheusServiceMonitorMetadata:
|
||||||
"""Prometheus ServiceMonitor metadata"""
|
"""Prometheus ServiceMonitor metadata"""
|
||||||
|
|
||||||
@ -46,7 +46,7 @@ class PrometheusServiceMonitorMetadata:
|
|||||||
labels: dict = field(default_factory=dict)
|
labels: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class PrometheusServiceMonitor:
|
class PrometheusServiceMonitor:
|
||||||
"""Prometheus ServiceMonitor"""
|
"""Prometheus ServiceMonitor"""
|
||||||
|
|
||||||
|
@ -0,0 +1,30 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
(
|
||||||
|
"authentik_policies_reputation",
|
||||||
|
"0007_reputation_authentik_p_identif_9434d7_idx_and_more",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="reputation",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_da493f_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="reputation",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_2ab34f_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="reputation",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_2a8ec7_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -96,7 +96,7 @@ class Reputation(ExpiringModel, SerializerModel):
|
|||||||
verbose_name = _("Reputation Score")
|
verbose_name = _("Reputation Score")
|
||||||
verbose_name_plural = _("Reputation Scores")
|
verbose_name_plural = _("Reputation Scores")
|
||||||
unique_together = ("identifier", "ip")
|
unique_together = ("identifier", "ip")
|
||||||
indexes = [
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
models.Index(fields=["identifier"]),
|
models.Index(fields=["identifier"]),
|
||||||
models.Index(fields=["ip"]),
|
models.Index(fields=["ip"]),
|
||||||
models.Index(fields=["ip", "identifier"]),
|
models.Index(fields=["ip", "identifier"]),
|
||||||
|
@ -0,0 +1,72 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0042_authenticatedsession_authentik_c_expires_08251d_idx_and_more"),
|
||||||
|
("authentik_providers_oauth2", "0026_alter_accesstoken_session_and_more"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="accesstoken",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_9f24a5_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="accesstoken",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_2d9205_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="accesstoken",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_c74005_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authorizationcode",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_f594b2_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authorizationcode",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_6a5e2c_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="authorizationcode",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_c0f353_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="devicetoken",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_961437_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="devicetoken",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_4fd278_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="devicetoken",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_cd6b1c_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="refreshtoken",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_p_expires_c479a7_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="refreshtoken",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_p_expirin_d4d17f_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="refreshtoken",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_p_expirin_acb4a5_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -425,6 +425,7 @@ class AuthorizationCode(SerializerModel, ExpiringModel, BaseGrantModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Authorization Code")
|
verbose_name = _("Authorization Code")
|
||||||
verbose_name_plural = _("Authorization Codes")
|
verbose_name_plural = _("Authorization Codes")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"Authorization code for {self.provider_id} for user {self.user_id}"
|
return f"Authorization code for {self.provider_id} for user {self.user_id}"
|
||||||
@ -453,7 +454,7 @@ class AccessToken(SerializerModel, ExpiringModel, BaseGrantModel):
|
|||||||
_id_token = models.TextField()
|
_id_token = models.TextField()
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
indexes = [
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
HashIndex(fields=["token"]),
|
HashIndex(fields=["token"]),
|
||||||
]
|
]
|
||||||
verbose_name = _("OAuth2 Access Token")
|
verbose_name = _("OAuth2 Access Token")
|
||||||
@ -504,7 +505,7 @@ class RefreshToken(SerializerModel, ExpiringModel, BaseGrantModel):
|
|||||||
)
|
)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
indexes = [
|
indexes = ExpiringModel.Meta.indexes + [
|
||||||
HashIndex(fields=["token"]),
|
HashIndex(fields=["token"]),
|
||||||
]
|
]
|
||||||
verbose_name = _("OAuth2 Refresh Token")
|
verbose_name = _("OAuth2 Refresh Token")
|
||||||
@ -556,6 +557,7 @@ class DeviceToken(ExpiringModel):
|
|||||||
class Meta:
|
class Meta:
|
||||||
verbose_name = _("Device Token")
|
verbose_name = _("Device Token")
|
||||||
verbose_name_plural = _("Device Tokens")
|
verbose_name_plural = _("Device Tokens")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f"Device Token for {self.provider_id}"
|
return f"Device Token for {self.provider_id}"
|
||||||
|
@ -49,7 +49,9 @@ class TesOAuth2DeviceInit(OAuthTestCase):
|
|||||||
kwargs={
|
kwargs={
|
||||||
"flow_slug": self.device_flow.slug,
|
"flow_slug": self.device_flow.slug,
|
||||||
},
|
},
|
||||||
),
|
)
|
||||||
|
+ "?"
|
||||||
|
+ urlencode({"inspector": "available"}),
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_device_init_post(self):
|
def test_device_init_post(self):
|
||||||
@ -63,7 +65,9 @@ class TesOAuth2DeviceInit(OAuthTestCase):
|
|||||||
kwargs={
|
kwargs={
|
||||||
"flow_slug": self.device_flow.slug,
|
"flow_slug": self.device_flow.slug,
|
||||||
},
|
},
|
||||||
),
|
)
|
||||||
|
+ "?"
|
||||||
|
+ urlencode({"inspector": "available"}),
|
||||||
)
|
)
|
||||||
res = self.api_client.get(
|
res = self.api_client.get(
|
||||||
reverse(
|
reverse(
|
||||||
@ -118,7 +122,9 @@ class TesOAuth2DeviceInit(OAuthTestCase):
|
|||||||
kwargs={
|
kwargs={
|
||||||
"flow_slug": provider.authorization_flow.slug,
|
"flow_slug": provider.authorization_flow.slug,
|
||||||
},
|
},
|
||||||
),
|
)
|
||||||
|
+ "?"
|
||||||
|
+ urlencode({"inspector": "available"}),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -150,7 +156,7 @@ class TesOAuth2DeviceInit(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
+ "?"
|
+ "?"
|
||||||
+ urlencode({QS_KEY_CODE: token.user_code}),
|
+ urlencode({QS_KEY_CODE: token.user_code, "inspector": "available"}),
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_device_init_denied(self):
|
def test_device_init_denied(self):
|
||||||
|
@ -12,6 +12,7 @@ from authentik.core.tests.utils import create_test_admin_user, create_test_cert,
|
|||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.providers.oauth2.models import (
|
from authentik.providers.oauth2.models import (
|
||||||
AccessToken,
|
AccessToken,
|
||||||
|
ClientTypes,
|
||||||
IDToken,
|
IDToken,
|
||||||
OAuth2Provider,
|
OAuth2Provider,
|
||||||
RedirectURI,
|
RedirectURI,
|
||||||
@ -108,3 +109,29 @@ class TesOAuth2Revoke(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
self.assertEqual(res.status_code, 401)
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
def test_revoke_public(self):
|
||||||
|
"""Test revoke public client"""
|
||||||
|
self.provider.client_type = ClientTypes.PUBLIC
|
||||||
|
self.provider.save()
|
||||||
|
token: AccessToken = AccessToken.objects.create(
|
||||||
|
provider=self.provider,
|
||||||
|
user=self.user,
|
||||||
|
token=generate_id(),
|
||||||
|
auth_time=timezone.now(),
|
||||||
|
_scope="openid user profile",
|
||||||
|
_id_token=json.dumps(
|
||||||
|
asdict(
|
||||||
|
IDToken("foo", "bar"),
|
||||||
|
)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
auth_public = b64encode(f"{self.provider.client_id}:{generate_id()}".encode()).decode()
|
||||||
|
res = self.client.post(
|
||||||
|
reverse("authentik_providers_oauth2:token-revoke"),
|
||||||
|
HTTP_AUTHORIZATION=f"Basic {auth_public}",
|
||||||
|
data={
|
||||||
|
"token": token.token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
@ -178,12 +178,18 @@ def protected_resource_view(scopes: list[str]):
|
|||||||
return wrapper
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
def authenticate_provider(request: HttpRequest) -> OAuth2Provider | None:
|
def provider_from_request(request: HttpRequest) -> tuple[OAuth2Provider | None, str, str]:
|
||||||
"""Attempt to authenticate via Basic auth of client_id:client_secret"""
|
"""Get provider from Basic auth of client_id:client_secret. Does not perform authentication"""
|
||||||
client_id, client_secret = extract_client_auth(request)
|
client_id, client_secret = extract_client_auth(request)
|
||||||
if client_id == client_secret == "":
|
if client_id == client_secret == "":
|
||||||
return None
|
return None, "", ""
|
||||||
provider: OAuth2Provider | None = OAuth2Provider.objects.filter(client_id=client_id).first()
|
provider: OAuth2Provider | None = OAuth2Provider.objects.filter(client_id=client_id).first()
|
||||||
|
return provider, client_id, client_secret
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate_provider(request: HttpRequest) -> OAuth2Provider | None:
|
||||||
|
"""Attempt to authenticate via Basic auth of client_id:client_secret"""
|
||||||
|
provider, client_id, client_secret = provider_from_request(request)
|
||||||
if not provider:
|
if not provider:
|
||||||
return None
|
return None
|
||||||
if client_id != provider.client_id or client_secret != provider.client_secret:
|
if client_id != provider.client_id or client_secret != provider.client_secret:
|
||||||
|
@ -9,8 +9,12 @@ from django.views.decorators.csrf import csrf_exempt
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.providers.oauth2.errors import TokenRevocationError
|
from authentik.providers.oauth2.errors import TokenRevocationError
|
||||||
from authentik.providers.oauth2.models import AccessToken, OAuth2Provider, RefreshToken
|
from authentik.providers.oauth2.models import AccessToken, ClientTypes, OAuth2Provider, RefreshToken
|
||||||
from authentik.providers.oauth2.utils import TokenResponse, authenticate_provider
|
from authentik.providers.oauth2.utils import (
|
||||||
|
TokenResponse,
|
||||||
|
authenticate_provider,
|
||||||
|
provider_from_request,
|
||||||
|
)
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
@ -27,7 +31,9 @@ class TokenRevocationParams:
|
|||||||
"""Extract required Parameters from HTTP Request"""
|
"""Extract required Parameters from HTTP Request"""
|
||||||
raw_token = request.POST.get("token")
|
raw_token = request.POST.get("token")
|
||||||
|
|
||||||
provider = authenticate_provider(request)
|
provider, _, _ = provider_from_request(request)
|
||||||
|
if provider and provider.client_type == ClientTypes.CONFIDENTIAL:
|
||||||
|
provider = authenticate_provider(request)
|
||||||
if not provider:
|
if not provider:
|
||||||
raise TokenRevocationError("invalid_client")
|
raise TokenRevocationError("invalid_client")
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ if TYPE_CHECKING:
|
|||||||
from authentik.outposts.controllers.kubernetes import KubernetesController
|
from authentik.outposts.controllers.kubernetes import KubernetesController
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class TraefikMiddlewareSpecForwardAuth:
|
class TraefikMiddlewareSpecForwardAuth:
|
||||||
"""traefik middleware forwardAuth spec"""
|
"""traefik middleware forwardAuth spec"""
|
||||||
|
|
||||||
@ -28,14 +28,14 @@ class TraefikMiddlewareSpecForwardAuth:
|
|||||||
trustForwardHeader: bool = field(default=True)
|
trustForwardHeader: bool = field(default=True)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class TraefikMiddlewareSpec:
|
class TraefikMiddlewareSpec:
|
||||||
"""Traefik middleware spec"""
|
"""Traefik middleware spec"""
|
||||||
|
|
||||||
forwardAuth: TraefikMiddlewareSpecForwardAuth
|
forwardAuth: TraefikMiddlewareSpecForwardAuth
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class TraefikMiddlewareMetadata:
|
class TraefikMiddlewareMetadata:
|
||||||
"""Traefik Middleware metadata"""
|
"""Traefik Middleware metadata"""
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ class TraefikMiddlewareMetadata:
|
|||||||
labels: dict = field(default_factory=dict)
|
labels: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass(slots=True)
|
||||||
class TraefikMiddleware:
|
class TraefikMiddleware:
|
||||||
"""Traefik Middleware"""
|
"""Traefik Middleware"""
|
||||||
|
|
||||||
|
@ -16,6 +16,7 @@ from rest_framework.decorators import action
|
|||||||
from rest_framework.fields import CharField, FileField, SerializerMethodField
|
from rest_framework.fields import CharField, FileField, SerializerMethodField
|
||||||
from rest_framework.parsers import MultiPartParser
|
from rest_framework.parsers import MultiPartParser
|
||||||
from rest_framework.permissions import AllowAny
|
from rest_framework.permissions import AllowAny
|
||||||
|
from rest_framework.renderers import BaseRenderer, JSONRenderer
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.serializers import PrimaryKeyRelatedField, ValidationError
|
from rest_framework.serializers import PrimaryKeyRelatedField, ValidationError
|
||||||
@ -38,6 +39,16 @@ from authentik.sources.saml.processors.constants import SAML_BINDING_POST, SAML_
|
|||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
|
|
||||||
|
class RawXMLDataRenderer(BaseRenderer):
|
||||||
|
"""Renderer to allow application/xml as value for 'Accept' in the metadata endpoint."""
|
||||||
|
|
||||||
|
media_type = "application/xml"
|
||||||
|
format = "xml"
|
||||||
|
|
||||||
|
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
class SAMLProviderSerializer(ProviderSerializer):
|
class SAMLProviderSerializer(ProviderSerializer):
|
||||||
"""SAMLProvider Serializer"""
|
"""SAMLProvider Serializer"""
|
||||||
|
|
||||||
@ -54,9 +65,23 @@ class SAMLProviderSerializer(ProviderSerializer):
|
|||||||
if "request" not in self._context:
|
if "request" not in self._context:
|
||||||
return ""
|
return ""
|
||||||
request: HttpRequest = self._context["request"]._request
|
request: HttpRequest = self._context["request"]._request
|
||||||
return request.build_absolute_uri(
|
try:
|
||||||
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": instance.pk}) + "?download"
|
return request.build_absolute_uri(
|
||||||
)
|
reverse(
|
||||||
|
"authentik_providers_saml:metadata-download",
|
||||||
|
kwargs={"application_slug": instance.application.slug},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
except Provider.application.RelatedObjectDoesNotExist:
|
||||||
|
return request.build_absolute_uri(
|
||||||
|
reverse(
|
||||||
|
"authentik_api:samlprovider-metadata",
|
||||||
|
kwargs={
|
||||||
|
"pk": instance.pk,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
+ "?download"
|
||||||
|
)
|
||||||
|
|
||||||
def get_url_sso_post(self, instance: SAMLProvider) -> str:
|
def get_url_sso_post(self, instance: SAMLProvider) -> str:
|
||||||
"""Get SSO Post URL"""
|
"""Get SSO Post URL"""
|
||||||
@ -224,9 +249,21 @@ class SAMLProviderViewSet(UsedByMixin, ModelViewSet):
|
|||||||
],
|
],
|
||||||
description="Optionally force the metadata to only include one binding.",
|
description="Optionally force the metadata to only include one binding.",
|
||||||
),
|
),
|
||||||
|
# Explicitly excluded, because otherwise spectacular automatically
|
||||||
|
# add it when using multiple renderer_classes
|
||||||
|
OpenApiParameter(
|
||||||
|
name="format",
|
||||||
|
exclude=True,
|
||||||
|
required=False,
|
||||||
|
),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@action(methods=["GET"], detail=True, permission_classes=[AllowAny])
|
@action(
|
||||||
|
methods=["GET"],
|
||||||
|
detail=True,
|
||||||
|
permission_classes=[AllowAny],
|
||||||
|
renderer_classes=[JSONRenderer, RawXMLDataRenderer],
|
||||||
|
)
|
||||||
def metadata(self, request: Request, pk: int) -> Response:
|
def metadata(self, request: Request, pk: int) -> Response:
|
||||||
"""Return metadata as XML string"""
|
"""Return metadata as XML string"""
|
||||||
# We don't use self.get_object() on purpose as this view is un-authenticated
|
# We don't use self.get_object() on purpose as this view is un-authenticated
|
||||||
@ -244,9 +281,9 @@ class SAMLProviderViewSet(UsedByMixin, ModelViewSet):
|
|||||||
f'attachment; filename="{provider.name}_authentik_meta.xml"'
|
f'attachment; filename="{provider.name}_authentik_meta.xml"'
|
||||||
)
|
)
|
||||||
return response
|
return response
|
||||||
return Response({"metadata": metadata})
|
return Response({"metadata": metadata}, content_type="application/json")
|
||||||
except Provider.application.RelatedObjectDoesNotExist:
|
except Provider.application.RelatedObjectDoesNotExist:
|
||||||
return Response({"metadata": ""})
|
return Response({"metadata": ""}, content_type="application/json")
|
||||||
|
|
||||||
@permission_required(
|
@permission_required(
|
||||||
None,
|
None,
|
||||||
|
@ -256,7 +256,7 @@ class AssertionProcessor:
|
|||||||
assertion.attrib["IssueInstant"] = self._issue_instant
|
assertion.attrib["IssueInstant"] = self._issue_instant
|
||||||
assertion.append(self.get_issuer())
|
assertion.append(self.get_issuer())
|
||||||
|
|
||||||
if self.provider.signing_kp:
|
if self.provider.signing_kp and self.provider.sign_assertion:
|
||||||
sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
|
sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
|
||||||
self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
|
self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
|
||||||
)
|
)
|
||||||
@ -295,6 +295,18 @@ class AssertionProcessor:
|
|||||||
|
|
||||||
response.append(self.get_issuer())
|
response.append(self.get_issuer())
|
||||||
|
|
||||||
|
if self.provider.signing_kp and self.provider.sign_response:
|
||||||
|
sign_algorithm_transform = SIGN_ALGORITHM_TRANSFORM_MAP.get(
|
||||||
|
self.provider.signature_algorithm, xmlsec.constants.TransformRsaSha1
|
||||||
|
)
|
||||||
|
signature = xmlsec.template.create(
|
||||||
|
response,
|
||||||
|
xmlsec.constants.TransformExclC14N,
|
||||||
|
sign_algorithm_transform,
|
||||||
|
ns=xmlsec.constants.DSigNs,
|
||||||
|
)
|
||||||
|
response.append(signature)
|
||||||
|
|
||||||
status = SubElement(response, f"{{{NS_SAML_PROTOCOL}}}Status")
|
status = SubElement(response, f"{{{NS_SAML_PROTOCOL}}}Status")
|
||||||
status_code = SubElement(status, f"{{{NS_SAML_PROTOCOL}}}StatusCode")
|
status_code = SubElement(status, f"{{{NS_SAML_PROTOCOL}}}StatusCode")
|
||||||
status_code.attrib["Value"] = "urn:oasis:names:tc:SAML:2.0:status:Success"
|
status_code.attrib["Value"] = "urn:oasis:names:tc:SAML:2.0:status:Success"
|
||||||
|
@ -104,6 +104,22 @@ class TestSAMLProviderAPI(APITestCase):
|
|||||||
)
|
)
|
||||||
self.assertEqual(200, response.status_code)
|
self.assertEqual(200, response.status_code)
|
||||||
self.assertIn("Content-Disposition", response)
|
self.assertIn("Content-Disposition", response)
|
||||||
|
# Test download with Accept: application/xml
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": provider.pk})
|
||||||
|
+ "?download",
|
||||||
|
HTTP_ACCEPT="application/xml",
|
||||||
|
)
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
self.assertIn("Content-Disposition", response)
|
||||||
|
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": provider.pk})
|
||||||
|
+ "?download",
|
||||||
|
HTTP_ACCEPT="application/xml;charset=UTF-8",
|
||||||
|
)
|
||||||
|
self.assertEqual(200, response.status_code)
|
||||||
|
self.assertIn("Content-Disposition", response)
|
||||||
|
|
||||||
def test_metadata_invalid(self):
|
def test_metadata_invalid(self):
|
||||||
"""Test metadata export (invalid)"""
|
"""Test metadata export (invalid)"""
|
||||||
@ -121,6 +137,11 @@ class TestSAMLProviderAPI(APITestCase):
|
|||||||
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": "abc"}),
|
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": "abc"}),
|
||||||
)
|
)
|
||||||
self.assertEqual(404, response.status_code)
|
self.assertEqual(404, response.status_code)
|
||||||
|
response = self.client.get(
|
||||||
|
reverse("authentik_api:samlprovider-metadata", kwargs={"pk": provider.pk}),
|
||||||
|
HTTP_ACCEPT="application/invalid-mime-type",
|
||||||
|
)
|
||||||
|
self.assertEqual(406, response.status_code)
|
||||||
|
|
||||||
def test_import_success(self):
|
def test_import_success(self):
|
||||||
"""Test metadata import (success case)"""
|
"""Test metadata import (success case)"""
|
||||||
|
@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
from base64 import b64encode
|
from base64 import b64encode
|
||||||
|
|
||||||
|
from defusedxml.lxml import fromstring
|
||||||
from django.http.request import QueryDict
|
from django.http.request import QueryDict
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
from lxml import etree # nosec
|
||||||
|
|
||||||
from authentik.blueprints.tests import apply_blueprint
|
from authentik.blueprints.tests import apply_blueprint
|
||||||
from authentik.core.tests.utils import create_test_admin_user, create_test_cert, create_test_flow
|
from authentik.core.tests.utils import create_test_admin_user, create_test_cert, create_test_flow
|
||||||
@ -11,12 +13,14 @@ from authentik.crypto.models import CertificateKeyPair
|
|||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.tests.utils import get_request
|
from authentik.lib.tests.utils import get_request
|
||||||
|
from authentik.lib.xml import lxml_from_string
|
||||||
from authentik.providers.saml.models import SAMLPropertyMapping, SAMLProvider
|
from authentik.providers.saml.models import SAMLPropertyMapping, SAMLProvider
|
||||||
from authentik.providers.saml.processors.assertion import AssertionProcessor
|
from authentik.providers.saml.processors.assertion import AssertionProcessor
|
||||||
from authentik.providers.saml.processors.authn_request_parser import AuthNRequestParser
|
from authentik.providers.saml.processors.authn_request_parser import AuthNRequestParser
|
||||||
from authentik.sources.saml.exceptions import MismatchedRequestID
|
from authentik.sources.saml.exceptions import MismatchedRequestID
|
||||||
from authentik.sources.saml.models import SAMLSource
|
from authentik.sources.saml.models import SAMLSource
|
||||||
from authentik.sources.saml.processors.constants import (
|
from authentik.sources.saml.processors.constants import (
|
||||||
|
NS_MAP,
|
||||||
SAML_BINDING_REDIRECT,
|
SAML_BINDING_REDIRECT,
|
||||||
SAML_NAME_ID_FORMAT_EMAIL,
|
SAML_NAME_ID_FORMAT_EMAIL,
|
||||||
SAML_NAME_ID_FORMAT_UNSPECIFIED,
|
SAML_NAME_ID_FORMAT_UNSPECIFIED,
|
||||||
@ -185,6 +189,19 @@ class TestAuthNRequest(TestCase):
|
|||||||
self.assertEqual(response.count(response_proc._assertion_id), 2)
|
self.assertEqual(response.count(response_proc._assertion_id), 2)
|
||||||
self.assertEqual(response.count(response_proc._response_id), 2)
|
self.assertEqual(response.count(response_proc._response_id), 2)
|
||||||
|
|
||||||
|
schema = etree.XMLSchema(
|
||||||
|
etree.parse("schemas/saml-schema-protocol-2.0.xsd", parser=etree.XMLParser()) # nosec
|
||||||
|
)
|
||||||
|
self.assertTrue(schema.validate(lxml_from_string(response)))
|
||||||
|
|
||||||
|
response_xml = fromstring(response)
|
||||||
|
self.assertEqual(
|
||||||
|
len(response_xml.xpath("//saml:Assertion/ds:Signature", namespaces=NS_MAP)), 1
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
len(response_xml.xpath("//samlp:Response/ds:Signature", namespaces=NS_MAP)), 1
|
||||||
|
)
|
||||||
|
|
||||||
# Now parse the response (source)
|
# Now parse the response (source)
|
||||||
http_request.POST = QueryDict(mutable=True)
|
http_request.POST = QueryDict(mutable=True)
|
||||||
http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode()
|
http_request.POST["SAMLResponse"] = b64encode(response.encode()).decode()
|
||||||
|
@ -5,6 +5,7 @@ from django.contrib.auth.models import Permission
|
|||||||
from django.db.models import QuerySet
|
from django.db.models import QuerySet
|
||||||
from django_filters.filters import ModelChoiceFilter
|
from django_filters.filters import ModelChoiceFilter
|
||||||
from django_filters.filterset import FilterSet
|
from django_filters.filterset import FilterSet
|
||||||
|
from django_filters.rest_framework import DjangoFilterBackend
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.fields import (
|
from rest_framework.fields import (
|
||||||
CharField,
|
CharField,
|
||||||
@ -13,6 +14,8 @@ from rest_framework.fields import (
|
|||||||
ReadOnlyField,
|
ReadOnlyField,
|
||||||
SerializerMethodField,
|
SerializerMethodField,
|
||||||
)
|
)
|
||||||
|
from rest_framework.filters import OrderingFilter, SearchFilter
|
||||||
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||||
|
|
||||||
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
@ -92,7 +95,9 @@ class RBACPermissionViewSet(ReadOnlyModelViewSet):
|
|||||||
queryset = Permission.objects.none()
|
queryset = Permission.objects.none()
|
||||||
serializer_class = PermissionSerializer
|
serializer_class = PermissionSerializer
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
|
||||||
filterset_class = PermissionFilter
|
filterset_class = PermissionFilter
|
||||||
|
permission_classes = [IsAuthenticated]
|
||||||
search_fields = [
|
search_fields = [
|
||||||
"codename",
|
"codename",
|
||||||
"content_type__model",
|
"content_type__model",
|
||||||
|
@ -1,10 +1,15 @@
|
|||||||
"""RBAC API Filter"""
|
"""RBAC API Filter"""
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
from django.db.models import QuerySet
|
from django.db.models import QuerySet
|
||||||
|
from django_filters.rest_framework import DjangoFilterBackend
|
||||||
|
from rest_framework.authentication import get_authorization_header
|
||||||
from rest_framework.exceptions import PermissionDenied
|
from rest_framework.exceptions import PermissionDenied
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.views import APIView
|
||||||
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
from rest_framework_guardian.filters import ObjectPermissionsFilter
|
||||||
|
|
||||||
|
from authentik.api.authentication import validate_auth
|
||||||
from authentik.core.models import UserTypes
|
from authentik.core.models import UserTypes
|
||||||
|
|
||||||
|
|
||||||
@ -12,7 +17,7 @@ class ObjectFilter(ObjectPermissionsFilter):
|
|||||||
"""Object permission filter that grants global permission higher priority than
|
"""Object permission filter that grants global permission higher priority than
|
||||||
per-object permissions"""
|
per-object permissions"""
|
||||||
|
|
||||||
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
def filter_queryset(self, request: Request, queryset: QuerySet, view: APIView) -> QuerySet:
|
||||||
permission = self.perm_format % {
|
permission = self.perm_format % {
|
||||||
"app_label": queryset.model._meta.app_label,
|
"app_label": queryset.model._meta.app_label,
|
||||||
"model_name": queryset.model._meta.model_name,
|
"model_name": queryset.model._meta.model_name,
|
||||||
@ -21,6 +26,9 @@ class ObjectFilter(ObjectPermissionsFilter):
|
|||||||
# per-object permissions
|
# per-object permissions
|
||||||
if request.user.has_perm(permission):
|
if request.user.has_perm(permission):
|
||||||
return queryset
|
return queryset
|
||||||
|
# User does not have permissions, but we have an owner field defined, so filter by that
|
||||||
|
if owner_field := getattr(view, "owner_field", None):
|
||||||
|
return queryset.filter(**{owner_field: request.user})
|
||||||
queryset = super().filter_queryset(request, queryset, view)
|
queryset = super().filter_queryset(request, queryset, view)
|
||||||
# Outposts (which are the only objects using internal service accounts)
|
# Outposts (which are the only objects using internal service accounts)
|
||||||
# except requests to return an empty list when they have no objects
|
# except requests to return an empty list when they have no objects
|
||||||
@ -32,3 +40,17 @@ class ObjectFilter(ObjectPermissionsFilter):
|
|||||||
# and also no object permissions assigned (directly or via role)
|
# and also no object permissions assigned (directly or via role)
|
||||||
raise PermissionDenied()
|
raise PermissionDenied()
|
||||||
return queryset
|
return queryset
|
||||||
|
|
||||||
|
|
||||||
|
class SecretKeyFilter(DjangoFilterBackend):
|
||||||
|
"""Allow access to all objects when authenticated with secret key as token.
|
||||||
|
|
||||||
|
Replaces both DjangoFilterBackend and ObjectFilter"""
|
||||||
|
|
||||||
|
def filter_queryset(self, request: Request, queryset: QuerySet, view) -> QuerySet:
|
||||||
|
auth_header = get_authorization_header(request)
|
||||||
|
token = validate_auth(auth_header)
|
||||||
|
if token and token == settings.SECRET_KEY:
|
||||||
|
return queryset
|
||||||
|
queryset = ObjectFilter().filter_queryset(request, queryset, view)
|
||||||
|
return super().filter_queryset(request, queryset, view)
|
||||||
|
@ -15,6 +15,17 @@ class ObjectPermissions(DjangoObjectPermissions):
|
|||||||
lookup = getattr(view, "lookup_url_kwarg", None) or getattr(view, "lookup_field", None)
|
lookup = getattr(view, "lookup_url_kwarg", None) or getattr(view, "lookup_field", None)
|
||||||
if lookup and lookup in view.kwargs:
|
if lookup and lookup in view.kwargs:
|
||||||
return True
|
return True
|
||||||
|
# Legacy behaviour:
|
||||||
|
# Allow creation of objects even without explicit permission
|
||||||
|
queryset = self._queryset(view)
|
||||||
|
required_perms = self.get_required_permissions(request.method, queryset.model)
|
||||||
|
if (
|
||||||
|
len(required_perms) == 1
|
||||||
|
and f"{queryset.model._meta.app_label}.add_{queryset.model._meta.model_name}"
|
||||||
|
in required_perms
|
||||||
|
and getattr(view, "rbac_allow_create_without_perm", False)
|
||||||
|
):
|
||||||
|
return True
|
||||||
return super().has_permission(request, view)
|
return super().has_permission(request, view)
|
||||||
|
|
||||||
def has_object_permission(self, request: Request, view, obj: Model) -> bool:
|
def has_object_permission(self, request: Request, view, obj: Model) -> bool:
|
||||||
@ -24,6 +35,10 @@ class ObjectPermissions(DjangoObjectPermissions):
|
|||||||
# Rank global permissions higher than per-object permissions
|
# Rank global permissions higher than per-object permissions
|
||||||
if request.user.has_perms(perms):
|
if request.user.has_perms(perms):
|
||||||
return True
|
return True
|
||||||
|
# Allow access for owners if configured
|
||||||
|
if owner_field := getattr(view, "owner_field", None):
|
||||||
|
if getattr(obj, owner_field) == request.user:
|
||||||
|
return True
|
||||||
return super().has_object_permission(request, view, obj)
|
return super().has_object_permission(request, view, obj)
|
||||||
|
|
||||||
|
|
||||||
|
@ -18,6 +18,7 @@ from celery.signals import (
|
|||||||
task_prerun,
|
task_prerun,
|
||||||
worker_ready,
|
worker_ready,
|
||||||
)
|
)
|
||||||
|
from celery.worker.control import inspect_command
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db import ProgrammingError
|
from django.db import ProgrammingError
|
||||||
from django_tenants.utils import get_public_schema_name
|
from django_tenants.utils import get_public_schema_name
|
||||||
@ -25,6 +26,7 @@ from structlog.contextvars import STRUCTLOG_KEY_PREFIX
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp
|
from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp
|
||||||
|
|
||||||
|
from authentik import get_full_version
|
||||||
from authentik.lib.sentry import before_send
|
from authentik.lib.sentry import before_send
|
||||||
from authentik.lib.utils.errors import exception_to_string
|
from authentik.lib.utils.errors import exception_to_string
|
||||||
|
|
||||||
@ -159,6 +161,12 @@ class LivenessProbe(bootsteps.StartStopStep):
|
|||||||
HEARTBEAT_FILE.touch()
|
HEARTBEAT_FILE.touch()
|
||||||
|
|
||||||
|
|
||||||
|
@inspect_command(default_timeout=0.2)
|
||||||
|
def ping(state, **kwargs):
|
||||||
|
"""Ping worker(s)."""
|
||||||
|
return {"ok": "pong", "version": get_full_version()}
|
||||||
|
|
||||||
|
|
||||||
CELERY_APP.config_from_object(settings.CELERY)
|
CELERY_APP.config_from_object(settings.CELERY)
|
||||||
|
|
||||||
# Load task modules from all registered Django app configs.
|
# Load task modules from all registered Django app configs.
|
||||||
|
@ -1,10 +1,7 @@
|
|||||||
"""Kerberos Source Serializer"""
|
"""Kerberos Source Serializer"""
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
|
||||||
from authentik.core.api.sources import (
|
from authentik.core.api.sources import (
|
||||||
GroupSourceConnectionSerializer,
|
GroupSourceConnectionSerializer,
|
||||||
GroupSourceConnectionViewSet,
|
GroupSourceConnectionViewSet,
|
||||||
@ -32,9 +29,8 @@ class UserKerberosSourceConnectionViewSet(UsedByMixin, ModelViewSet):
|
|||||||
serializer_class = UserKerberosSourceConnectionSerializer
|
serializer_class = UserKerberosSourceConnectionSerializer
|
||||||
filterset_fields = ["source__slug"]
|
filterset_fields = ["source__slug"]
|
||||||
search_fields = ["source__slug"]
|
search_fields = ["source__slug"]
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
ordering = ["source__slug"]
|
ordering = ["source__slug"]
|
||||||
|
owner_field = "user"
|
||||||
|
|
||||||
|
|
||||||
class GroupKerberosSourceConnectionSerializer(GroupSourceConnectionSerializer):
|
class GroupKerberosSourceConnectionSerializer(GroupSourceConnectionSerializer):
|
||||||
|
@ -28,17 +28,19 @@ class KerberosBackend(InbuiltBackend):
|
|||||||
if "@" in username:
|
if "@" in username:
|
||||||
username, realm = username.rsplit("@", 1)
|
username, realm = username.rsplit("@", 1)
|
||||||
|
|
||||||
user, source = self.auth_user(username, realm, **kwargs)
|
user, source = self.auth_user(request, username, realm, **kwargs)
|
||||||
if user:
|
if user:
|
||||||
self.set_method("kerberos", request, source=source)
|
self.set_method("kerberos", request, source=source)
|
||||||
return user
|
return user
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def auth_user(
|
def auth_user(
|
||||||
self, username: str, realm: str | None, password: str, **filters
|
self, request: HttpRequest, username: str, realm: str | None, password: str, **filters
|
||||||
) -> tuple[User | None, KerberosSource | None]:
|
) -> tuple[User | None, KerberosSource | None]:
|
||||||
sources = KerberosSource.objects.filter(enabled=True)
|
sources = KerberosSource.objects.filter(enabled=True)
|
||||||
user = User.objects.filter(usersourceconnection__source__in=sources, **filters).first()
|
user = User.objects.filter(
|
||||||
|
usersourceconnection__source__in=sources, username=username, **filters
|
||||||
|
).first()
|
||||||
|
|
||||||
if user is not None:
|
if user is not None:
|
||||||
# User found, let's get its connections for the sources that are available
|
# User found, let's get its connections for the sources that are available
|
||||||
@ -74,10 +76,10 @@ class KerberosBackend(InbuiltBackend):
|
|||||||
user=user_source_connection.user,
|
user=user_source_connection.user,
|
||||||
)
|
)
|
||||||
user_source_connection.user.set_password(
|
user_source_connection.user.set_password(
|
||||||
password, sender=user_source_connection.source
|
password, sender=user_source_connection.source, request=request
|
||||||
)
|
)
|
||||||
user_source_connection.user.save()
|
user_source_connection.user.save()
|
||||||
return user, user_source_connection.source
|
return user_source_connection.user, user_source_connection.source
|
||||||
# Password doesn't match, onto next source
|
# Password doesn't match, onto next source
|
||||||
LOGGER.debug(
|
LOGGER.debug(
|
||||||
"failed to kinit, password invalid",
|
"failed to kinit, password invalid",
|
||||||
|
@ -12,6 +12,7 @@ from django.db.models.fields import b64decode
|
|||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from django.shortcuts import reverse
|
from django.shortcuts import reverse
|
||||||
from django.templatetags.static import static
|
from django.templatetags.static import static
|
||||||
|
from django.utils.timezone import now
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
from kadmin import KAdmin, KAdminApiVersion
|
from kadmin import KAdmin, KAdminApiVersion
|
||||||
from kadmin.exceptions import PyKAdminException
|
from kadmin.exceptions import PyKAdminException
|
||||||
@ -173,12 +174,18 @@ class KerberosSource(Source):
|
|||||||
def get_base_user_properties(self, principal: str, **kwargs):
|
def get_base_user_properties(self, principal: str, **kwargs):
|
||||||
localpart, _ = principal.rsplit("@", 1)
|
localpart, _ = principal.rsplit("@", 1)
|
||||||
|
|
||||||
return {
|
properties = {
|
||||||
"username": localpart,
|
"username": localpart,
|
||||||
"type": UserTypes.INTERNAL,
|
"type": UserTypes.INTERNAL,
|
||||||
"path": self.get_user_path(),
|
"path": self.get_user_path(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if "principal_obj" in kwargs:
|
||||||
|
princ_expiry = kwargs["principal_obj"].expire_time
|
||||||
|
properties["is_active"] = princ_expiry is None or princ_expiry > now()
|
||||||
|
|
||||||
|
return properties
|
||||||
|
|
||||||
def get_base_group_properties(self, group_id: str, **kwargs):
|
def get_base_group_properties(self, group_id: str, **kwargs):
|
||||||
return {
|
return {
|
||||||
"name": group_id,
|
"name": group_id,
|
||||||
|
@ -20,13 +20,15 @@ class LDAPBackend(InbuiltBackend):
|
|||||||
return None
|
return None
|
||||||
for source in LDAPSource.objects.filter(enabled=True):
|
for source in LDAPSource.objects.filter(enabled=True):
|
||||||
LOGGER.debug("LDAP Auth attempt", source=source)
|
LOGGER.debug("LDAP Auth attempt", source=source)
|
||||||
user = self.auth_user(source, **kwargs)
|
user = self.auth_user(request, source, **kwargs)
|
||||||
if user:
|
if user:
|
||||||
self.set_method("ldap", request, source=source)
|
self.set_method("ldap", request, source=source)
|
||||||
return user
|
return user
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def auth_user(self, source: LDAPSource, password: str, **filters: str) -> User | None:
|
def auth_user(
|
||||||
|
self, request: HttpRequest, source: LDAPSource, password: str, **filters: str
|
||||||
|
) -> User | None:
|
||||||
"""Try to bind as either user_dn or mail with password.
|
"""Try to bind as either user_dn or mail with password.
|
||||||
Returns True on success, otherwise False"""
|
Returns True on success, otherwise False"""
|
||||||
users = User.objects.filter(**filters)
|
users = User.objects.filter(**filters)
|
||||||
@ -43,7 +45,7 @@ class LDAPBackend(InbuiltBackend):
|
|||||||
if source.password_login_update_internal_password:
|
if source.password_login_update_internal_password:
|
||||||
# Password given successfully binds to LDAP, so we save it in our Database
|
# Password given successfully binds to LDAP, so we save it in our Database
|
||||||
LOGGER.debug("Updating user's password in DB", user=user)
|
LOGGER.debug("Updating user's password in DB", user=user)
|
||||||
user.set_password(password, sender=source)
|
user.set_password(password, sender=source, request=request)
|
||||||
user.save()
|
user.save()
|
||||||
return user
|
return user
|
||||||
# Password doesn't match
|
# Password doesn't match
|
||||||
|
@ -81,7 +81,12 @@ class OAuth2Client(BaseOAuthClient):
|
|||||||
if self.source.source_type.urls_customizable and self.source.access_token_url:
|
if self.source.source_type.urls_customizable and self.source.access_token_url:
|
||||||
access_token_url = self.source.access_token_url
|
access_token_url = self.source.access_token_url
|
||||||
response = self.do_request(
|
response = self.do_request(
|
||||||
"post", access_token_url, data=args, headers=self._default_headers, **request_kwargs
|
"post",
|
||||||
|
access_token_url,
|
||||||
|
auth=(self.get_client_id(), self.get_client_secret()),
|
||||||
|
data=args,
|
||||||
|
headers=self._default_headers,
|
||||||
|
**request_kwargs,
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
except RequestException as exc:
|
except RequestException as exc:
|
||||||
|
@ -88,6 +88,55 @@ class TestSCIMUsers(APITestCase):
|
|||||||
).exists()
|
).exists()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_user_create_duplicate_by_username(self):
|
||||||
|
"""Test user create"""
|
||||||
|
user = create_test_user()
|
||||||
|
username = generate_id()
|
||||||
|
obj1 = {
|
||||||
|
"userName": username,
|
||||||
|
"externalId": generate_id(),
|
||||||
|
"emails": [
|
||||||
|
{
|
||||||
|
"primary": True,
|
||||||
|
"value": user.email,
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
obj2 = obj1.copy()
|
||||||
|
obj2.update({"externalId": generate_id()})
|
||||||
|
response = self.client.post(
|
||||||
|
reverse(
|
||||||
|
"authentik_sources_scim:v2-users",
|
||||||
|
kwargs={
|
||||||
|
"source_slug": self.source.slug,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
data=dumps(obj1),
|
||||||
|
content_type=SCIM_CONTENT_TYPE,
|
||||||
|
HTTP_AUTHORIZATION=f"Bearer {self.source.token.key}",
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
self.assertTrue(
|
||||||
|
SCIMSourceUser.objects.filter(source=self.source, user__username=username).exists()
|
||||||
|
)
|
||||||
|
self.assertTrue(
|
||||||
|
Event.objects.filter(
|
||||||
|
action=EventAction.MODEL_CREATED, user__username=self.source.token.user.username
|
||||||
|
).exists()
|
||||||
|
)
|
||||||
|
response = self.client.post(
|
||||||
|
reverse(
|
||||||
|
"authentik_sources_scim:v2-users",
|
||||||
|
kwargs={
|
||||||
|
"source_slug": self.source.slug,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
data=dumps(obj2),
|
||||||
|
content_type=SCIM_CONTENT_TYPE,
|
||||||
|
HTTP_AUTHORIZATION=f"Bearer {self.source.token.key}",
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 409)
|
||||||
|
|
||||||
def test_user_property_mappings(self):
|
def test_user_property_mappings(self):
|
||||||
"""Test user property_mappings"""
|
"""Test user property_mappings"""
|
||||||
self.source.user_property_mappings.set(
|
self.source.user_property_mappings.set(
|
||||||
|
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from django.db.models import Q
|
||||||
from django.db.transaction import atomic
|
from django.db.transaction import atomic
|
||||||
from django.http import Http404, QueryDict
|
from django.http import Http404, QueryDict
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
@ -113,8 +114,11 @@ class UsersView(SCIMObjectView):
|
|||||||
def post(self, request: Request, **kwargs) -> Response:
|
def post(self, request: Request, **kwargs) -> Response:
|
||||||
"""Create user handler"""
|
"""Create user handler"""
|
||||||
connection = SCIMSourceUser.objects.filter(
|
connection = SCIMSourceUser.objects.filter(
|
||||||
|
Q(
|
||||||
|
Q(user__uuid=request.data.get("id"))
|
||||||
|
| Q(user__username=request.data.get("userName"))
|
||||||
|
),
|
||||||
source=self.source,
|
source=self.source,
|
||||||
user__uuid=request.data.get("id"),
|
|
||||||
).first()
|
).first()
|
||||||
if connection:
|
if connection:
|
||||||
self.logger.debug("Found existing user")
|
self.logger.debug("Found existing user")
|
||||||
|
@ -1,20 +1,18 @@
|
|||||||
"""AuthenticatorDuoStage API Views"""
|
"""AuthenticatorDuoStage API Views"""
|
||||||
|
|
||||||
from django.http import Http404
|
from django.http import Http404
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
from drf_spectacular.utils import OpenApiResponse, extend_schema, inline_serializer
|
||||||
from guardian.shortcuts import get_objects_for_user
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import CharField, ChoiceField, IntegerField
|
from rest_framework.fields import CharField, ChoiceField, IntegerField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.flows.api.stages import StageSerializer
|
from authentik.flows.api.stages import StageSerializer
|
||||||
@ -168,9 +166,11 @@ class AuthenticatorDuoStageViewSet(UsedByMixin, ModelViewSet):
|
|||||||
class DuoDeviceSerializer(ModelSerializer):
|
class DuoDeviceSerializer(ModelSerializer):
|
||||||
"""Serializer for Duo authenticator devices"""
|
"""Serializer for Duo authenticator devices"""
|
||||||
|
|
||||||
|
user = GroupMemberSerializer(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = DuoDevice
|
model = DuoDevice
|
||||||
fields = ["pk", "name"]
|
fields = ["pk", "name", "user"]
|
||||||
depth = 2
|
depth = 2
|
||||||
|
|
||||||
|
|
||||||
@ -189,8 +189,7 @@ class DuoDeviceViewSet(
|
|||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
permission_classes = [OwnerPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
|
|
||||||
class DuoAdminDeviceViewSet(ModelViewSet):
|
class DuoAdminDeviceViewSet(ModelViewSet):
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
"""AuthenticatorSMSStage API Views"""
|
"""AuthenticatorSMSStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.flows.api.stages import StageSerializer
|
from authentik.flows.api.stages import StageSerializer
|
||||||
@ -44,9 +42,11 @@ class AuthenticatorSMSStageViewSet(UsedByMixin, ModelViewSet):
|
|||||||
class SMSDeviceSerializer(ModelSerializer):
|
class SMSDeviceSerializer(ModelSerializer):
|
||||||
"""Serializer for sms authenticator devices"""
|
"""Serializer for sms authenticator devices"""
|
||||||
|
|
||||||
|
user = GroupMemberSerializer(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = SMSDevice
|
model = SMSDevice
|
||||||
fields = ["name", "pk", "phone_number"]
|
fields = ["name", "pk", "phone_number", "user"]
|
||||||
depth = 2
|
depth = 2
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"phone_number": {"read_only": True},
|
"phone_number": {"read_only": True},
|
||||||
@ -65,11 +65,10 @@ class SMSDeviceViewSet(
|
|||||||
|
|
||||||
queryset = SMSDevice.objects.all()
|
queryset = SMSDevice.objects.all()
|
||||||
serializer_class = SMSDeviceSerializer
|
serializer_class = SMSDeviceSerializer
|
||||||
permission_classes = [OwnerPermissions]
|
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
owner_field = "user"
|
||||||
|
|
||||||
|
|
||||||
class SMSAdminDeviceViewSet(ModelViewSet):
|
class SMSAdminDeviceViewSet(ModelViewSet):
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
"""AuthenticatorStaticStage API Views"""
|
"""AuthenticatorStaticStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.flows.api.stages import StageSerializer
|
from authentik.flows.api.stages import StageSerializer
|
||||||
@ -51,10 +49,11 @@ class StaticDeviceSerializer(ModelSerializer):
|
|||||||
"""Serializer for static authenticator devices"""
|
"""Serializer for static authenticator devices"""
|
||||||
|
|
||||||
token_set = StaticDeviceTokenSerializer(many=True, read_only=True)
|
token_set = StaticDeviceTokenSerializer(many=True, read_only=True)
|
||||||
|
user = GroupMemberSerializer(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = StaticDevice
|
model = StaticDevice
|
||||||
fields = ["name", "token_set", "pk"]
|
fields = ["name", "token_set", "pk", "user"]
|
||||||
|
|
||||||
|
|
||||||
class StaticDeviceViewSet(
|
class StaticDeviceViewSet(
|
||||||
@ -69,11 +68,10 @@ class StaticDeviceViewSet(
|
|||||||
|
|
||||||
queryset = StaticDevice.objects.filter(confirmed=True)
|
queryset = StaticDevice.objects.filter(confirmed=True)
|
||||||
serializer_class = StaticDeviceSerializer
|
serializer_class = StaticDeviceSerializer
|
||||||
permission_classes = [OwnerPermissions]
|
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
owner_field = "user"
|
||||||
|
|
||||||
|
|
||||||
class StaticAdminDeviceViewSet(ModelViewSet):
|
class StaticAdminDeviceViewSet(ModelViewSet):
|
||||||
|
@ -1,12 +1,10 @@
|
|||||||
"""AuthenticatorTOTPStage API Views"""
|
"""AuthenticatorTOTPStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.fields import ChoiceField
|
from rest_framework.fields import ChoiceField
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.flows.api.stages import StageSerializer
|
from authentik.flows.api.stages import StageSerializer
|
||||||
@ -40,11 +38,14 @@ class AuthenticatorTOTPStageViewSet(UsedByMixin, ModelViewSet):
|
|||||||
class TOTPDeviceSerializer(ModelSerializer):
|
class TOTPDeviceSerializer(ModelSerializer):
|
||||||
"""Serializer for totp authenticator devices"""
|
"""Serializer for totp authenticator devices"""
|
||||||
|
|
||||||
|
user = GroupMemberSerializer(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = TOTPDevice
|
model = TOTPDevice
|
||||||
fields = [
|
fields = [
|
||||||
"name",
|
"name",
|
||||||
"pk",
|
"pk",
|
||||||
|
"user",
|
||||||
]
|
]
|
||||||
depth = 2
|
depth = 2
|
||||||
|
|
||||||
@ -61,11 +62,10 @@ class TOTPDeviceViewSet(
|
|||||||
|
|
||||||
queryset = TOTPDevice.objects.filter(confirmed=True)
|
queryset = TOTPDevice.objects.filter(confirmed=True)
|
||||||
serializer_class = TOTPDeviceSerializer
|
serializer_class = TOTPDeviceSerializer
|
||||||
permission_classes = [OwnerPermissions]
|
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
|
owner_field = "user"
|
||||||
|
|
||||||
|
|
||||||
class TOTPAdminDeviceViewSet(ModelViewSet):
|
class TOTPAdminDeviceViewSet(ModelViewSet):
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
"""AuthenticatorWebAuthnStage API Views"""
|
"""AuthenticatorWebAuthnStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework.backends import DjangoFilterBackend
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerPermissions
|
from authentik.core.api.groups import GroupMemberSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.stages.authenticator_webauthn.api.device_types import WebAuthnDeviceTypeSerializer
|
from authentik.stages.authenticator_webauthn.api.device_types import WebAuthnDeviceTypeSerializer
|
||||||
@ -16,10 +14,11 @@ class WebAuthnDeviceSerializer(ModelSerializer):
|
|||||||
"""Serializer for WebAuthn authenticator devices"""
|
"""Serializer for WebAuthn authenticator devices"""
|
||||||
|
|
||||||
device_type = WebAuthnDeviceTypeSerializer(read_only=True, allow_null=True)
|
device_type = WebAuthnDeviceTypeSerializer(read_only=True, allow_null=True)
|
||||||
|
user = GroupMemberSerializer(read_only=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = WebAuthnDevice
|
model = WebAuthnDevice
|
||||||
fields = ["pk", "name", "created_on", "device_type", "aaguid"]
|
fields = ["pk", "name", "created_on", "device_type", "aaguid", "user"]
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"aaguid": {"read_only": True},
|
"aaguid": {"read_only": True},
|
||||||
}
|
}
|
||||||
@ -40,8 +39,7 @@ class WebAuthnDeviceViewSet(
|
|||||||
search_fields = ["name"]
|
search_fields = ["name"]
|
||||||
filterset_fields = ["name"]
|
filterset_fields = ["name"]
|
||||||
ordering = ["name"]
|
ordering = ["name"]
|
||||||
permission_classes = [OwnerPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
|
|
||||||
class WebAuthnAdminDeviceViewSet(ModelViewSet):
|
class WebAuthnAdminDeviceViewSet(ModelViewSet):
|
||||||
|
File diff suppressed because one or more lines are too long
@ -1,12 +1,8 @@
|
|||||||
"""ConsentStage API Views"""
|
"""ConsentStage API Views"""
|
||||||
|
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
|
||||||
from guardian.utils import get_anonymous_user
|
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.filters import OrderingFilter, SearchFilter
|
|
||||||
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
from rest_framework.viewsets import GenericViewSet, ModelViewSet
|
||||||
|
|
||||||
from authentik.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
|
||||||
from authentik.core.api.applications import ApplicationSerializer
|
from authentik.core.api.applications import ApplicationSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.users import UserSerializer
|
from authentik.core.api.users import UserSerializer
|
||||||
@ -57,11 +53,4 @@ class UserConsentViewSet(
|
|||||||
filterset_fields = ["user", "application"]
|
filterset_fields = ["user", "application"]
|
||||||
ordering = ["application", "expires"]
|
ordering = ["application", "expires"]
|
||||||
search_fields = ["user__username"]
|
search_fields = ["user__username"]
|
||||||
permission_classes = [OwnerSuperuserPermissions]
|
owner_field = "user"
|
||||||
filter_backends = [OwnerFilter, DjangoFilterBackend, OrderingFilter, SearchFilter]
|
|
||||||
|
|
||||||
def get_queryset(self):
|
|
||||||
user = self.request.user if self.request else get_anonymous_user()
|
|
||||||
if user.is_superuser:
|
|
||||||
return super().get_queryset()
|
|
||||||
return super().get_queryset().filter(user=user.pk)
|
|
||||||
|
@ -0,0 +1,30 @@
|
|||||||
|
# Generated by Django 5.0.10 on 2025-01-13 18:05
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0042_authenticatedsession_authentik_c_expires_08251d_idx_and_more"),
|
||||||
|
("authentik_stages_consent", "0006_alter_userconsent_expires"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="userconsent",
|
||||||
|
index=models.Index(fields=["expires"], name="authentik_s_expires_0e99e8_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="userconsent",
|
||||||
|
index=models.Index(fields=["expiring"], name="authentik_s_expirin_8f51e5_idx"),
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name="userconsent",
|
||||||
|
index=models.Index(
|
||||||
|
fields=["expiring", "expires"], name="authentik_s_expirin_e50090_idx"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -71,3 +71,4 @@ class UserConsent(SerializerModel, ExpiringModel):
|
|||||||
unique_together = (("user", "application", "permissions"),)
|
unique_together = (("user", "application", "permissions"),)
|
||||||
verbose_name = _("User Consent")
|
verbose_name = _("User Consent")
|
||||||
verbose_name_plural = _("User Consents")
|
verbose_name_plural = _("User Consents")
|
||||||
|
indexes = ExpiringModel.Meta.indexes
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user