Compare commits
245 Commits
outposts/f
...
version/20
Author | SHA1 | Date | |
---|---|---|---|
b99ac01228 | |||
15026748d1 | |||
2739376a2a | |||
152121175b | |||
1d57a258f3 | |||
f15cac39c8 | |||
ce77d82b24 | |||
c3fe57197d | |||
267938d435 | |||
6a7c2e0662 | |||
5336afb1b4 | |||
9bb44055a3 | |||
143663d293 | |||
bd54d034e1 | |||
be85eecac5 | |||
24385c9c68 | |||
e141a11475 | |||
b055adec2a | |||
772acb10d6 | |||
a7bf963409 | |||
317afc932a | |||
5e5a74eebf | |||
fa87519536 | |||
0deaf25b1f | |||
47d5fc26cc | |||
9a996e7176 | |||
554a26442d | |||
573517bf0a | |||
2cd68dfa87 | |||
8029a13be1 | |||
6900ffffd8 | |||
873aaf85f9 | |||
9c69f67778 | |||
6cf7a72831 | |||
7e3b325929 | |||
b916b612c7 | |||
b7c5fc3f1e | |||
a3ac5ec183 | |||
d30379ba93 | |||
12815526c1 | |||
ed2f0a2d5e | |||
536d776d02 | |||
f70d6432e7 | |||
cc08bfb18b | |||
79dcc30778 | |||
68a1bcf233 | |||
cd7de4c0b9 | |||
3195a75b9a | |||
886d7832df | |||
a3595a36d2 | |||
28ac00798c | |||
f4b0d6e85c | |||
daa3c91afc | |||
5eba598584 | |||
a6b16ecc68 | |||
a41924939b | |||
0afd3b121e | |||
a58374f065 | |||
8faec99bd6 | |||
6c27a2f783 | |||
78e4c313b5 | |||
f8140e1543 | |||
4405a04b0b | |||
7eb5fa6a24 | |||
216e8aff64 | |||
c91bbecb7b | |||
084b3eb039 | |||
557aadecc0 | |||
33b8c45f5c | |||
52132112f6 | |||
ff1510dedc | |||
c3398004ff | |||
47f09ac285 | |||
259c87fa37 | |||
80bb6c6274 | |||
f8c2fc2ead | |||
ea84ee0222 | |||
a695ffc224 | |||
9e22f007a8 | |||
6299fc7f81 | |||
a032fd529b | |||
ec78e56fbd | |||
ad7dedb61f | |||
8356ceaead | |||
228197ea5e | |||
27d3d4a534 | |||
f2dcbf9b1d | |||
03e39a6557 | |||
454a09d91e | |||
61434c807d | |||
7265a56f05 | |||
95df14106c | |||
91d78b0c7d | |||
6c492fbeee | |||
f7ef8c89c2 | |||
c6c460fb48 | |||
78ecbc097c | |||
7fc350bb0b | |||
3bada52fd6 | |||
847fe6ddee | |||
312f09204b | |||
d76c823268 | |||
c8e074c363 | |||
906faf9cce | |||
c68a42f63b | |||
fd8c1d41db | |||
3704f4ccf4 | |||
eb071d4d90 | |||
1c04dc0986 | |||
639a5c429c | |||
35bae56486 | |||
0a8de6499c | |||
f164fff2e7 | |||
51a56942bc | |||
92fd6a55db | |||
b5b1ed5887 | |||
8ccdbdc370 | |||
ac57d6e820 | |||
eaa3d11df8 | |||
bb0eea1f39 | |||
87f9f85c6d | |||
4728a444b7 | |||
4d58eba027 | |||
35fa8ca3d0 | |||
cf07e930b8 | |||
afd155bbba | |||
0b0beecb49 | |||
0644a5ee3a | |||
f3b4e55af5 | |||
9c25d72d61 | |||
ad2d38fa4a | |||
b1b0cf8a87 | |||
f47b208433 | |||
b958868ea7 | |||
5fd414576b | |||
9d9616138f | |||
99e2c6911c | |||
0fa3fbf416 | |||
5ea54e8f7e | |||
8215ee19c6 | |||
9bddc9b577 | |||
c10a8ecf51 | |||
7acd0558f5 | |||
9f4be4d150 | |||
af9766972d | |||
9efc06e473 | |||
d1566acb4b | |||
3c964a3e71 | |||
01cfec62e7 | |||
cebef6a596 | |||
5fe372e84d | |||
d5a3a7552a | |||
ab17f37f0b | |||
ee883ceccc | |||
7df0e88b9d | |||
53f827b54f | |||
395dc08f05 | |||
080f2ab5e7 | |||
2a2e159a0d | |||
564b2874a9 | |||
8ded11806a | |||
36bd4b1e51 | |||
95a679ab3b | |||
5ca8eefa8b | |||
b0f5c9b010 | |||
6ae9071368 | |||
ab795e6642 | |||
b7b62ba089 | |||
7f0ccc61dd | |||
d5abaed66a | |||
64d611212e | |||
9e9769d7fb | |||
5aa744edca | |||
0a7e2e9f81 | |||
f43c0bc798 | |||
ffd3924095 | |||
ed275bce4a | |||
b99ce890ef | |||
5509bce3d7 | |||
a3f1e7a4d1 | |||
17fb4dab34 | |||
c0f3b56012 | |||
53415d8af8 | |||
ed99b3d98f | |||
6373dd2053 | |||
3f607ee2c8 | |||
da6e74a353 | |||
9b879989fe | |||
b1508b9d01 | |||
4601864f94 | |||
a2994218e4 | |||
0ae53b1ce8 | |||
d5fa9da444 | |||
91da421391 | |||
a1e67377f9 | |||
5ad379f54f | |||
0be95d377a | |||
4da66cdb6b | |||
a28b888ca4 | |||
5ec008d0d3 | |||
b06dbab4ac | |||
ab4d7ba2f0 | |||
ea806daf3e | |||
27e5f45919 | |||
8b17ab9bb0 | |||
9283e02808 | |||
d6b5359b8b | |||
77657b1f33 | |||
131a43033e | |||
fef841a458 | |||
bb8b87fcb3 | |||
f36a5a053f | |||
cc8f52b502 | |||
0b0e08446d | |||
1913b5ec41 | |||
a8332eced6 | |||
af7cc8d42d | |||
5830781a5a | |||
a7f324b96f | |||
494cfc2fea | |||
3af27323de | |||
8a6febaa02 | |||
ecce31ee87 | |||
967a38b7ac | |||
9d1ad104ec | |||
01663468de | |||
5e7731a4aa | |||
cb0fa6beb9 | |||
6f67366dfa | |||
8b7922a5cd | |||
dea44fc74d | |||
dfe8a98849 | |||
54d508ae8c | |||
7b0d8f8991 | |||
b058906074 | |||
4b0566c9d1 | |||
40dfa920e2 | |||
187d5e9b4c | |||
147312c160 | |||
4426cbec34 | |||
e05f028c0a | |||
58a5c69f49 | |||
8c7c60b271 | |||
d8c243bcd2 | |||
f7cc4349d7 |
@ -1,5 +1,5 @@
|
|||||||
[bumpversion]
|
[bumpversion]
|
||||||
current_version = 2023.4.1
|
current_version = 2023.5.5
|
||||||
tag = True
|
tag = True
|
||||||
commit = True
|
commit = True
|
||||||
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)
|
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)
|
||||||
|
12
.github/dependabot.yml
vendored
12
.github/dependabot.yml
vendored
@ -6,8 +6,6 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "ci:"
|
prefix: "ci:"
|
||||||
- package-ecosystem: gomod
|
- package-ecosystem: gomod
|
||||||
@ -16,8 +14,6 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "core:"
|
prefix: "core:"
|
||||||
- package-ecosystem: npm
|
- package-ecosystem: npm
|
||||||
@ -26,8 +22,6 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "web:"
|
prefix: "web:"
|
||||||
- package-ecosystem: npm
|
- package-ecosystem: npm
|
||||||
@ -36,8 +30,6 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "website:"
|
prefix: "website:"
|
||||||
- package-ecosystem: pip
|
- package-ecosystem: pip
|
||||||
@ -46,8 +38,6 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "core:"
|
prefix: "core:"
|
||||||
- package-ecosystem: docker
|
- package-ecosystem: docker
|
||||||
@ -56,7 +46,5 @@ updates:
|
|||||||
interval: daily
|
interval: daily
|
||||||
time: "04:00"
|
time: "04:00"
|
||||||
open-pull-requests-limit: 10
|
open-pull-requests-limit: 10
|
||||||
reviewers:
|
|
||||||
- "@goauthentik/core"
|
|
||||||
commit-message:
|
commit-message:
|
||||||
prefix: "core:"
|
prefix: "core:"
|
||||||
|
23
.github/pull_request_template.md
vendored
23
.github/pull_request_template.md
vendored
@ -1,10 +1,10 @@
|
|||||||
<!--
|
<!--
|
||||||
👋 Hello there! Welcome.
|
👋 Hello there! Welcome.
|
||||||
|
|
||||||
Please check the [Contributing guidelines](https://github.com/goauthentik/authentik/blob/main/CONTRIBUTING.md#how-can-i-contribute).
|
Please check the [Contributing guidelines](https://goauthentik.io/developer-docs/#how-can-i-contribute).
|
||||||
-->
|
-->
|
||||||
|
|
||||||
# Details
|
## Details
|
||||||
|
|
||||||
- **Does this resolve an issue?**
|
- **Does this resolve an issue?**
|
||||||
Resolves #
|
Resolves #
|
||||||
@ -19,6 +19,21 @@ Please check the [Contributing guidelines](https://github.com/goauthentik/authen
|
|||||||
|
|
||||||
- Adds breaking change which causes \<issue\>.
|
- Adds breaking change which causes \<issue\>.
|
||||||
|
|
||||||
## Additional
|
## Checklist
|
||||||
|
|
||||||
Any further notes or comments you want to make.
|
- [ ] Local tests pass (`ak test authentik/`)
|
||||||
|
- [ ] The code has been formatted (`make lint-fix`)
|
||||||
|
|
||||||
|
If an API change has been made
|
||||||
|
|
||||||
|
- [ ] The API schema has been updated (`make gen-build`)
|
||||||
|
|
||||||
|
If changes to the frontend have been made
|
||||||
|
|
||||||
|
- [ ] The code has been formatted (`make web`)
|
||||||
|
- [ ] The translation files have been updated (`make i18n-extract`)
|
||||||
|
|
||||||
|
If applicable
|
||||||
|
|
||||||
|
- [ ] The documentation has been updated
|
||||||
|
- [ ] The documentation has been formatted (`make website`)
|
||||||
|
2
.github/workflows/ci-main.yml
vendored
2
.github/workflows/ci-main.yml
vendored
@ -112,7 +112,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.5.0
|
uses: helm/kind-action@v1.7.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
|
||||||
|
1
.github/workflows/ci-outpost.yml
vendored
1
.github/workflows/ci-outpost.yml
vendored
@ -135,4 +135,5 @@ jobs:
|
|||||||
set -x
|
set -x
|
||||||
export GOOS=${{ matrix.goos }}
|
export GOOS=${{ matrix.goos }}
|
||||||
export GOARCH=${{ matrix.goarch }}
|
export GOARCH=${{ matrix.goarch }}
|
||||||
|
export CGO_ENABLED=0
|
||||||
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
||||||
|
7
.github/workflows/ghcr-retention.yml
vendored
7
.github/workflows/ghcr-retention.yml
vendored
@ -10,6 +10,11 @@ jobs:
|
|||||||
name: Delete old unused container images
|
name: Delete old unused container images
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v1
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
- name: Delete 'dev' containers older than a week
|
- name: Delete 'dev' containers older than a week
|
||||||
uses: snok/container-retention-policy@v2
|
uses: snok/container-retention-policy@v2
|
||||||
with:
|
with:
|
||||||
@ -18,5 +23,5 @@ jobs:
|
|||||||
account-type: org
|
account-type: org
|
||||||
org-name: goauthentik
|
org-name: goauthentik
|
||||||
untagged-only: false
|
untagged-only: false
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
skip-tags: gh-next,gh-main
|
skip-tags: gh-next,gh-main
|
||||||
|
1
.github/workflows/release-publish.yml
vendored
1
.github/workflows/release-publish.yml
vendored
@ -123,6 +123,7 @@ jobs:
|
|||||||
set -x
|
set -x
|
||||||
export GOOS=${{ matrix.goos }}
|
export GOOS=${{ matrix.goos }}
|
||||||
export GOARCH=${{ matrix.goarch }}
|
export GOARCH=${{ matrix.goarch }}
|
||||||
|
export CGO_ENABLED=0
|
||||||
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
go build -tags=outpost_static_embed -v -o ./authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
||||||
- name: Upload binaries to release
|
- name: Upload binaries to release
|
||||||
uses: svenstaro/upload-release-action@v2
|
uses: svenstaro/upload-release-action@v2
|
||||||
|
9
.github/workflows/release-tag.yml
vendored
9
.github/workflows/release-tag.yml
vendored
@ -22,18 +22,23 @@ jobs:
|
|||||||
docker-compose up --no-start
|
docker-compose up --no-start
|
||||||
docker-compose start postgresql redis
|
docker-compose start postgresql redis
|
||||||
docker-compose run -u root server test-all
|
docker-compose run -u root server test-all
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v1
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
- name: Extract version number
|
- name: Extract version number
|
||||||
id: get_version
|
id: get_version
|
||||||
uses: actions/github-script@v6
|
uses: actions/github-script@v6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
github-token: ${{ steps.generate_token.outputs.token }}
|
||||||
script: |
|
script: |
|
||||||
return context.payload.ref.replace(/\/refs\/tags\/version\//, '');
|
return context.payload.ref.replace(/\/refs\/tags\/version\//, '');
|
||||||
- name: Create Release
|
- name: Create Release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: actions/create-release@v1.1.4
|
uses: actions/create-release@v1.1.4
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
|
||||||
with:
|
with:
|
||||||
tag_name: ${{ github.ref }}
|
tag_name: ${{ github.ref }}
|
||||||
release_name: Release ${{ steps.get_version.outputs.result }}
|
release_name: Release ${{ steps.get_version.outputs.result }}
|
||||||
|
34
.github/workflows/translation-advice.yml
vendored
Normal file
34
.github/workflows/translation-advice.yml
vendored
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
name: authentik-translation-advice
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- "!**"
|
||||||
|
- "locale/**"
|
||||||
|
- "web/src/locales/**"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
post-comment:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Find Comment
|
||||||
|
uses: peter-evans/find-comment@v2
|
||||||
|
id: fc
|
||||||
|
with:
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
comment-author: "github-actions[bot]"
|
||||||
|
body-includes: authentik translations instructions
|
||||||
|
- name: Create or update comment
|
||||||
|
uses: peter-evans/create-or-update-comment@v3
|
||||||
|
with:
|
||||||
|
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||||
|
issue-number: ${{ github.event.pull_request.number }}
|
||||||
|
edit-mode: replace
|
||||||
|
body: |
|
||||||
|
### authentik translations instructions
|
||||||
|
|
||||||
|
Thanks for your pull request!
|
||||||
|
|
||||||
|
authentik translations are handled using [Transifex](https://explore.transifex.com/authentik/authentik/). Please edit translations over there and they'll be included automatically.
|
16
.github/workflows/translation-compile.yml
vendored
16
.github/workflows/translation-compile.yml
vendored
@ -3,10 +3,7 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
paths:
|
paths:
|
||||||
- "/locale/"
|
- "locale/**"
|
||||||
pull_request:
|
|
||||||
paths:
|
|
||||||
- "/locale/"
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@ -18,18 +15,23 @@ jobs:
|
|||||||
compile:
|
compile:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v1
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
- name: Setup authentik env
|
- name: Setup authentik env
|
||||||
uses: ./.github/actions/setup
|
uses: ./.github/actions/setup
|
||||||
- name: run compile
|
- name: run compile
|
||||||
run: poetry run ./manage.py compilemessages
|
run: poetry run ak compilemessages
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
uses: peter-evans/create-pull-request@v5
|
uses: peter-evans/create-pull-request@v5
|
||||||
id: cpr
|
id: cpr
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
branch: compile-backend-translation
|
branch: compile-backend-translation
|
||||||
commit-message: "core: compile backend translations"
|
commit-message: "core: compile backend translations"
|
||||||
title: "core: compile backend translations"
|
title: "core: compile backend translations"
|
||||||
|
11
.github/workflows/web-api-publish.yml
vendored
11
.github/workflows/web-api-publish.yml
vendored
@ -9,9 +9,14 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
- id: generate_token
|
||||||
|
uses: tibdex/github-app-token@v1
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.GH_APP_ID }}
|
||||||
|
private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
- uses: actions/setup-node@v3.6.0
|
- uses: actions/setup-node@v3.6.0
|
||||||
with:
|
with:
|
||||||
node-version: "20"
|
node-version: "20"
|
||||||
@ -33,7 +38,7 @@ jobs:
|
|||||||
- uses: peter-evans/create-pull-request@v5
|
- uses: peter-evans/create-pull-request@v5
|
||||||
id: cpr
|
id: cpr
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
branch: update-web-api-client
|
branch: update-web-api-client
|
||||||
commit-message: "web: bump API Client version"
|
commit-message: "web: bump API Client version"
|
||||||
title: "web: bump API Client version"
|
title: "web: bump API Client version"
|
||||||
@ -44,6 +49,6 @@ jobs:
|
|||||||
author: authentik bot <github-bot@goauthentik.io>
|
author: authentik bot <github-bot@goauthentik.io>
|
||||||
- uses: peter-evans/enable-pull-request-automerge@v3
|
- uses: peter-evans/enable-pull-request-automerge@v3
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.BOT_GITHUB_TOKEN }}
|
token: ${{ steps.generate_token.outputs.token }}
|
||||||
pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
pull-request-number: ${{ steps.cpr.outputs.pull-request-number }}
|
||||||
merge-method: squash
|
merge-method: squash
|
||||||
|
5
.vscode/extensions.json
vendored
5
.vscode/extensions.json
vendored
@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"recommendations": [
|
"recommendations": [
|
||||||
"EditorConfig.EditorConfig",
|
|
||||||
"bashmish.es6-string-css",
|
"bashmish.es6-string-css",
|
||||||
"bpruitt-goddard.mermaid-markdown-syntax-highlighting",
|
"bpruitt-goddard.mermaid-markdown-syntax-highlighting",
|
||||||
"dbaeumer.vscode-eslint",
|
"dbaeumer.vscode-eslint",
|
||||||
|
"EditorConfig.EditorConfig",
|
||||||
"esbenp.prettier-vscode",
|
"esbenp.prettier-vscode",
|
||||||
|
"github.vscode-github-actions",
|
||||||
"golang.go",
|
"golang.go",
|
||||||
"Gruntfuggly.todo-tree",
|
"Gruntfuggly.todo-tree",
|
||||||
"mechatroner.rainbow-csv",
|
"mechatroner.rainbow-csv",
|
||||||
@ -15,6 +16,6 @@
|
|||||||
"ms-python.vscode-pylance",
|
"ms-python.vscode-pylance",
|
||||||
"redhat.vscode-yaml",
|
"redhat.vscode-yaml",
|
||||||
"Tobermory.es6-string-html",
|
"Tobermory.es6-string-html",
|
||||||
"unifiedjs.vscode-mdx"
|
"unifiedjs.vscode-mdx",
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
7
.vscode/settings.json
vendored
7
.vscode/settings.json
vendored
@ -48,5 +48,10 @@
|
|||||||
"ignoreCase": false
|
"ignoreCase": false
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"go.testFlags": ["-count=1"]
|
"go.testFlags": [
|
||||||
|
"-count=1"
|
||||||
|
],
|
||||||
|
"github-actions.workflows.pinned.workflows": [
|
||||||
|
".github/workflows/ci-main.yml"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
2
CODEOWNERS
Normal file
2
CODEOWNERS
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
* @goauthentik/core
|
||||||
|
website/docs/security/** @goauthentik/security
|
188
CONTRIBUTING.md
188
CONTRIBUTING.md
@ -1,188 +0,0 @@
|
|||||||
# Contributing to authentik
|
|
||||||
|
|
||||||
:+1::tada: Thanks for taking the time to contribute! :tada::+1:
|
|
||||||
|
|
||||||
The following is a set of guidelines for contributing to authentik and its components, which are hosted in the [goauthentik Organization](https://github.com/goauthentik) on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.
|
|
||||||
|
|
||||||
#### Table Of Contents
|
|
||||||
|
|
||||||
[Code of Conduct](#code-of-conduct)
|
|
||||||
|
|
||||||
[I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question)
|
|
||||||
|
|
||||||
[What should I know before I get started?](#what-should-i-know-before-i-get-started)
|
|
||||||
|
|
||||||
- [The components](#the-components)
|
|
||||||
- [authentik's structure](#authentiks-structure)
|
|
||||||
|
|
||||||
[How Can I Contribute?](#how-can-i-contribute)
|
|
||||||
|
|
||||||
- [Reporting Bugs](#reporting-bugs)
|
|
||||||
- [Suggesting Enhancements](#suggesting-enhancements)
|
|
||||||
- [Your First Code Contribution](#your-first-code-contribution)
|
|
||||||
- [Help with the Docs](#help-with-the-docs)
|
|
||||||
- [Pull Requests](#pull-requests)
|
|
||||||
|
|
||||||
[Styleguides](#styleguides)
|
|
||||||
|
|
||||||
- [Git Commit Messages](#git-commit-messages)
|
|
||||||
- [Python Styleguide](#python-styleguide)
|
|
||||||
- [Documentation Styleguide](#documentation-styleguide)
|
|
||||||
|
|
||||||
## Code of Conduct
|
|
||||||
|
|
||||||
Basically, don't be a dickhead. This is an open-source non-profit project, that is made in the free time of Volunteers. If there's something you dislike or think can be done better, tell us! We'd love to hear any suggestions for improvement.
|
|
||||||
|
|
||||||
## I don't want to read this whole thing I just have a question!!!
|
|
||||||
|
|
||||||
Either [create a question on GitHub](https://github.com/goauthentik/authentik/issues/new?assignees=&labels=question&template=question.md&title=) or join [the Discord server](https://goauthentik.io/discord)
|
|
||||||
|
|
||||||
## What should I know before I get started?
|
|
||||||
|
|
||||||
### The components
|
|
||||||
|
|
||||||
authentik consists of a few larger components:
|
|
||||||
|
|
||||||
- _authentik_ the actual application server, is described below.
|
|
||||||
- _outpost-proxy_ is a Go application based on a forked version of oauth2_proxy, which does identity-aware reverse proxying.
|
|
||||||
- _outpost-ldap_ is a Go LDAP server that uses the _authentik_ application server as its backend
|
|
||||||
- _web_ is the web frontend, both for administrating and using authentik. It is written in TypeScript using lit-html and the PatternFly CSS Library.
|
|
||||||
- _website_ is the Website/documentation, which uses docusaurus.
|
|
||||||
|
|
||||||
### authentik's structure
|
|
||||||
|
|
||||||
authentik is at it's very core a Django project. It consists of many individual django applications. These applications are intended to separate concerns, and they may share code between each other.
|
|
||||||
|
|
||||||
These are the current packages:
|
|
||||||
<a id="authentik-packages"/>
|
|
||||||
|
|
||||||
```
|
|
||||||
authentik
|
|
||||||
├── admin - Administrative tasks and APIs, no models (Version updates, Metrics, system tasks)
|
|
||||||
├── api - General API Configuration (Routes, Schema and general API utilities)
|
|
||||||
├── blueprints - Handle managed models and their state.
|
|
||||||
├── core - Core authentik functionality, central routes, core Models
|
|
||||||
├── crypto - Cryptography, currently used to generate and hold Certificates and Private Keys
|
|
||||||
├── events - Event Log, middleware and signals to generate signals
|
|
||||||
├── flows - Flows, the FlowPlanner and the FlowExecutor, used for all flows for authentication, authorization, etc
|
|
||||||
├── lib - Generic library of functions, few dependencies on other packages.
|
|
||||||
├── outposts - Configure and deploy outposts on kubernetes and docker.
|
|
||||||
├── policies - General PolicyEngine
|
|
||||||
│ ├── dummy - A Dummy policy used for testing
|
|
||||||
│ ├── event_matcher - Match events based on different criteria
|
|
||||||
│ ├── expiry - Check when a user's password was last set
|
|
||||||
│ ├── expression - Execute any arbitrary python code
|
|
||||||
│ ├── password - Check a password against several rules
|
|
||||||
│ └── reputation - Check the user's/client's reputation
|
|
||||||
├── providers
|
|
||||||
│ ├── ldap - Provide LDAP access to authentik users/groups using an outpost
|
|
||||||
│ ├── oauth2 - OIDC-compliant OAuth2 provider
|
|
||||||
│ ├── proxy - Provides an identity-aware proxy using an outpost
|
|
||||||
│ └── saml - SAML2 Provider
|
|
||||||
├── recovery - Generate keys to use in case you lock yourself out
|
|
||||||
├── root - Root django application, contains global settings and routes
|
|
||||||
├── sources
|
|
||||||
│ ├── ldap - Sync LDAP users from OpenLDAP or Active Directory into authentik
|
|
||||||
│ ├── oauth - OAuth1 and OAuth2 Source
|
|
||||||
│ ├── plex - Plex source
|
|
||||||
│ └── saml - SAML2 Source
|
|
||||||
├── stages
|
|
||||||
│ ├── authenticator_duo - Configure a DUO authenticator
|
|
||||||
│ ├── authenticator_static - Configure TOTP backup keys
|
|
||||||
│ ├── authenticator_totp - Configure a TOTP authenticator
|
|
||||||
│ ├── authenticator_validate - Validate any authenticator
|
|
||||||
│ ├── authenticator_webauthn - Configure a WebAuthn authenticator
|
|
||||||
│ ├── captcha - Make the user pass a captcha
|
|
||||||
│ ├── consent - Let the user decide if they want to consent to an action
|
|
||||||
│ ├── deny - Static deny, can be used with policies
|
|
||||||
│ ├── dummy - Dummy stage to test
|
|
||||||
│ ├── email - Send the user an email and block execution until they click the link
|
|
||||||
│ ├── identification - Identify a user with any combination of fields
|
|
||||||
│ ├── invitation - Invitation system to limit flows to certain users
|
|
||||||
│ ├── password - Password authentication
|
|
||||||
│ ├── prompt - Arbitrary prompts
|
|
||||||
│ ├── user_delete - Delete the currently pending user
|
|
||||||
│ ├── user_login - Login the currently pending user
|
|
||||||
│ ├── user_logout - Logout the currently pending user
|
|
||||||
│ └── user_write - Write any currenetly pending data to the user.
|
|
||||||
└── tenants - Soft tennancy, configure defaults and branding per domain
|
|
||||||
```
|
|
||||||
|
|
||||||
This django project is running in gunicorn, which spawns multiple workers and threads. Gunicorn is run from a lightweight Go application which reverse-proxies it, handles static files and will eventually gain more functionality as more code is migrated to go.
|
|
||||||
|
|
||||||
There are also several background tasks which run in Celery, the root celery application is defined in `authentik.root.celery`.
|
|
||||||
|
|
||||||
## How Can I Contribute?
|
|
||||||
|
|
||||||
### Reporting Bugs
|
|
||||||
|
|
||||||
This section guides you through submitting a bug report for authentik. Following these guidelines helps maintainers and the community understand your report, reproduce the behavior, and find related reports.
|
|
||||||
|
|
||||||
Whenever authentik encounters an error, it will be logged as an Event with the type `system_exception`. This event type has a button to directly open a pre-filled GitHub issue form.
|
|
||||||
|
|
||||||
This form will have the full stack trace of the error that occurred and shouldn't contain any sensitive data.
|
|
||||||
|
|
||||||
### Suggesting Enhancements
|
|
||||||
|
|
||||||
This section guides you through submitting an enhancement suggestion for authentik, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion and find related suggestions.
|
|
||||||
|
|
||||||
When you are creating an enhancement suggestion, please fill in [the template](https://github.com/goauthentik/authentik/issues/new?assignees=&labels=enhancement&template=feature_request.md&title=), including the steps that you imagine you would take if the feature you're requesting existed.
|
|
||||||
|
|
||||||
### Your First Code Contribution
|
|
||||||
|
|
||||||
#### Local development
|
|
||||||
|
|
||||||
authentik can be run locally, all though depending on which part you want to work on, different pre-requisites are required.
|
|
||||||
|
|
||||||
This is documented in the [developer docs](https://goauthentik.io/developer-docs/?utm_source=github)
|
|
||||||
|
|
||||||
### Help with the Docs
|
|
||||||
Contributions to the technical documentation are greatly appreciated. Open a PR if you have improvements to make or new content to add. If you have questions or suggestions about the documentation, open an Issue. No contribution is too small.
|
|
||||||
|
|
||||||
### Pull Requests
|
|
||||||
|
|
||||||
The process described here has several goals:
|
|
||||||
|
|
||||||
- Maintain authentik's quality
|
|
||||||
- Fix problems that are important to users
|
|
||||||
- Engage the community in working toward the best possible authentik
|
|
||||||
- Enable a sustainable system for authentik's maintainers to review contributions
|
|
||||||
|
|
||||||
Please follow these steps to have your contribution considered by the maintainers:
|
|
||||||
|
|
||||||
1. Follow the [styleguides](#styleguides)
|
|
||||||
2. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing <details><summary>What if the status checks are failing?</summary>If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite.</details>
|
|
||||||
3. Ensure your Code has tests. While it is not always possible to test every single case, the majority of the code should be tested.
|
|
||||||
|
|
||||||
While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted.
|
|
||||||
|
|
||||||
## Styleguides
|
|
||||||
|
|
||||||
### PR naming
|
|
||||||
|
|
||||||
- Use the format of `<package>: <verb> <description>`
|
|
||||||
- See [here](#authentik-packages) for `package`
|
|
||||||
- Example: `providers/saml2: fix parsing of requests`
|
|
||||||
|
|
||||||
### Git Commit Messages
|
|
||||||
|
|
||||||
- Use the format of `<package>: <verb> <description>`
|
|
||||||
- See [here](#authentik-packages) for `package`
|
|
||||||
- Example: `providers/saml2: fix parsing of requests`
|
|
||||||
- Reference issues and pull requests liberally after the first line
|
|
||||||
- Naming of commits within a PR does not need to adhere to the guidelines as we squash merge PRs
|
|
||||||
|
|
||||||
### Python Styleguide
|
|
||||||
|
|
||||||
All Python code is linted with [black](https://black.readthedocs.io/en/stable/), [PyLint](https://www.pylint.org/) and [isort](https://pycqa.github.io/isort/).
|
|
||||||
|
|
||||||
authentik runs on Python 3.9 at the time of writing this.
|
|
||||||
|
|
||||||
- Use native type-annotations wherever possible.
|
|
||||||
- Add meaningful docstrings when possible.
|
|
||||||
- Ensure any database migrations work properly from the last stable version (this is checked via CI)
|
|
||||||
- If your code changes central functions, make sure nothing else is broken.
|
|
||||||
|
|
||||||
### Documentation Styleguide
|
|
||||||
|
|
||||||
- Use [MDX](https://mdxjs.com/) whenever appropriate.
|
|
1
CONTRIBUTING.md
Symbolic link
1
CONTRIBUTING.md
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
website/developer-docs/index.md
|
@ -7,7 +7,7 @@ COPY ./SECURITY.md /work/
|
|||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
WORKDIR /work/website
|
WORKDIR /work/website
|
||||||
RUN npm ci && npm run build-docs-only
|
RUN npm ci --include=dev && npm run build-docs-only
|
||||||
|
|
||||||
# Stage 2: Build webui
|
# Stage 2: Build webui
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/node:20 as web-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/node:20 as web-builder
|
||||||
@ -17,7 +17,7 @@ COPY ./website /work/website/
|
|||||||
|
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
WORKDIR /work/web
|
WORKDIR /work/web
|
||||||
RUN npm ci && npm run build
|
RUN npm ci --include=dev && npm run build
|
||||||
|
|
||||||
# Stage 3: Poetry to requirements.txt export
|
# Stage 3: Poetry to requirements.txt export
|
||||||
FROM docker.io/python:3.11.3-slim-bullseye AS poetry-locker
|
FROM docker.io/python:3.11.3-slim-bullseye AS poetry-locker
|
||||||
@ -31,7 +31,7 @@ RUN pip install --no-cache-dir poetry && \
|
|||||||
poetry export -f requirements.txt --dev --output requirements-dev.txt
|
poetry export -f requirements.txt --dev --output requirements-dev.txt
|
||||||
|
|
||||||
# Stage 4: Build go proxy
|
# Stage 4: Build go proxy
|
||||||
FROM docker.io/golang:1.20.3-bullseye AS go-builder
|
FROM docker.io/golang:1.20.4-bullseye AS go-builder
|
||||||
|
|
||||||
WORKDIR /work
|
WORKDIR /work
|
||||||
|
|
||||||
@ -47,11 +47,12 @@ COPY ./go.sum /work/go.sum
|
|||||||
RUN go build -o /work/authentik ./cmd/server/
|
RUN go build -o /work/authentik ./cmd/server/
|
||||||
|
|
||||||
# Stage 5: MaxMind GeoIP
|
# Stage 5: MaxMind GeoIP
|
||||||
FROM docker.io/maxmindinc/geoipupdate:v5.0 as geoip
|
FROM ghcr.io/maxmind/geoipupdate:v5.1 as geoip
|
||||||
|
|
||||||
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City"
|
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City"
|
||||||
ENV GEOIPUPDATE_VERBOSE="true"
|
ENV GEOIPUPDATE_VERBOSE="true"
|
||||||
|
|
||||||
|
USER root
|
||||||
RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
|
RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
|
||||||
--mount=type=secret,id=GEOIPUPDATE_LICENSE_KEY \
|
--mount=type=secret,id=GEOIPUPDATE_LICENSE_KEY \
|
||||||
mkdir -p /usr/share/GeoIP && \
|
mkdir -p /usr/share/GeoIP && \
|
||||||
|
2
Makefile
2
Makefile
@ -206,6 +206,8 @@ install: web-install website-install
|
|||||||
|
|
||||||
dev-reset:
|
dev-reset:
|
||||||
dropdb -U postgres -h localhost authentik
|
dropdb -U postgres -h localhost authentik
|
||||||
|
# Also remove the test-db if it exists
|
||||||
|
dropdb -U postgres -h localhost test_authentik || true
|
||||||
createdb -U postgres -h localhost authentik
|
createdb -U postgres -h localhost authentik
|
||||||
redis-cli -n 0 flushall
|
redis-cli -n 0 flushall
|
||||||
make migrate
|
make migrate
|
||||||
|
@ -6,8 +6,8 @@ Authentik takes security very seriously. We follow the rules of [responsible dis
|
|||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported |
|
||||||
| --------- | ------------------ |
|
| --------- | ------------------ |
|
||||||
| 2023.2.x | :white_check_mark: |
|
| 2023.4.x | :white_check_mark: |
|
||||||
| 2023.3.x | :white_check_mark: |
|
| 2023.5.x | :white_check_mark: |
|
||||||
|
|
||||||
## Reporting a Vulnerability
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
from os import environ
|
from os import environ
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
__version__ = "2023.4.1"
|
__version__ = "2023.5.5"
|
||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
"""authentik administration overview"""
|
"""authentik administration overview"""
|
||||||
import os
|
|
||||||
import platform
|
import platform
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from sys import version as python_version
|
from sys import version as python_version
|
||||||
@ -34,7 +33,6 @@ class RuntimeDict(TypedDict):
|
|||||||
class SystemSerializer(PassiveSerializer):
|
class SystemSerializer(PassiveSerializer):
|
||||||
"""Get system information."""
|
"""Get system information."""
|
||||||
|
|
||||||
env = SerializerMethodField()
|
|
||||||
http_headers = SerializerMethodField()
|
http_headers = SerializerMethodField()
|
||||||
http_host = SerializerMethodField()
|
http_host = SerializerMethodField()
|
||||||
http_is_secure = SerializerMethodField()
|
http_is_secure = SerializerMethodField()
|
||||||
@ -43,10 +41,6 @@ class SystemSerializer(PassiveSerializer):
|
|||||||
server_time = SerializerMethodField()
|
server_time = SerializerMethodField()
|
||||||
embedded_outpost_host = SerializerMethodField()
|
embedded_outpost_host = SerializerMethodField()
|
||||||
|
|
||||||
def get_env(self, request: Request) -> dict[str, str]:
|
|
||||||
"""Get Environment"""
|
|
||||||
return os.environ.copy()
|
|
||||||
|
|
||||||
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 = {}
|
||||||
|
22
authentik/admin/urls.py
Normal file
22
authentik/admin/urls.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from authentik.admin.api.meta import AppsViewSet
|
||||||
|
from authentik.admin.api.metrics import AdministrationMetricsViewSet
|
||||||
|
from authentik.admin.api.system import SystemView
|
||||||
|
from authentik.admin.api.tasks import TaskViewSet
|
||||||
|
from authentik.admin.api.version import VersionView
|
||||||
|
from authentik.admin.api.workers import WorkerView
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("admin/system_tasks", TaskViewSet, "admin_system_tasks"),
|
||||||
|
("admin/apps", AppsViewSet, "apps"),
|
||||||
|
path(
|
||||||
|
"admin/metrics/",
|
||||||
|
AdministrationMetricsViewSet.as_view(),
|
||||||
|
name="admin_metrics",
|
||||||
|
),
|
||||||
|
path("admin/version/", VersionView.as_view(), name="admin_version"),
|
||||||
|
path("admin/workers/", WorkerView.as_view(), name="admin_workers"),
|
||||||
|
path("admin/system/", SystemView.as_view(), name="admin_system"),
|
||||||
|
]
|
@ -1,4 +1,5 @@
|
|||||||
"""API Authentication"""
|
"""API Authentication"""
|
||||||
|
from hmac import compare_digest
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@ -78,7 +79,7 @@ def token_secret_key(value: str) -> Optional[User]:
|
|||||||
and return the service account for the managed outpost"""
|
and return the service account for the managed outpost"""
|
||||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
|
|
||||||
if value != settings.SECRET_KEY:
|
if not compare_digest(value, settings.SECRET_KEY):
|
||||||
return None
|
return None
|
||||||
outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
|
outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
|
||||||
if not outposts:
|
if not outposts:
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
"""core Configs API"""
|
"""core Configs API"""
|
||||||
from os import path
|
from pathlib import Path
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.db import models
|
from django.db import models
|
||||||
@ -63,7 +63,7 @@ class ConfigView(APIView):
|
|||||||
"""Get all capabilities this server instance supports"""
|
"""Get all capabilities this server instance supports"""
|
||||||
caps = []
|
caps = []
|
||||||
deb_test = settings.DEBUG or settings.TEST
|
deb_test = settings.DEBUG or settings.TEST
|
||||||
if path.ismount(settings.MEDIA_ROOT) or deb_test:
|
if Path(settings.MEDIA_ROOT).is_mount() or deb_test:
|
||||||
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
caps.append(Capabilities.CAN_SAVE_MEDIA)
|
||||||
if GEOIP_READER.enabled:
|
if GEOIP_READER.enabled:
|
||||||
caps.append(Capabilities.CAN_GEO_IP)
|
caps.append(Capabilities.CAN_GEO_IP)
|
||||||
|
@ -1,269 +1,50 @@
|
|||||||
"""api v3 urls"""
|
"""api v3 urls"""
|
||||||
|
from importlib import import_module
|
||||||
|
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
from django.urls.resolvers import URLPattern
|
||||||
from django.views.decorators.cache import cache_page
|
from django.views.decorators.cache import cache_page
|
||||||
from drf_spectacular.views import SpectacularAPIView
|
from drf_spectacular.views import SpectacularAPIView
|
||||||
from rest_framework import routers
|
from rest_framework import routers
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.admin.api.meta import AppsViewSet
|
|
||||||
from authentik.admin.api.metrics import AdministrationMetricsViewSet
|
|
||||||
from authentik.admin.api.system import SystemView
|
|
||||||
from authentik.admin.api.tasks import TaskViewSet
|
|
||||||
from authentik.admin.api.version import VersionView
|
|
||||||
from authentik.admin.api.workers import WorkerView
|
|
||||||
from authentik.api.v3.config import ConfigView
|
from authentik.api.v3.config import ConfigView
|
||||||
from authentik.api.views import APIBrowserView
|
from authentik.api.views import APIBrowserView
|
||||||
from authentik.blueprints.api import BlueprintInstanceViewSet
|
from authentik.lib.utils.reflection import get_apps
|
||||||
from authentik.core.api.applications import ApplicationViewSet
|
|
||||||
from authentik.core.api.authenticated_sessions import AuthenticatedSessionViewSet
|
LOGGER = get_logger()
|
||||||
from authentik.core.api.devices import AdminDeviceViewSet, DeviceViewSet
|
|
||||||
from authentik.core.api.groups import GroupViewSet
|
|
||||||
from authentik.core.api.propertymappings import PropertyMappingViewSet
|
|
||||||
from authentik.core.api.providers import ProviderViewSet
|
|
||||||
from authentik.core.api.sources import SourceViewSet, UserSourceConnectionViewSet
|
|
||||||
from authentik.core.api.tokens import TokenViewSet
|
|
||||||
from authentik.core.api.users import UserViewSet
|
|
||||||
from authentik.crypto.api import CertificateKeyPairViewSet
|
|
||||||
from authentik.events.api.events import EventViewSet
|
|
||||||
from authentik.events.api.notification_mappings import NotificationWebhookMappingViewSet
|
|
||||||
from authentik.events.api.notification_rules import NotificationRuleViewSet
|
|
||||||
from authentik.events.api.notification_transports import NotificationTransportViewSet
|
|
||||||
from authentik.events.api.notifications import NotificationViewSet
|
|
||||||
from authentik.flows.api.bindings import FlowStageBindingViewSet
|
|
||||||
from authentik.flows.api.flows import FlowViewSet
|
|
||||||
from authentik.flows.api.stages import StageViewSet
|
|
||||||
from authentik.flows.views.executor import FlowExecutorView
|
|
||||||
from authentik.flows.views.inspector import FlowInspectorView
|
|
||||||
from authentik.outposts.api.outposts import OutpostViewSet
|
|
||||||
from authentik.outposts.api.service_connections import (
|
|
||||||
DockerServiceConnectionViewSet,
|
|
||||||
KubernetesServiceConnectionViewSet,
|
|
||||||
ServiceConnectionViewSet,
|
|
||||||
)
|
|
||||||
from authentik.policies.api.bindings import PolicyBindingViewSet
|
|
||||||
from authentik.policies.api.policies import PolicyViewSet
|
|
||||||
from authentik.policies.dummy.api import DummyPolicyViewSet
|
|
||||||
from authentik.policies.event_matcher.api import EventMatcherPolicyViewSet
|
|
||||||
from authentik.policies.expiry.api import PasswordExpiryPolicyViewSet
|
|
||||||
from authentik.policies.expression.api import ExpressionPolicyViewSet
|
|
||||||
from authentik.policies.password.api import PasswordPolicyViewSet
|
|
||||||
from authentik.policies.reputation.api import ReputationPolicyViewSet, ReputationViewSet
|
|
||||||
from authentik.providers.ldap.api import LDAPOutpostConfigViewSet, LDAPProviderViewSet
|
|
||||||
from authentik.providers.oauth2.api.providers import OAuth2ProviderViewSet
|
|
||||||
from authentik.providers.oauth2.api.scopes import ScopeMappingViewSet
|
|
||||||
from authentik.providers.oauth2.api.tokens import (
|
|
||||||
AccessTokenViewSet,
|
|
||||||
AuthorizationCodeViewSet,
|
|
||||||
RefreshTokenViewSet,
|
|
||||||
)
|
|
||||||
from authentik.providers.proxy.api import ProxyOutpostConfigViewSet, ProxyProviderViewSet
|
|
||||||
from authentik.providers.radius.api import RadiusOutpostConfigViewSet, RadiusProviderViewSet
|
|
||||||
from authentik.providers.saml.api.property_mapping import SAMLPropertyMappingViewSet
|
|
||||||
from authentik.providers.saml.api.providers import SAMLProviderViewSet
|
|
||||||
from authentik.providers.scim.api.property_mapping import SCIMMappingViewSet
|
|
||||||
from authentik.providers.scim.api.providers import SCIMProviderViewSet
|
|
||||||
from authentik.sources.ldap.api import LDAPPropertyMappingViewSet, LDAPSourceViewSet
|
|
||||||
from authentik.sources.oauth.api.source import OAuthSourceViewSet
|
|
||||||
from authentik.sources.oauth.api.source_connection import UserOAuthSourceConnectionViewSet
|
|
||||||
from authentik.sources.plex.api.source import PlexSourceViewSet
|
|
||||||
from authentik.sources.plex.api.source_connection import PlexSourceConnectionViewSet
|
|
||||||
from authentik.sources.saml.api.source import SAMLSourceViewSet
|
|
||||||
from authentik.sources.saml.api.source_connection import UserSAMLSourceConnectionViewSet
|
|
||||||
from authentik.stages.authenticator_duo.api import (
|
|
||||||
AuthenticatorDuoStageViewSet,
|
|
||||||
DuoAdminDeviceViewSet,
|
|
||||||
DuoDeviceViewSet,
|
|
||||||
)
|
|
||||||
from authentik.stages.authenticator_sms.api import (
|
|
||||||
AuthenticatorSMSStageViewSet,
|
|
||||||
SMSAdminDeviceViewSet,
|
|
||||||
SMSDeviceViewSet,
|
|
||||||
)
|
|
||||||
from authentik.stages.authenticator_static.api import (
|
|
||||||
AuthenticatorStaticStageViewSet,
|
|
||||||
StaticAdminDeviceViewSet,
|
|
||||||
StaticDeviceViewSet,
|
|
||||||
)
|
|
||||||
from authentik.stages.authenticator_totp.api import (
|
|
||||||
AuthenticatorTOTPStageViewSet,
|
|
||||||
TOTPAdminDeviceViewSet,
|
|
||||||
TOTPDeviceViewSet,
|
|
||||||
)
|
|
||||||
from authentik.stages.authenticator_validate.api import AuthenticatorValidateStageViewSet
|
|
||||||
from authentik.stages.authenticator_webauthn.api import (
|
|
||||||
AuthenticateWebAuthnStageViewSet,
|
|
||||||
WebAuthnAdminDeviceViewSet,
|
|
||||||
WebAuthnDeviceViewSet,
|
|
||||||
)
|
|
||||||
from authentik.stages.captcha.api import CaptchaStageViewSet
|
|
||||||
from authentik.stages.consent.api import ConsentStageViewSet, UserConsentViewSet
|
|
||||||
from authentik.stages.deny.api import DenyStageViewSet
|
|
||||||
from authentik.stages.dummy.api import DummyStageViewSet
|
|
||||||
from authentik.stages.email.api import EmailStageViewSet
|
|
||||||
from authentik.stages.identification.api import IdentificationStageViewSet
|
|
||||||
from authentik.stages.invitation.api import InvitationStageViewSet, InvitationViewSet
|
|
||||||
from authentik.stages.password.api import PasswordStageViewSet
|
|
||||||
from authentik.stages.prompt.api import PromptStageViewSet, PromptViewSet
|
|
||||||
from authentik.stages.user_delete.api import UserDeleteStageViewSet
|
|
||||||
from authentik.stages.user_login.api import UserLoginStageViewSet
|
|
||||||
from authentik.stages.user_logout.api import UserLogoutStageViewSet
|
|
||||||
from authentik.stages.user_write.api import UserWriteStageViewSet
|
|
||||||
from authentik.tenants.api import TenantViewSet
|
|
||||||
|
|
||||||
router = routers.DefaultRouter()
|
router = routers.DefaultRouter()
|
||||||
router.include_format_suffixes = False
|
router.include_format_suffixes = False
|
||||||
|
|
||||||
router.register("admin/system_tasks", TaskViewSet, basename="admin_system_tasks")
|
_other_urls = []
|
||||||
router.register("admin/apps", AppsViewSet, basename="apps")
|
for _authentik_app in get_apps():
|
||||||
|
try:
|
||||||
|
api_urls = import_module(f"{_authentik_app.name}.urls")
|
||||||
|
except (ModuleNotFoundError, ImportError):
|
||||||
|
continue
|
||||||
|
if not hasattr(api_urls, "api_urlpatterns"):
|
||||||
|
continue
|
||||||
|
urls: list = getattr(api_urls, "api_urlpatterns")
|
||||||
|
for url in urls:
|
||||||
|
if isinstance(url, URLPattern):
|
||||||
|
_other_urls.append(url)
|
||||||
|
else:
|
||||||
|
router.register(*url)
|
||||||
|
LOGGER.debug(
|
||||||
|
"Mounted API URLs",
|
||||||
|
app_name=_authentik_app.name,
|
||||||
|
)
|
||||||
|
|
||||||
router.register("core/authenticated_sessions", AuthenticatedSessionViewSet)
|
|
||||||
router.register("core/applications", ApplicationViewSet)
|
|
||||||
router.register("core/groups", GroupViewSet)
|
|
||||||
router.register("core/users", UserViewSet)
|
|
||||||
router.register("core/user_consent", UserConsentViewSet)
|
|
||||||
router.register("core/tokens", TokenViewSet)
|
|
||||||
router.register("core/tenants", TenantViewSet)
|
|
||||||
|
|
||||||
router.register("outposts/instances", OutpostViewSet)
|
|
||||||
router.register("outposts/service_connections/all", ServiceConnectionViewSet)
|
|
||||||
router.register("outposts/service_connections/docker", DockerServiceConnectionViewSet)
|
|
||||||
router.register("outposts/service_connections/kubernetes", KubernetesServiceConnectionViewSet)
|
|
||||||
router.register("outposts/proxy", ProxyOutpostConfigViewSet)
|
|
||||||
router.register("outposts/ldap", LDAPOutpostConfigViewSet)
|
|
||||||
router.register("outposts/radius", RadiusOutpostConfigViewSet)
|
|
||||||
|
|
||||||
router.register("flows/instances", FlowViewSet)
|
|
||||||
router.register("flows/bindings", FlowStageBindingViewSet)
|
|
||||||
|
|
||||||
router.register("crypto/certificatekeypairs", CertificateKeyPairViewSet)
|
|
||||||
|
|
||||||
router.register("events/events", EventViewSet)
|
|
||||||
router.register("events/notifications", NotificationViewSet)
|
|
||||||
router.register("events/transports", NotificationTransportViewSet)
|
|
||||||
router.register("events/rules", NotificationRuleViewSet)
|
|
||||||
|
|
||||||
router.register("managed/blueprints", BlueprintInstanceViewSet)
|
|
||||||
|
|
||||||
router.register("sources/all", SourceViewSet)
|
|
||||||
router.register("sources/user_connections/all", UserSourceConnectionViewSet)
|
|
||||||
router.register("sources/user_connections/oauth", UserOAuthSourceConnectionViewSet)
|
|
||||||
router.register("sources/user_connections/plex", PlexSourceConnectionViewSet)
|
|
||||||
router.register("sources/user_connections/saml", UserSAMLSourceConnectionViewSet)
|
|
||||||
router.register("sources/ldap", LDAPSourceViewSet)
|
|
||||||
router.register("sources/saml", SAMLSourceViewSet)
|
|
||||||
router.register("sources/oauth", OAuthSourceViewSet)
|
|
||||||
router.register("sources/plex", PlexSourceViewSet)
|
|
||||||
|
|
||||||
router.register("policies/all", PolicyViewSet)
|
|
||||||
router.register("policies/bindings", PolicyBindingViewSet)
|
|
||||||
router.register("policies/expression", ExpressionPolicyViewSet)
|
|
||||||
router.register("policies/event_matcher", EventMatcherPolicyViewSet)
|
|
||||||
router.register("policies/password_expiry", PasswordExpiryPolicyViewSet)
|
|
||||||
router.register("policies/password", PasswordPolicyViewSet)
|
|
||||||
router.register("policies/reputation/scores", ReputationViewSet)
|
|
||||||
router.register("policies/reputation", ReputationPolicyViewSet)
|
|
||||||
|
|
||||||
router.register("providers/all", ProviderViewSet)
|
|
||||||
router.register("providers/ldap", LDAPProviderViewSet)
|
|
||||||
router.register("providers/proxy", ProxyProviderViewSet)
|
|
||||||
router.register("providers/oauth2", OAuth2ProviderViewSet)
|
|
||||||
router.register("providers/saml", SAMLProviderViewSet)
|
|
||||||
router.register("providers/scim", SCIMProviderViewSet)
|
|
||||||
router.register("providers/radius", RadiusProviderViewSet)
|
|
||||||
|
|
||||||
router.register("oauth2/authorization_codes", AuthorizationCodeViewSet)
|
|
||||||
router.register("oauth2/refresh_tokens", RefreshTokenViewSet)
|
|
||||||
router.register("oauth2/access_tokens", AccessTokenViewSet)
|
|
||||||
|
|
||||||
router.register("propertymappings/all", PropertyMappingViewSet)
|
|
||||||
router.register("propertymappings/ldap", LDAPPropertyMappingViewSet)
|
|
||||||
router.register("propertymappings/saml", SAMLPropertyMappingViewSet)
|
|
||||||
router.register("propertymappings/scope", ScopeMappingViewSet)
|
|
||||||
router.register("propertymappings/notification", NotificationWebhookMappingViewSet)
|
|
||||||
router.register("propertymappings/scim", SCIMMappingViewSet)
|
|
||||||
|
|
||||||
router.register("authenticators/all", DeviceViewSet, basename="device")
|
|
||||||
router.register("authenticators/duo", DuoDeviceViewSet)
|
|
||||||
router.register("authenticators/sms", SMSDeviceViewSet)
|
|
||||||
router.register("authenticators/static", StaticDeviceViewSet)
|
|
||||||
router.register("authenticators/totp", TOTPDeviceViewSet)
|
|
||||||
router.register("authenticators/webauthn", WebAuthnDeviceViewSet)
|
|
||||||
router.register(
|
|
||||||
"authenticators/admin/all",
|
|
||||||
AdminDeviceViewSet,
|
|
||||||
basename="admin-device",
|
|
||||||
)
|
|
||||||
router.register(
|
|
||||||
"authenticators/admin/duo",
|
|
||||||
DuoAdminDeviceViewSet,
|
|
||||||
basename="admin-duodevice",
|
|
||||||
)
|
|
||||||
router.register(
|
|
||||||
"authenticators/admin/sms",
|
|
||||||
SMSAdminDeviceViewSet,
|
|
||||||
basename="admin-smsdevice",
|
|
||||||
)
|
|
||||||
router.register(
|
|
||||||
"authenticators/admin/static",
|
|
||||||
StaticAdminDeviceViewSet,
|
|
||||||
basename="admin-staticdevice",
|
|
||||||
)
|
|
||||||
router.register("authenticators/admin/totp", TOTPAdminDeviceViewSet, basename="admin-totpdevice")
|
|
||||||
router.register(
|
|
||||||
"authenticators/admin/webauthn",
|
|
||||||
WebAuthnAdminDeviceViewSet,
|
|
||||||
basename="admin-webauthndevice",
|
|
||||||
)
|
|
||||||
|
|
||||||
router.register("stages/all", StageViewSet)
|
|
||||||
router.register("stages/authenticator/duo", AuthenticatorDuoStageViewSet)
|
|
||||||
router.register("stages/authenticator/sms", AuthenticatorSMSStageViewSet)
|
|
||||||
router.register("stages/authenticator/static", AuthenticatorStaticStageViewSet)
|
|
||||||
router.register("stages/authenticator/totp", AuthenticatorTOTPStageViewSet)
|
|
||||||
router.register("stages/authenticator/validate", AuthenticatorValidateStageViewSet)
|
|
||||||
router.register("stages/authenticator/webauthn", AuthenticateWebAuthnStageViewSet)
|
|
||||||
router.register("stages/captcha", CaptchaStageViewSet)
|
|
||||||
router.register("stages/consent", ConsentStageViewSet)
|
|
||||||
router.register("stages/deny", DenyStageViewSet)
|
|
||||||
router.register("stages/email", EmailStageViewSet)
|
|
||||||
router.register("stages/identification", IdentificationStageViewSet)
|
|
||||||
router.register("stages/invitation/invitations", InvitationViewSet)
|
|
||||||
router.register("stages/invitation/stages", InvitationStageViewSet)
|
|
||||||
router.register("stages/password", PasswordStageViewSet)
|
|
||||||
router.register("stages/prompt/prompts", PromptViewSet)
|
|
||||||
router.register("stages/prompt/stages", PromptStageViewSet)
|
|
||||||
router.register("stages/user_delete", UserDeleteStageViewSet)
|
|
||||||
router.register("stages/user_login", UserLoginStageViewSet)
|
|
||||||
router.register("stages/user_logout", UserLogoutStageViewSet)
|
|
||||||
router.register("stages/user_write", UserWriteStageViewSet)
|
|
||||||
|
|
||||||
router.register("stages/dummy", DummyStageViewSet)
|
|
||||||
router.register("policies/dummy", DummyPolicyViewSet)
|
|
||||||
|
|
||||||
urlpatterns = (
|
urlpatterns = (
|
||||||
[
|
[
|
||||||
path("", APIBrowserView.as_view(), name="schema-browser"),
|
path("", APIBrowserView.as_view(), name="schema-browser"),
|
||||||
]
|
]
|
||||||
+ router.urls
|
+ router.urls
|
||||||
|
+ _other_urls
|
||||||
+ [
|
+ [
|
||||||
path(
|
|
||||||
"admin/metrics/",
|
|
||||||
AdministrationMetricsViewSet.as_view(),
|
|
||||||
name="admin_metrics",
|
|
||||||
),
|
|
||||||
path("admin/version/", VersionView.as_view(), name="admin_version"),
|
|
||||||
path("admin/workers/", WorkerView.as_view(), name="admin_workers"),
|
|
||||||
path("admin/system/", SystemView.as_view(), name="admin_system"),
|
|
||||||
path("root/config/", ConfigView.as_view(), name="config"),
|
path("root/config/", ConfigView.as_view(), name="config"),
|
||||||
path(
|
|
||||||
"flows/executor/<slug:flow_slug>/",
|
|
||||||
FlowExecutorView.as_view(),
|
|
||||||
name="flow-executor",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"flows/inspector/<slug:flow_slug>/",
|
|
||||||
FlowInspectorView.as_view(),
|
|
||||||
name="flow-inspector",
|
|
||||||
),
|
|
||||||
path("schema/", cache_page(86400)(SpectacularAPIView.as_view()), name="schema"),
|
path("schema/", cache_page(86400)(SpectacularAPIView.as_view()), name="schema"),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
@ -11,8 +11,9 @@ from rest_framework.serializers import ListSerializer, ModelSerializer
|
|||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
from authentik.blueprints.models import BlueprintInstance, BlueprintRetrievalFailed
|
from authentik.blueprints.models import BlueprintInstance
|
||||||
from authentik.blueprints.v1.importer import Importer
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
from authentik.blueprints.v1.oci import OCI_PREFIX
|
||||||
from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_find_dict
|
from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_find_dict
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
@ -35,11 +36,12 @@ class BlueprintInstanceSerializer(ModelSerializer):
|
|||||||
"""Info about a single blueprint instance file"""
|
"""Info about a single blueprint instance file"""
|
||||||
|
|
||||||
def validate_path(self, path: str) -> str:
|
def validate_path(self, path: str) -> str:
|
||||||
"""Ensure the path specified is retrievable"""
|
"""Ensure the path (if set) specified is retrievable"""
|
||||||
try:
|
if path == "" or path.startswith(OCI_PREFIX):
|
||||||
BlueprintInstance(path=path).retrieve()
|
return path
|
||||||
except BlueprintRetrievalFailed as exc:
|
files: list[dict] = blueprints_find_dict.delay().get()
|
||||||
raise ValidationError(exc) from exc
|
if path not in [file["path"] for file in files]:
|
||||||
|
raise ValidationError(_("Blueprint file does not exist"))
|
||||||
return path
|
return path
|
||||||
|
|
||||||
def validate_content(self, content: str) -> str:
|
def validate_content(self, content: str) -> str:
|
||||||
@ -49,7 +51,8 @@ class BlueprintInstanceSerializer(ModelSerializer):
|
|||||||
context = self.instance.context if self.instance else {}
|
context = self.instance.context if self.instance else {}
|
||||||
valid, logs = Importer(content, context).validate()
|
valid, logs = Importer(content, context).validate()
|
||||||
if not valid:
|
if not valid:
|
||||||
raise ValidationError(_("Failed to validate blueprint"), *[x["msg"] for x in logs])
|
text_logs = "\n".join([x["event"] for x in logs])
|
||||||
|
raise ValidationError(_("Failed to validate blueprint: %(logs)s" % {"logs": text_logs}))
|
||||||
return content
|
return content
|
||||||
|
|
||||||
def validate(self, attrs: dict) -> dict:
|
def validate(self, attrs: dict) -> dict:
|
||||||
|
@ -1,12 +1,17 @@
|
|||||||
"""Generate JSON Schema for blueprints"""
|
"""Generate JSON Schema for blueprints"""
|
||||||
from json import dumps, loads
|
from json import dumps
|
||||||
from pathlib import Path
|
from typing import Any
|
||||||
|
|
||||||
from django.core.management.base import BaseCommand, no_translations
|
from django.core.management.base import BaseCommand, no_translations
|
||||||
|
from django.db.models import Model
|
||||||
|
from drf_jsonschema_serializer.convert import field_to_converter
|
||||||
|
from rest_framework.fields import Field, JSONField, UUIDField
|
||||||
|
from rest_framework.serializers import Serializer
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.blueprints.v1.importer import is_model_allowed
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, is_model_allowed
|
||||||
from authentik.blueprints.v1.meta.registry import registry
|
from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
@ -16,21 +21,146 @@ class Command(BaseCommand):
|
|||||||
|
|
||||||
schema: dict
|
schema: dict
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.schema = {
|
||||||
|
"$schema": "http://json-schema.org/draft-07/schema",
|
||||||
|
"$id": "https://goauthentik.io/blueprints/schema.json",
|
||||||
|
"type": "object",
|
||||||
|
"title": "authentik Blueprint schema",
|
||||||
|
"required": ["version", "entries"],
|
||||||
|
"properties": {
|
||||||
|
"version": {
|
||||||
|
"$id": "#/properties/version",
|
||||||
|
"type": "integer",
|
||||||
|
"title": "Blueprint version",
|
||||||
|
"default": 1,
|
||||||
|
},
|
||||||
|
"metadata": {
|
||||||
|
"$id": "#/properties/metadata",
|
||||||
|
"type": "object",
|
||||||
|
"required": ["name"],
|
||||||
|
"properties": {
|
||||||
|
"name": {"type": "string"},
|
||||||
|
"labels": {"type": "object", "additionalProperties": {"type": "string"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"context": {
|
||||||
|
"$id": "#/properties/context",
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": True,
|
||||||
|
},
|
||||||
|
"entries": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"oneOf": [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"$defs": {},
|
||||||
|
}
|
||||||
|
|
||||||
@no_translations
|
@no_translations
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, **options):
|
||||||
"""Generate JSON Schema for blueprints"""
|
"""Generate JSON Schema for blueprints"""
|
||||||
path = Path(__file__).parent.joinpath("./schema_template.json")
|
self.build()
|
||||||
with open(path, "r", encoding="utf-8") as _template_file:
|
self.stdout.write(dumps(self.schema, indent=4, default=Command.json_default))
|
||||||
self.schema = loads(_template_file.read())
|
|
||||||
self.set_model_allowed()
|
|
||||||
self.stdout.write(dumps(self.schema, indent=4))
|
|
||||||
|
|
||||||
def set_model_allowed(self):
|
@staticmethod
|
||||||
"""Set model enum"""
|
def json_default(value: Any) -> Any:
|
||||||
model_names = []
|
"""Helper that handles gettext_lazy strings that JSON doesn't handle"""
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
def build(self):
|
||||||
|
"""Build all models into the schema"""
|
||||||
for model in registry.get_models():
|
for model in registry.get_models():
|
||||||
if not is_model_allowed(model):
|
if issubclass(model, BaseMetaModel):
|
||||||
|
serializer_class = model.serializer()
|
||||||
|
else:
|
||||||
|
if model._meta.abstract:
|
||||||
|
continue
|
||||||
|
if not is_model_allowed(model):
|
||||||
|
continue
|
||||||
|
model_instance: Model = model()
|
||||||
|
if not isinstance(model_instance, SerializerModel):
|
||||||
|
continue
|
||||||
|
serializer_class = model_instance.serializer
|
||||||
|
serializer = serializer_class(
|
||||||
|
context={
|
||||||
|
SERIALIZER_CONTEXT_BLUEPRINT: False,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
model_path = f"{model._meta.app_label}.{model._meta.model_name}"
|
||||||
|
self.schema["properties"]["entries"]["items"]["oneOf"].append(
|
||||||
|
self.template_entry(model_path, serializer)
|
||||||
|
)
|
||||||
|
|
||||||
|
def template_entry(self, model_path: str, serializer: Serializer) -> dict:
|
||||||
|
"""Template entry for a single model"""
|
||||||
|
model_schema = self.to_jsonschema(serializer)
|
||||||
|
model_schema["required"] = []
|
||||||
|
def_name = f"model_{model_path}"
|
||||||
|
def_path = f"#/$defs/{def_name}"
|
||||||
|
self.schema["$defs"][def_name] = model_schema
|
||||||
|
return {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["model", "identifiers"],
|
||||||
|
"properties": {
|
||||||
|
"model": {"const": model_path},
|
||||||
|
"id": {"type": "string"},
|
||||||
|
"state": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["absent", "present", "created"],
|
||||||
|
"default": "present",
|
||||||
|
},
|
||||||
|
"conditions": {"type": "array", "items": {"type": "boolean"}},
|
||||||
|
"attrs": {"$ref": def_path},
|
||||||
|
"identifiers": {"$ref": def_path},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
def field_to_jsonschema(self, field: Field) -> dict:
|
||||||
|
"""Convert a single field to json schema"""
|
||||||
|
if isinstance(field, Serializer):
|
||||||
|
result = self.to_jsonschema(field)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
converter = field_to_converter[field]
|
||||||
|
result = converter.convert(field)
|
||||||
|
except KeyError:
|
||||||
|
if isinstance(field, JSONField):
|
||||||
|
result = {"type": "object", "additionalProperties": True}
|
||||||
|
elif isinstance(field, UUIDField):
|
||||||
|
result = {"type": "string", "format": "uuid"}
|
||||||
|
else:
|
||||||
|
raise
|
||||||
|
if field.label:
|
||||||
|
result["title"] = field.label
|
||||||
|
if field.help_text:
|
||||||
|
result["description"] = field.help_text
|
||||||
|
return self.clean_result(result)
|
||||||
|
|
||||||
|
def clean_result(self, result: dict) -> dict:
|
||||||
|
"""Remove enumNames from result, recursively"""
|
||||||
|
result.pop("enumNames", None)
|
||||||
|
for key, value in result.items():
|
||||||
|
if isinstance(value, dict):
|
||||||
|
result[key] = self.clean_result(value)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def to_jsonschema(self, serializer: Serializer) -> dict:
|
||||||
|
"""Convert serializer to json schema"""
|
||||||
|
properties = {}
|
||||||
|
required = []
|
||||||
|
for name, field in serializer.fields.items():
|
||||||
|
if field.read_only:
|
||||||
continue
|
continue
|
||||||
model_names.append(f"{model._meta.app_label}.{model._meta.model_name}")
|
sub_schema = self.field_to_jsonschema(field)
|
||||||
model_names.sort()
|
if field.required:
|
||||||
self.schema["properties"]["entries"]["items"]["properties"]["model"]["enum"] = model_names
|
required.append(name)
|
||||||
|
properties[name] = sub_schema
|
||||||
|
|
||||||
|
result = {"type": "object", "properties": properties}
|
||||||
|
if required:
|
||||||
|
result["required"] = required
|
||||||
|
return result
|
||||||
|
@ -1,105 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "http://json-schema.org/draft-07/schema",
|
|
||||||
"$id": "http://example.com/example.json",
|
|
||||||
"type": "object",
|
|
||||||
"title": "authentik Blueprint schema",
|
|
||||||
"default": {},
|
|
||||||
"required": [
|
|
||||||
"version",
|
|
||||||
"entries"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"version": {
|
|
||||||
"$id": "#/properties/version",
|
|
||||||
"type": "integer",
|
|
||||||
"title": "Blueprint version",
|
|
||||||
"default": 1
|
|
||||||
},
|
|
||||||
"metadata": {
|
|
||||||
"$id": "#/properties/metadata",
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"name"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"name": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"labels": {
|
|
||||||
"type": "object"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"context": {
|
|
||||||
"$id": "#/properties/context",
|
|
||||||
"type": "object",
|
|
||||||
"additionalProperties": true
|
|
||||||
},
|
|
||||||
"entries": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"$id": "#entry",
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"model"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"model": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"placeholder"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"id": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"state": {
|
|
||||||
"type": "string",
|
|
||||||
"enum": [
|
|
||||||
"absent",
|
|
||||||
"present",
|
|
||||||
"created"
|
|
||||||
],
|
|
||||||
"default": "present"
|
|
||||||
},
|
|
||||||
"conditions": {
|
|
||||||
"type": "array",
|
|
||||||
"items": {
|
|
||||||
"type": "boolean"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"attrs": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"name": {
|
|
||||||
"type": "string",
|
|
||||||
"description": "Commonly available field, may not exist on all models"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"default": {},
|
|
||||||
"additionalProperties": true
|
|
||||||
},
|
|
||||||
"identifiers": {
|
|
||||||
"type": "object",
|
|
||||||
"default": {},
|
|
||||||
"properties": {
|
|
||||||
"pk": {
|
|
||||||
"description": "Commonly available field, may not exist on all models",
|
|
||||||
"anyOf": [
|
|
||||||
{
|
|
||||||
"type": "number"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "string",
|
|
||||||
"format": "uuid"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"additionalProperties": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -45,7 +45,7 @@ def check_blueprint_v1_file(BlueprintInstance: type, path: Path):
|
|||||||
enabled=True,
|
enabled=True,
|
||||||
managed_models=[],
|
managed_models=[],
|
||||||
last_applied_hash="",
|
last_applied_hash="",
|
||||||
metadata=metadata,
|
metadata=metadata or {},
|
||||||
)
|
)
|
||||||
instance.save()
|
instance.save()
|
||||||
|
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
# Generated by Django 4.1.7 on 2023-04-28 10:49
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
from authentik.lib.migrations import fallback_names
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("authentik_blueprints", "0002_blueprintinstance_content"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(fallback_names("authentik_blueprints", "blueprintinstance", "name")),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="blueprintinstance",
|
||||||
|
name="name",
|
||||||
|
field=models.TextField(unique=True),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="blueprintinstance",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -8,7 +8,7 @@ from django.utils.translation import gettext_lazy as _
|
|||||||
from rest_framework.serializers import Serializer
|
from rest_framework.serializers import Serializer
|
||||||
from structlog import get_logger
|
from structlog import get_logger
|
||||||
|
|
||||||
from authentik.blueprints.v1.oci import BlueprintOCIClient, OCIException
|
from authentik.blueprints.v1.oci import OCI_PREFIX, BlueprintOCIClient, OCIException
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.lib.models import CreatedUpdatedModel, SerializerModel
|
from authentik.lib.models import CreatedUpdatedModel, SerializerModel
|
||||||
from authentik.lib.sentry import SentryIgnoredException
|
from authentik.lib.sentry import SentryIgnoredException
|
||||||
@ -17,20 +17,20 @@ LOGGER = get_logger()
|
|||||||
|
|
||||||
|
|
||||||
class BlueprintRetrievalFailed(SentryIgnoredException):
|
class BlueprintRetrievalFailed(SentryIgnoredException):
|
||||||
"""Error raised when we're unable to fetch the blueprint contents, whether it be HTTP files
|
"""Error raised when we are unable to fetch the blueprint contents, whether it be HTTP files
|
||||||
not being accessible or local files not being readable"""
|
not being accessible or local files not being readable"""
|
||||||
|
|
||||||
|
|
||||||
class ManagedModel(models.Model):
|
class ManagedModel(models.Model):
|
||||||
"""Model which can be managed by authentik exclusively"""
|
"""Model that can be managed by authentik exclusively"""
|
||||||
|
|
||||||
managed = models.TextField(
|
managed = models.TextField(
|
||||||
default=None,
|
default=None,
|
||||||
null=True,
|
null=True,
|
||||||
verbose_name=_("Managed by authentik"),
|
verbose_name=_("Managed by authentik"),
|
||||||
help_text=_(
|
help_text=_(
|
||||||
"Objects which are managed by authentik. These objects are created and updated "
|
"Objects that are managed by authentik. These objects are created and updated "
|
||||||
"automatically. This is flag only indicates that an object can be overwritten by "
|
"automatically. This flag only indicates that an object can be overwritten by "
|
||||||
"migrations. You can still modify the objects via the API, but expect changes "
|
"migrations. You can still modify the objects via the API, but expect changes "
|
||||||
"to be overwritten in a later update."
|
"to be overwritten in a later update."
|
||||||
),
|
),
|
||||||
@ -57,7 +57,7 @@ class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
|
|
||||||
instance_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
instance_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
||||||
|
|
||||||
name = models.TextField()
|
name = models.TextField(unique=True)
|
||||||
metadata = models.JSONField(default=dict)
|
metadata = models.JSONField(default=dict)
|
||||||
path = models.TextField(default="", blank=True)
|
path = models.TextField(default="", blank=True)
|
||||||
content = models.TextField(default="", blank=True)
|
content = models.TextField(default="", blank=True)
|
||||||
@ -72,7 +72,7 @@ class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
|
|
||||||
def retrieve_oci(self) -> str:
|
def retrieve_oci(self) -> str:
|
||||||
"""Get blueprint from an OCI registry"""
|
"""Get blueprint from an OCI registry"""
|
||||||
client = BlueprintOCIClient(self.path.replace("oci://", "https://"))
|
client = BlueprintOCIClient(self.path.replace(OCI_PREFIX, "https://"))
|
||||||
try:
|
try:
|
||||||
manifests = client.fetch_manifests()
|
manifests = client.fetch_manifests()
|
||||||
return client.fetch_blobs(manifests)
|
return client.fetch_blobs(manifests)
|
||||||
@ -82,7 +82,10 @@ class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
def retrieve_file(self) -> str:
|
def retrieve_file(self) -> str:
|
||||||
"""Get blueprint from path"""
|
"""Get blueprint from path"""
|
||||||
try:
|
try:
|
||||||
full_path = Path(CONFIG.y("blueprints_dir")).joinpath(Path(self.path))
|
base = Path(CONFIG.y("blueprints_dir"))
|
||||||
|
full_path = base.joinpath(Path(self.path)).resolve()
|
||||||
|
if not str(full_path).startswith(str(base.resolve())):
|
||||||
|
raise BlueprintRetrievalFailed("Invalid blueprint path")
|
||||||
with full_path.open("r", encoding="utf-8") as _file:
|
with full_path.open("r", encoding="utf-8") as _file:
|
||||||
return _file.read()
|
return _file.read()
|
||||||
except (IOError, OSError) as exc:
|
except (IOError, OSError) as exc:
|
||||||
@ -90,7 +93,7 @@ class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
|
|
||||||
def retrieve(self) -> str:
|
def retrieve(self) -> str:
|
||||||
"""Retrieve blueprint contents"""
|
"""Retrieve blueprint contents"""
|
||||||
if self.path.startswith("oci://"):
|
if self.path.startswith(OCI_PREFIX):
|
||||||
return self.retrieve_oci()
|
return self.retrieve_oci()
|
||||||
if self.path != "":
|
if self.path != "":
|
||||||
return self.retrieve_file()
|
return self.retrieve_file()
|
||||||
|
41
authentik/blueprints/tests/fixtures/conditional_fields.yaml
vendored
Normal file
41
authentik/blueprints/tests/fixtures/conditional_fields.yaml
vendored
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
version: 1
|
||||||
|
metadata:
|
||||||
|
name: test conditional fields
|
||||||
|
labels:
|
||||||
|
blueprints.goauthentik.io/description: |
|
||||||
|
Some models have conditional fields that are only allowed in blueprint contexts
|
||||||
|
- Token (key)
|
||||||
|
- Application (icon)
|
||||||
|
- Source (icon)
|
||||||
|
- Flow (background)
|
||||||
|
entries:
|
||||||
|
- model: authentik_core.token
|
||||||
|
identifiers:
|
||||||
|
identifier: %(uid)s-token
|
||||||
|
attrs:
|
||||||
|
key: %(uid)s
|
||||||
|
user: %(user)s
|
||||||
|
intent: api
|
||||||
|
- model: authentik_core.application
|
||||||
|
identifiers:
|
||||||
|
slug: %(uid)s-app
|
||||||
|
attrs:
|
||||||
|
name: %(uid)s-app
|
||||||
|
icon: https://goauthentik.io/img/icon.png
|
||||||
|
- model: authentik_sources_oauth.oauthsource
|
||||||
|
identifiers:
|
||||||
|
slug: %(uid)s-source
|
||||||
|
attrs:
|
||||||
|
name: %(uid)s-source
|
||||||
|
provider_type: azuread
|
||||||
|
consumer_key: %(uid)s
|
||||||
|
consumer_secret: %(uid)s
|
||||||
|
icon: https://goauthentik.io/img/icon.png
|
||||||
|
- model: authentik_flows.flow
|
||||||
|
identifiers:
|
||||||
|
slug: %(uid)s-flow
|
||||||
|
attrs:
|
||||||
|
name: %(uid)s-flow
|
||||||
|
title: %(uid)s-flow
|
||||||
|
designation: authentication
|
||||||
|
background: https://goauthentik.io/img/icon.png
|
@ -1,34 +1,15 @@
|
|||||||
"""authentik managed models tests"""
|
"""authentik managed models tests"""
|
||||||
from typing import Callable, Type
|
|
||||||
|
|
||||||
from django.apps import apps
|
|
||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
|
||||||
from authentik.blueprints.v1.importer import is_model_allowed
|
from authentik.blueprints.models import BlueprintInstance, BlueprintRetrievalFailed
|
||||||
from authentik.lib.models import SerializerModel
|
from authentik.lib.generators import generate_id
|
||||||
|
|
||||||
|
|
||||||
class TestModels(TestCase):
|
class TestModels(TestCase):
|
||||||
"""Test Models"""
|
"""Test Models"""
|
||||||
|
|
||||||
|
def test_retrieve_file(self):
|
||||||
def serializer_tester_factory(test_model: Type[SerializerModel]) -> Callable:
|
"""Test retrieve_file"""
|
||||||
"""Test serializer"""
|
instance = BlueprintInstance.objects.create(name=generate_id(), path="../etc/hosts")
|
||||||
|
with self.assertRaises(BlueprintRetrievalFailed):
|
||||||
def tester(self: TestModels):
|
instance.retrieve()
|
||||||
if test_model._meta.abstract: # pragma: no cover
|
|
||||||
return
|
|
||||||
model_class = test_model()
|
|
||||||
self.assertTrue(isinstance(model_class, SerializerModel))
|
|
||||||
self.assertIsNotNone(model_class.serializer)
|
|
||||||
|
|
||||||
return tester
|
|
||||||
|
|
||||||
|
|
||||||
for app in apps.get_app_configs():
|
|
||||||
if not app.label.startswith("authentik"):
|
|
||||||
continue
|
|
||||||
for model in app.get_models():
|
|
||||||
if not is_model_allowed(model):
|
|
||||||
continue
|
|
||||||
setattr(TestModels, f"test_{app.label}_{model.__name__}", serializer_tester_factory(model))
|
|
||||||
|
@ -32,6 +32,29 @@ class TestBlueprintOCI(TransactionTestCase):
|
|||||||
"foo",
|
"foo",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_successful_port(self):
|
||||||
|
"""Successful retrieval with custom port"""
|
||||||
|
with Mocker() as mocker:
|
||||||
|
mocker.get(
|
||||||
|
"https://ghcr.io:1234/v2/goauthentik/blueprints/test/manifests/latest",
|
||||||
|
json={
|
||||||
|
"layers": [
|
||||||
|
{
|
||||||
|
"mediaType": OCI_MEDIA_TYPE,
|
||||||
|
"digest": "foo",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
mocker.get("https://ghcr.io:1234/v2/goauthentik/blueprints/test/blobs/foo", text="foo")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
BlueprintInstance(
|
||||||
|
path="oci://ghcr.io:1234/goauthentik/blueprints/test:latest"
|
||||||
|
).retrieve(),
|
||||||
|
"foo",
|
||||||
|
)
|
||||||
|
|
||||||
def test_manifests_error(self):
|
def test_manifests_error(self):
|
||||||
"""Test manifests request erroring"""
|
"""Test manifests request erroring"""
|
||||||
with Mocker() as mocker:
|
with Mocker() as mocker:
|
||||||
|
34
authentik/blueprints/tests/test_serializer_models.py
Normal file
34
authentik/blueprints/tests/test_serializer_models.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
"""authentik managed models tests"""
|
||||||
|
from typing import Callable, Type
|
||||||
|
|
||||||
|
from django.apps import apps
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import is_model_allowed
|
||||||
|
from authentik.lib.models import SerializerModel
|
||||||
|
|
||||||
|
|
||||||
|
class TestModels(TestCase):
|
||||||
|
"""Test Models"""
|
||||||
|
|
||||||
|
|
||||||
|
def serializer_tester_factory(test_model: Type[SerializerModel]) -> Callable:
|
||||||
|
"""Test serializer"""
|
||||||
|
|
||||||
|
def tester(self: TestModels):
|
||||||
|
if test_model._meta.abstract: # pragma: no cover
|
||||||
|
return
|
||||||
|
model_class = test_model()
|
||||||
|
self.assertTrue(isinstance(model_class, SerializerModel))
|
||||||
|
self.assertIsNotNone(model_class.serializer)
|
||||||
|
|
||||||
|
return tester
|
||||||
|
|
||||||
|
|
||||||
|
for app in apps.get_app_configs():
|
||||||
|
if not app.label.startswith("authentik"):
|
||||||
|
continue
|
||||||
|
for model in app.get_models():
|
||||||
|
if not is_model_allowed(model):
|
||||||
|
continue
|
||||||
|
setattr(TestModels, f"test_{app.label}_{model.__name__}", serializer_tester_factory(model))
|
@ -44,6 +44,14 @@ class TestBlueprintsV1API(APITestCase):
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_api_oci(self):
|
||||||
|
"""Test validation with OCI path"""
|
||||||
|
res = self.client.post(
|
||||||
|
reverse("authentik_api:blueprintinstance-list"),
|
||||||
|
data={"name": "foo", "path": "oci://foo/bar"},
|
||||||
|
)
|
||||||
|
self.assertEqual(res.status_code, 201)
|
||||||
|
|
||||||
def test_api_blank(self):
|
def test_api_blank(self):
|
||||||
"""Test blank"""
|
"""Test blank"""
|
||||||
res = self.client.post(
|
res = self.client.post(
|
||||||
@ -67,4 +75,7 @@ class TestBlueprintsV1API(APITestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
self.assertEqual(res.status_code, 400)
|
self.assertEqual(res.status_code, 400)
|
||||||
self.assertJSONEqual(res.content.decode(), {"content": ["Failed to validate blueprint"]})
|
self.assertJSONEqual(
|
||||||
|
res.content.decode(),
|
||||||
|
{"content": ["Failed to validate blueprint: Invalid blueprint version"]},
|
||||||
|
)
|
||||||
|
47
authentik/blueprints/tests/test_v1_conditional_fields.py
Normal file
47
authentik/blueprints/tests/test_v1_conditional_fields.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
"""Test blueprints v1"""
|
||||||
|
from django.test import TransactionTestCase
|
||||||
|
|
||||||
|
from authentik.blueprints.v1.importer import Importer
|
||||||
|
from authentik.core.models import Application, Token
|
||||||
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
from authentik.flows.models import Flow
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
|
from authentik.lib.tests.utils import load_fixture
|
||||||
|
from authentik.sources.oauth.models import OAuthSource
|
||||||
|
|
||||||
|
|
||||||
|
class TestBlueprintsV1ConditionalFields(TransactionTestCase):
|
||||||
|
"""Test Blueprints conditional fields"""
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
user = create_test_admin_user()
|
||||||
|
self.uid = generate_id()
|
||||||
|
import_yaml = load_fixture("fixtures/conditional_fields.yaml", uid=self.uid, user=user.pk)
|
||||||
|
|
||||||
|
importer = Importer(import_yaml)
|
||||||
|
self.assertTrue(importer.validate()[0])
|
||||||
|
self.assertTrue(importer.apply())
|
||||||
|
|
||||||
|
def test_token(self):
|
||||||
|
"""Test token"""
|
||||||
|
token = Token.objects.filter(identifier=f"{self.uid}-token").first()
|
||||||
|
self.assertIsNotNone(token)
|
||||||
|
self.assertEqual(token.key, self.uid)
|
||||||
|
|
||||||
|
def test_application(self):
|
||||||
|
"""Test application"""
|
||||||
|
app = Application.objects.filter(slug=f"{self.uid}-app").first()
|
||||||
|
self.assertIsNotNone(app)
|
||||||
|
self.assertEqual(app.meta_icon, "https://goauthentik.io/img/icon.png")
|
||||||
|
|
||||||
|
def test_source(self):
|
||||||
|
"""Test source"""
|
||||||
|
source = OAuthSource.objects.filter(slug=f"{self.uid}-source").first()
|
||||||
|
self.assertIsNotNone(source)
|
||||||
|
self.assertEqual(source.icon, "https://goauthentik.io/img/icon.png")
|
||||||
|
|
||||||
|
def test_flow(self):
|
||||||
|
"""Test flow"""
|
||||||
|
flow = Flow.objects.filter(slug=f"{self.uid}-flow").first()
|
||||||
|
self.assertIsNotNone(flow)
|
||||||
|
self.assertEqual(flow.background, "https://goauthentik.io/img/icon.png")
|
6
authentik/blueprints/urls.py
Normal file
6
authentik/blueprints/urls.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.blueprints.api import BlueprintInstanceViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("managed/blueprints", BlueprintInstanceViewSet),
|
||||||
|
]
|
@ -299,7 +299,7 @@ class Importer:
|
|||||||
orig_import = deepcopy(self.__import)
|
orig_import = deepcopy(self.__import)
|
||||||
if self.__import.version != 1:
|
if self.__import.version != 1:
|
||||||
self.logger.warning("Invalid blueprint version")
|
self.logger.warning("Invalid blueprint version")
|
||||||
return False, []
|
return False, [{"event": "Invalid blueprint version"}]
|
||||||
with (
|
with (
|
||||||
transaction_rollback(),
|
transaction_rollback(),
|
||||||
capture_logs() as logs,
|
capture_logs() as logs,
|
||||||
|
@ -19,6 +19,7 @@ from authentik.lib.sentry import SentryIgnoredException
|
|||||||
from authentik.lib.utils.http import authentik_user_agent
|
from authentik.lib.utils.http import authentik_user_agent
|
||||||
|
|
||||||
OCI_MEDIA_TYPE = "application/vnd.goauthentik.blueprint.v1+yaml"
|
OCI_MEDIA_TYPE = "application/vnd.goauthentik.blueprint.v1+yaml"
|
||||||
|
OCI_PREFIX = "oci://"
|
||||||
|
|
||||||
|
|
||||||
class OCIException(SentryIgnoredException):
|
class OCIException(SentryIgnoredException):
|
||||||
@ -39,11 +40,16 @@ class BlueprintOCIClient:
|
|||||||
self.logger = get_logger().bind(url=self.sanitized_url)
|
self.logger = get_logger().bind(url=self.sanitized_url)
|
||||||
|
|
||||||
self.ref = "latest"
|
self.ref = "latest"
|
||||||
|
# Remove the leading slash of the path to convert it to an image name
|
||||||
path = self.url.path[1:]
|
path = self.url.path[1:]
|
||||||
if ":" in self.url.path:
|
if ":" in path:
|
||||||
|
# if there's a colon in the path, use everything after it as a ref
|
||||||
path, _, self.ref = path.partition(":")
|
path, _, self.ref = path.partition(":")
|
||||||
|
base_url = f"https://{self.url.hostname}"
|
||||||
|
if self.url.port:
|
||||||
|
base_url += f":{self.url.port}"
|
||||||
self.client = NewClient(
|
self.client = NewClient(
|
||||||
f"https://{self.url.hostname}",
|
base_url,
|
||||||
WithUserAgent(authentik_user_agent()),
|
WithUserAgent(authentik_user_agent()),
|
||||||
WithUsernamePassword(self.url.username, self.url.password),
|
WithUsernamePassword(self.url.username, self.url.password),
|
||||||
WithDefaultName(path),
|
WithDefaultName(path),
|
||||||
|
@ -28,6 +28,7 @@ from authentik.blueprints.models import (
|
|||||||
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, EntryInvalidError
|
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, EntryInvalidError
|
||||||
from authentik.blueprints.v1.importer import Importer
|
from authentik.blueprints.v1.importer import Importer
|
||||||
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
||||||
|
from authentik.blueprints.v1.oci import OCI_PREFIX
|
||||||
from authentik.events.monitored_tasks import (
|
from authentik.events.monitored_tasks import (
|
||||||
MonitoredTask,
|
MonitoredTask,
|
||||||
TaskResult,
|
TaskResult,
|
||||||
@ -101,7 +102,10 @@ def blueprints_find():
|
|||||||
"""Find blueprints and return valid ones"""
|
"""Find blueprints and return valid ones"""
|
||||||
blueprints = []
|
blueprints = []
|
||||||
root = Path(CONFIG.y("blueprints_dir"))
|
root = Path(CONFIG.y("blueprints_dir"))
|
||||||
for path in root.glob("**/*.yaml"):
|
for path in root.rglob("**/*.yaml"):
|
||||||
|
# Check if any part in the path starts with a dot and assume a hidden file
|
||||||
|
if any(part for part in path.parts if part.startswith(".")):
|
||||||
|
continue
|
||||||
LOGGER.debug("found blueprint", path=str(path))
|
LOGGER.debug("found blueprint", path=str(path))
|
||||||
with open(path, "r", encoding="utf-8") as blueprint_file:
|
with open(path, "r", encoding="utf-8") as blueprint_file:
|
||||||
try:
|
try:
|
||||||
@ -225,7 +229,7 @@ def apply_blueprint(self: MonitoredTask, instance_pk: str):
|
|||||||
def clear_failed_blueprints():
|
def clear_failed_blueprints():
|
||||||
"""Remove blueprints which couldn't be fetched"""
|
"""Remove blueprints which couldn't be fetched"""
|
||||||
# Exclude OCI blueprints as those might be temporarily unavailable
|
# Exclude OCI blueprints as those might be temporarily unavailable
|
||||||
for blueprint in BlueprintInstance.objects.exclude(path__startswith="oci://"):
|
for blueprint in BlueprintInstance.objects.exclude(path__startswith=OCI_PREFIX):
|
||||||
try:
|
try:
|
||||||
blueprint.retrieve()
|
blueprint.retrieve()
|
||||||
except BlueprintRetrievalFailed:
|
except BlueprintRetrievalFailed:
|
||||||
|
@ -11,7 +11,7 @@ from drf_spectacular.types import OpenApiTypes
|
|||||||
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
||||||
from guardian.shortcuts import get_objects_for_user
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import ReadOnlyField, SerializerMethodField
|
from rest_framework.fields import CharField, ReadOnlyField, SerializerMethodField
|
||||||
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
|
||||||
@ -23,6 +23,7 @@ from structlog.testing import capture_logs
|
|||||||
|
|
||||||
from authentik.admin.api.metrics import CoordinateSerializer
|
from authentik.admin.api.metrics import CoordinateSerializer
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.providers import ProviderSerializer
|
from authentik.core.api.providers import ProviderSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.models import Application, User
|
from authentik.core.models import Application, User
|
||||||
@ -51,6 +52,9 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
|
|
||||||
launch_url = SerializerMethodField()
|
launch_url = SerializerMethodField()
|
||||||
provider_obj = ProviderSerializer(source="get_provider", required=False, read_only=True)
|
provider_obj = ProviderSerializer(source="get_provider", required=False, read_only=True)
|
||||||
|
backchannel_providers_obj = ProviderSerializer(
|
||||||
|
source="backchannel_providers", required=False, read_only=True, many=True
|
||||||
|
)
|
||||||
|
|
||||||
meta_icon = ReadOnlyField(source="get_meta_icon")
|
meta_icon = ReadOnlyField(source="get_meta_icon")
|
||||||
|
|
||||||
@ -61,6 +65,11 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
user = self.context["request"].user
|
user = self.context["request"].user
|
||||||
return app.get_launch_url(user)
|
return app.get_launch_url(user)
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
|
self.fields["icon"] = CharField(source="meta_icon", required=False)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Application
|
model = Application
|
||||||
fields = [
|
fields = [
|
||||||
@ -69,6 +78,8 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
"slug",
|
"slug",
|
||||||
"provider",
|
"provider",
|
||||||
"provider_obj",
|
"provider_obj",
|
||||||
|
"backchannel_providers",
|
||||||
|
"backchannel_providers_obj",
|
||||||
"launch_url",
|
"launch_url",
|
||||||
"open_in_new_tab",
|
"open_in_new_tab",
|
||||||
"meta_launch_url",
|
"meta_launch_url",
|
||||||
@ -80,6 +91,7 @@ class ApplicationSerializer(ModelSerializer):
|
|||||||
]
|
]
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
"meta_icon": {"read_only": True},
|
"meta_icon": {"read_only": True},
|
||||||
|
"backchannel_providers": {"required": False},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -93,7 +93,6 @@ class PropertyMappingViewSet(
|
|||||||
{
|
{
|
||||||
"name": subclass._meta.verbose_name,
|
"name": subclass._meta.verbose_name,
|
||||||
"description": subclass.__doc__,
|
"description": subclass.__doc__,
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
"component": subclass().component,
|
"component": subclass().component,
|
||||||
"model_name": subclass._meta.model_name,
|
"model_name": subclass._meta.model_name,
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
"""Provider API Views"""
|
"""Provider API Views"""
|
||||||
|
from django.db.models import QuerySet
|
||||||
|
from django.db.models.query import Q
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
from django_filters.filters import BooleanFilter
|
||||||
|
from django_filters.filterset import FilterSet
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from rest_framework import mixins
|
from rest_framework import mixins
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
@ -20,12 +24,13 @@ class ProviderSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
assigned_application_slug = ReadOnlyField(source="application.slug")
|
assigned_application_slug = ReadOnlyField(source="application.slug")
|
||||||
assigned_application_name = ReadOnlyField(source="application.name")
|
assigned_application_name = ReadOnlyField(source="application.name")
|
||||||
|
assigned_backchannel_application_slug = ReadOnlyField(source="backchannel_application.slug")
|
||||||
|
assigned_backchannel_application_name = ReadOnlyField(source="backchannel_application.name")
|
||||||
|
|
||||||
component = SerializerMethodField()
|
component = SerializerMethodField()
|
||||||
|
|
||||||
def get_component(self, obj: Provider) -> str: # pragma: no cover
|
def get_component(self, obj: Provider) -> str: # pragma: no cover
|
||||||
"""Get object component so that we know how to edit the object"""
|
"""Get object component so that we know how to edit the object"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if obj.__class__ == Provider:
|
if obj.__class__ == Provider:
|
||||||
return ""
|
return ""
|
||||||
return obj.component
|
return obj.component
|
||||||
@ -41,6 +46,8 @@ class ProviderSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
"component",
|
"component",
|
||||||
"assigned_application_slug",
|
"assigned_application_slug",
|
||||||
"assigned_application_name",
|
"assigned_application_name",
|
||||||
|
"assigned_backchannel_application_slug",
|
||||||
|
"assigned_backchannel_application_name",
|
||||||
"verbose_name",
|
"verbose_name",
|
||||||
"verbose_name_plural",
|
"verbose_name_plural",
|
||||||
"meta_model_name",
|
"meta_model_name",
|
||||||
@ -50,6 +57,27 @@ class ProviderSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ProviderFilter(FilterSet):
|
||||||
|
"""Filter for providers"""
|
||||||
|
|
||||||
|
application__isnull = BooleanFilter(method="filter_application__isnull")
|
||||||
|
backchannel_only = BooleanFilter(
|
||||||
|
method="filter_backchannel_only",
|
||||||
|
)
|
||||||
|
|
||||||
|
def filter_application__isnull(self, queryset: QuerySet, name, value):
|
||||||
|
"""Only return providers that are neither assigned to application,
|
||||||
|
both as provider or application provider"""
|
||||||
|
return queryset.filter(
|
||||||
|
Q(backchannel_application__isnull=value, is_backchannel=True)
|
||||||
|
| Q(application__isnull=value)
|
||||||
|
)
|
||||||
|
|
||||||
|
def filter_backchannel_only(self, queryset: QuerySet, name, value):
|
||||||
|
"""Only return backchannel providers"""
|
||||||
|
return queryset.filter(is_backchannel=value)
|
||||||
|
|
||||||
|
|
||||||
class ProviderViewSet(
|
class ProviderViewSet(
|
||||||
mixins.RetrieveModelMixin,
|
mixins.RetrieveModelMixin,
|
||||||
mixins.DestroyModelMixin,
|
mixins.DestroyModelMixin,
|
||||||
@ -61,9 +89,7 @@ class ProviderViewSet(
|
|||||||
|
|
||||||
queryset = Provider.objects.none()
|
queryset = Provider.objects.none()
|
||||||
serializer_class = ProviderSerializer
|
serializer_class = ProviderSerializer
|
||||||
filterset_fields = {
|
filterset_class = ProviderFilter
|
||||||
"application": ["isnull"],
|
|
||||||
}
|
|
||||||
search_fields = [
|
search_fields = [
|
||||||
"name",
|
"name",
|
||||||
"application__name",
|
"application__name",
|
||||||
@ -79,6 +105,8 @@ class ProviderViewSet(
|
|||||||
data = []
|
data = []
|
||||||
for subclass in all_subclasses(self.queryset.model):
|
for subclass in all_subclasses(self.queryset.model):
|
||||||
subclass: Provider
|
subclass: Provider
|
||||||
|
if subclass._meta.abstract:
|
||||||
|
continue
|
||||||
data.append(
|
data.append(
|
||||||
{
|
{
|
||||||
"name": subclass._meta.verbose_name,
|
"name": subclass._meta.verbose_name,
|
||||||
|
@ -5,16 +5,18 @@ 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.filters import OrderingFilter, SearchFilter
|
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.serializers import ModelSerializer, ReadOnlyField, SerializerMethodField
|
from rest_framework.serializers import ModelSerializer
|
||||||
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.api.authorization import OwnerFilter, OwnerSuperuserPermissions
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
|
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 MetaNameSerializer, TypeCreateSerializer
|
from authentik.core.api.utils import MetaNameSerializer, TypeCreateSerializer
|
||||||
from authentik.core.models import Source, UserSourceConnection
|
from authentik.core.models import Source, UserSourceConnection
|
||||||
@ -40,11 +42,15 @@ class SourceSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
def get_component(self, obj: Source) -> str:
|
def get_component(self, obj: Source) -> str:
|
||||||
"""Get object component so that we know how to edit the object"""
|
"""Get object component so that we know how to edit the object"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if obj.__class__ == Source:
|
if obj.__class__ == Source:
|
||||||
return ""
|
return ""
|
||||||
return obj.component
|
return obj.component
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
|
self.fields["icon"] = CharField(required=False)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Source
|
model = Source
|
||||||
fields = [
|
fields = [
|
||||||
@ -139,7 +145,6 @@ class SourceViewSet(
|
|||||||
component = subclass.__bases__[0]().component
|
component = subclass.__bases__[0]().component
|
||||||
else:
|
else:
|
||||||
component = subclass().component
|
component = subclass().component
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
data.append(
|
data.append(
|
||||||
{
|
{
|
||||||
"name": subclass._meta.verbose_name,
|
"name": subclass._meta.verbose_name,
|
||||||
|
@ -56,7 +56,6 @@ class UsedByMixin:
|
|||||||
# pylint: disable=too-many-locals
|
# pylint: disable=too-many-locals
|
||||||
def used_by(self, request: Request, *args, **kwargs) -> Response:
|
def used_by(self, request: Request, *args, **kwargs) -> Response:
|
||||||
"""Get a list of all objects that use this object"""
|
"""Get a list of all objects that use this object"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
model: Model = self.get_object()
|
model: Model = self.get_object()
|
||||||
used_by = []
|
used_by = []
|
||||||
shadows = []
|
shadows = []
|
||||||
|
@ -67,11 +67,12 @@ from authentik.core.models import (
|
|||||||
TokenIntents,
|
TokenIntents,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from authentik.events.models import EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.flows.exceptions import FlowNonApplicableException
|
from authentik.flows.exceptions import FlowNonApplicableException
|
||||||
from authentik.flows.models import FlowToken
|
from authentik.flows.models import FlowToken
|
||||||
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner
|
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner
|
||||||
from authentik.flows.views.executor import QS_KEY_TOKEN
|
from authentik.flows.views.executor import QS_KEY_TOKEN
|
||||||
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.stages.email.models import EmailStage
|
from authentik.stages.email.models import EmailStage
|
||||||
from authentik.stages.email.tasks import send_mails
|
from authentik.stages.email.tasks import send_mails
|
||||||
from authentik.stages.email.utils import TemplateEmailMessage
|
from authentik.stages.email.utils import TemplateEmailMessage
|
||||||
@ -106,7 +107,7 @@ class UserSerializer(ModelSerializer):
|
|||||||
avatar = CharField(read_only=True)
|
avatar = CharField(read_only=True)
|
||||||
attributes = JSONField(validators=[is_dict], required=False)
|
attributes = JSONField(validators=[is_dict], required=False)
|
||||||
groups = PrimaryKeyRelatedField(
|
groups = PrimaryKeyRelatedField(
|
||||||
allow_empty=True, many=True, source="ak_groups", queryset=Group.objects.all()
|
allow_empty=True, many=True, source="ak_groups", queryset=Group.objects.all(), default=list
|
||||||
)
|
)
|
||||||
groups_obj = ListSerializer(child=UserGroupSerializer(), read_only=True, source="ak_groups")
|
groups_obj = ListSerializer(child=UserGroupSerializer(), read_only=True, source="ak_groups")
|
||||||
uid = CharField(read_only=True)
|
uid = CharField(read_only=True)
|
||||||
@ -543,6 +544,58 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
send_mails(email_stage, message)
|
send_mails(email_stage, message)
|
||||||
return Response(status=204)
|
return Response(status=204)
|
||||||
|
|
||||||
|
@permission_required("authentik_core.impersonate")
|
||||||
|
@extend_schema(
|
||||||
|
request=OpenApiTypes.NONE,
|
||||||
|
responses={
|
||||||
|
"204": OpenApiResponse(description="Successfully started impersonation"),
|
||||||
|
"401": OpenApiResponse(description="Access denied"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
@action(detail=True, methods=["POST"])
|
||||||
|
def impersonate(self, request: Request, pk: int) -> Response:
|
||||||
|
"""Impersonate a user"""
|
||||||
|
if not CONFIG.y_bool("impersonation"):
|
||||||
|
LOGGER.debug("User attempted to impersonate", user=request.user)
|
||||||
|
return Response(status=401)
|
||||||
|
if not request.user.has_perm("impersonate"):
|
||||||
|
LOGGER.debug("User attempted to impersonate without permissions", user=request.user)
|
||||||
|
return Response(status=401)
|
||||||
|
|
||||||
|
user_to_be = self.get_object()
|
||||||
|
|
||||||
|
request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER] = request.user
|
||||||
|
request.session[SESSION_KEY_IMPERSONATE_USER] = user_to_be
|
||||||
|
|
||||||
|
Event.new(EventAction.IMPERSONATION_STARTED).from_http(request, user_to_be)
|
||||||
|
|
||||||
|
return Response(status=201)
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
request=OpenApiTypes.NONE,
|
||||||
|
responses={
|
||||||
|
"204": OpenApiResponse(description="Successfully started impersonation"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
@action(detail=False, methods=["GET"])
|
||||||
|
def impersonate_end(self, request: Request) -> Response:
|
||||||
|
"""End Impersonation a user"""
|
||||||
|
if (
|
||||||
|
SESSION_KEY_IMPERSONATE_USER not in request.session
|
||||||
|
or SESSION_KEY_IMPERSONATE_ORIGINAL_USER not in request.session
|
||||||
|
):
|
||||||
|
LOGGER.debug("Can't end impersonation", user=request.user)
|
||||||
|
return Response(status=204)
|
||||||
|
|
||||||
|
original_user = request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER]
|
||||||
|
|
||||||
|
del request.session[SESSION_KEY_IMPERSONATE_USER]
|
||||||
|
del request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER]
|
||||||
|
|
||||||
|
Event.new(EventAction.IMPERSONATION_ENDED).from_http(request, original_user)
|
||||||
|
|
||||||
|
return Response(status=204)
|
||||||
|
|
||||||
def _filter_queryset_for_list(self, queryset: QuerySet) -> QuerySet:
|
def _filter_queryset_for_list(self, queryset: QuerySet) -> QuerySet:
|
||||||
"""Custom filter_queryset method which ignores guardian, but still supports sorting"""
|
"""Custom filter_queryset method which ignores guardian, but still supports sorting"""
|
||||||
for backend in list(self.filter_backends):
|
for backend in list(self.filter_backends):
|
||||||
|
@ -11,7 +11,6 @@ class AuthentikCoreConfig(ManagedAppConfig):
|
|||||||
label = "authentik_core"
|
label = "authentik_core"
|
||||||
verbose_name = "authentik Core"
|
verbose_name = "authentik Core"
|
||||||
mountpoint = ""
|
mountpoint = ""
|
||||||
ws_mountpoint = "authentik.core.urls"
|
|
||||||
default = True
|
default = True
|
||||||
|
|
||||||
def reconcile_load_core_signals(self):
|
def reconcile_load_core_signals(self):
|
||||||
|
@ -0,0 +1,82 @@
|
|||||||
|
# Generated by Django 4.1.7 on 2023-04-30 17:56
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.apps.registry import Apps
|
||||||
|
from django.db import DatabaseError, InternalError, ProgrammingError, migrations, models
|
||||||
|
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
|
||||||
|
|
||||||
|
|
||||||
|
def backport_is_backchannel(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
|
||||||
|
from authentik.core.models import BackchannelProvider
|
||||||
|
|
||||||
|
for model in BackchannelProvider.__subclasses__():
|
||||||
|
try:
|
||||||
|
for obj in model.objects.all():
|
||||||
|
obj.is_backchannel = True
|
||||||
|
obj.save()
|
||||||
|
except (DatabaseError, InternalError, ProgrammingError):
|
||||||
|
# The model might not have been migrated yet/doesn't exist yet
|
||||||
|
# so we don't need to worry about backporting the data
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("authentik_core", "0028_provider_authentication_flow"),
|
||||||
|
("authentik_providers_ldap", "0002_ldapprovider_bind_mode"),
|
||||||
|
("authentik_providers_scim", "0006_rename_parent_group_scimprovider_filter_group"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="provider",
|
||||||
|
name="backchannel_application",
|
||||||
|
field=models.ForeignKey(
|
||||||
|
default=None,
|
||||||
|
help_text="Accessed from applications; optional backchannel providers for protocols like LDAP and SCIM.",
|
||||||
|
null=True,
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="backchannel_providers",
|
||||||
|
to="authentik_core.application",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="provider",
|
||||||
|
name="is_backchannel",
|
||||||
|
field=models.BooleanField(default=False),
|
||||||
|
),
|
||||||
|
migrations.RunPython(backport_is_backchannel),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="propertymapping",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="source",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="token",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -270,6 +270,20 @@ class Provider(SerializerModel):
|
|||||||
|
|
||||||
property_mappings = models.ManyToManyField("PropertyMapping", default=None, blank=True)
|
property_mappings = models.ManyToManyField("PropertyMapping", default=None, blank=True)
|
||||||
|
|
||||||
|
backchannel_application = models.ForeignKey(
|
||||||
|
"Application",
|
||||||
|
default=None,
|
||||||
|
null=True,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
help_text=_(
|
||||||
|
"Accessed from applications; optional backchannel providers for protocols "
|
||||||
|
"like LDAP and SCIM."
|
||||||
|
),
|
||||||
|
related_name="backchannel_providers",
|
||||||
|
)
|
||||||
|
|
||||||
|
is_backchannel = models.BooleanField(default=False)
|
||||||
|
|
||||||
objects = InheritanceManager()
|
objects = InheritanceManager()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -292,6 +306,26 @@ class Provider(SerializerModel):
|
|||||||
return str(self.name)
|
return str(self.name)
|
||||||
|
|
||||||
|
|
||||||
|
class BackchannelProvider(Provider):
|
||||||
|
"""Base class for providers that augment other providers, for example LDAP and SCIM.
|
||||||
|
Multiple of these providers can be configured per application, they may not use the application
|
||||||
|
slug in URLs as an application may have multiple instances of the same
|
||||||
|
type of Backchannel provider
|
||||||
|
|
||||||
|
They can use the application's policies and metadata"""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def component(self) -> str:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@property
|
||||||
|
def serializer(self) -> type[Serializer]:
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
abstract = True
|
||||||
|
|
||||||
|
|
||||||
class Application(SerializerModel, PolicyBindingModel):
|
class Application(SerializerModel, PolicyBindingModel):
|
||||||
"""Every Application which uses authentik for authentication/identification/authorization
|
"""Every Application which uses authentik for authentication/identification/authorization
|
||||||
needs an Application record. Other authentication types can subclass this Model to
|
needs an Application record. Other authentication types can subclass this Model to
|
||||||
|
@ -6,11 +6,11 @@ from django.contrib.sessions.backends.cache import KEY_PREFIX
|
|||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.core.signals import Signal
|
from django.core.signals import Signal
|
||||||
from django.db.models import Model
|
from django.db.models import Model
|
||||||
from django.db.models.signals import post_save, pre_delete
|
from django.db.models.signals import post_save, pre_delete, pre_save
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
from django.http.request import HttpRequest
|
from django.http.request import HttpRequest
|
||||||
|
|
||||||
from authentik.core.models import Application, AuthenticatedSession
|
from authentik.core.models import Application, AuthenticatedSession, BackchannelProvider
|
||||||
|
|
||||||
# Arguments: user: User, password: str
|
# Arguments: user: User, password: str
|
||||||
password_changed = Signal()
|
password_changed = Signal()
|
||||||
@ -54,3 +54,11 @@ def authenticated_session_delete(sender: type[Model], instance: "AuthenticatedSe
|
|||||||
"""Delete session when authenticated session is deleted"""
|
"""Delete session when authenticated session is deleted"""
|
||||||
cache_key = f"{KEY_PREFIX}{instance.session_key}"
|
cache_key = f"{KEY_PREFIX}{instance.session_key}"
|
||||||
cache.delete(cache_key)
|
cache.delete(cache_key)
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(pre_save)
|
||||||
|
def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
|
||||||
|
"""Ensure backchannel providers have is_backchannel set to true"""
|
||||||
|
if not isinstance(instance, BackchannelProvider):
|
||||||
|
return
|
||||||
|
instance.is_backchannel = True
|
||||||
|
@ -28,7 +28,7 @@ from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET, SESSI
|
|||||||
from authentik.lib.utils.urls import redirect_with_qs
|
from authentik.lib.utils.urls import redirect_with_qs
|
||||||
from authentik.lib.views import bad_request_message
|
from authentik.lib.views import bad_request_message
|
||||||
from authentik.policies.denied import AccessDeniedResponse
|
from authentik.policies.denied import AccessDeniedResponse
|
||||||
from authentik.policies.utils import delete_none_keys
|
from authentik.policies.utils import delete_none_values
|
||||||
from authentik.stages.password import BACKEND_INBUILT
|
from authentik.stages.password import BACKEND_INBUILT
|
||||||
from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND
|
from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND
|
||||||
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
|
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
|
||||||
@ -329,7 +329,7 @@ class SourceFlowManager:
|
|||||||
)
|
)
|
||||||
],
|
],
|
||||||
**{
|
**{
|
||||||
PLAN_CONTEXT_PROMPT: delete_none_keys(self.enroll_info),
|
PLAN_CONTEXT_PROMPT: delete_none_values(self.enroll_info),
|
||||||
PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
|
PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<script src="{% static 'dist/user/UserInterface.js' %}?version={{ version }}" type="module"></script>
|
<script src="{% static 'dist/user/UserInterface.js' %}?version={{ version }}" type="module"></script>
|
||||||
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: light)">
|
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: light)">
|
||||||
<meta name="theme-color" content="#151515" media="(prefers-color-scheme: dark)">
|
<meta name="theme-color" content="#1c1e21" media="(prefers-color-scheme: dark)">
|
||||||
<link rel="icon" href="{{ tenant.branding_favicon }}">
|
<link rel="icon" href="{{ tenant.branding_favicon }}">
|
||||||
<link rel="shortcut icon" href="{{ tenant.branding_favicon }}">
|
<link rel="shortcut icon" href="{{ tenant.branding_favicon }}">
|
||||||
{% include "base/header_js.html" %}
|
{% include "base/header_js.html" %}
|
||||||
|
@ -139,6 +139,8 @@ class TestApplicationsAPI(APITestCase):
|
|||||||
"verbose_name": "OAuth2/OpenID Provider",
|
"verbose_name": "OAuth2/OpenID Provider",
|
||||||
"verbose_name_plural": "OAuth2/OpenID Providers",
|
"verbose_name_plural": "OAuth2/OpenID Providers",
|
||||||
},
|
},
|
||||||
|
"backchannel_providers": [],
|
||||||
|
"backchannel_providers_obj": [],
|
||||||
"launch_url": f"https://goauthentik.io/{self.user.username}",
|
"launch_url": f"https://goauthentik.io/{self.user.username}",
|
||||||
"meta_launch_url": "https://goauthentik.io/%(username)s",
|
"meta_launch_url": "https://goauthentik.io/%(username)s",
|
||||||
"open_in_new_tab": True,
|
"open_in_new_tab": True,
|
||||||
@ -189,6 +191,8 @@ class TestApplicationsAPI(APITestCase):
|
|||||||
"verbose_name": "OAuth2/OpenID Provider",
|
"verbose_name": "OAuth2/OpenID Provider",
|
||||||
"verbose_name_plural": "OAuth2/OpenID Providers",
|
"verbose_name_plural": "OAuth2/OpenID Providers",
|
||||||
},
|
},
|
||||||
|
"backchannel_providers": [],
|
||||||
|
"backchannel_providers_obj": [],
|
||||||
"launch_url": f"https://goauthentik.io/{self.user.username}",
|
"launch_url": f"https://goauthentik.io/{self.user.username}",
|
||||||
"meta_launch_url": "https://goauthentik.io/%(username)s",
|
"meta_launch_url": "https://goauthentik.io/%(username)s",
|
||||||
"open_in_new_tab": True,
|
"open_in_new_tab": True,
|
||||||
@ -210,6 +214,8 @@ class TestApplicationsAPI(APITestCase):
|
|||||||
"policy_engine_mode": "any",
|
"policy_engine_mode": "any",
|
||||||
"provider": None,
|
"provider": None,
|
||||||
"provider_obj": None,
|
"provider_obj": None,
|
||||||
|
"backchannel_providers": [],
|
||||||
|
"backchannel_providers_obj": [],
|
||||||
"slug": "denied",
|
"slug": "denied",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
@ -1,14 +1,14 @@
|
|||||||
"""impersonation tests"""
|
"""impersonation tests"""
|
||||||
from json import loads
|
from json import loads
|
||||||
|
|
||||||
from django.test.testcases import TestCase
|
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from authentik.core.models import User
|
from authentik.core.models import User
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
|
||||||
|
|
||||||
class TestImpersonation(TestCase):
|
class TestImpersonation(APITestCase):
|
||||||
"""impersonation tests"""
|
"""impersonation tests"""
|
||||||
|
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
@ -23,10 +23,10 @@ class TestImpersonation(TestCase):
|
|||||||
self.other_user.save()
|
self.other_user.save()
|
||||||
self.client.force_login(self.user)
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
self.client.get(
|
self.client.post(
|
||||||
reverse(
|
reverse(
|
||||||
"authentik_core:impersonate-init",
|
"authentik_api:user-impersonate",
|
||||||
kwargs={"user_id": self.other_user.pk},
|
kwargs={"pk": self.other_user.pk},
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -35,7 +35,7 @@ class TestImpersonation(TestCase):
|
|||||||
self.assertEqual(response_body["user"]["username"], self.other_user.username)
|
self.assertEqual(response_body["user"]["username"], self.other_user.username)
|
||||||
self.assertEqual(response_body["original"]["username"], self.user.username)
|
self.assertEqual(response_body["original"]["username"], self.user.username)
|
||||||
|
|
||||||
self.client.get(reverse("authentik_core:impersonate-end"))
|
self.client.get(reverse("authentik_api:user-impersonate-end"))
|
||||||
|
|
||||||
response = self.client.get(reverse("authentik_api:user-me"))
|
response = self.client.get(reverse("authentik_api:user-me"))
|
||||||
response_body = loads(response.content.decode())
|
response_body = loads(response.content.decode())
|
||||||
@ -46,9 +46,7 @@ class TestImpersonation(TestCase):
|
|||||||
"""test impersonation without permissions"""
|
"""test impersonation without permissions"""
|
||||||
self.client.force_login(self.other_user)
|
self.client.force_login(self.other_user)
|
||||||
|
|
||||||
self.client.get(
|
self.client.get(reverse("authentik_api:user-impersonate", kwargs={"pk": self.user.pk}))
|
||||||
reverse("authentik_core:impersonate-init", kwargs={"user_id": self.user.pk})
|
|
||||||
)
|
|
||||||
|
|
||||||
response = self.client.get(reverse("authentik_api:user-me"))
|
response = self.client.get(reverse("authentik_api:user-me"))
|
||||||
response_body = loads(response.content.decode())
|
response_body = loads(response.content.decode())
|
||||||
@ -58,5 +56,5 @@ class TestImpersonation(TestCase):
|
|||||||
"""test un-impersonation without impersonating first"""
|
"""test un-impersonation without impersonating first"""
|
||||||
self.client.force_login(self.other_user)
|
self.client.force_login(self.other_user)
|
||||||
|
|
||||||
response = self.client.get(reverse("authentik_core:impersonate-end"))
|
response = self.client.get(reverse("authentik_api:user-impersonate-end"))
|
||||||
self.assertRedirects(response, reverse("authentik_core:if-user"))
|
self.assertEqual(response.status_code, 204)
|
||||||
|
@ -53,9 +53,8 @@ def provider_tester_factory(test_model: type[Stage]) -> Callable:
|
|||||||
def tester(self: TestModels):
|
def tester(self: TestModels):
|
||||||
model_class = None
|
model_class = None
|
||||||
if test_model._meta.abstract: # pragma: no cover
|
if test_model._meta.abstract: # pragma: no cover
|
||||||
model_class = test_model.__bases__[0]()
|
return
|
||||||
else:
|
model_class = test_model()
|
||||||
model_class = test_model()
|
|
||||||
self.assertIsNotNone(model_class.component)
|
self.assertIsNotNone(model_class.component)
|
||||||
|
|
||||||
return tester
|
return tester
|
||||||
|
@ -77,6 +77,7 @@ class TestTokenAPI(APITestCase):
|
|||||||
|
|
||||||
def test_list(self):
|
def test_list(self):
|
||||||
"""Test Token List (Test normal authentication)"""
|
"""Test Token List (Test normal authentication)"""
|
||||||
|
Token.objects.all().delete()
|
||||||
token_should: Token = Token.objects.create(
|
token_should: Token = Token.objects.create(
|
||||||
identifier="test", expiring=False, user=self.user
|
identifier="test", expiring=False, user=self.user
|
||||||
)
|
)
|
||||||
@ -88,6 +89,7 @@ class TestTokenAPI(APITestCase):
|
|||||||
|
|
||||||
def test_list_admin(self):
|
def test_list_admin(self):
|
||||||
"""Test Token List (Test with admin auth)"""
|
"""Test Token List (Test with admin auth)"""
|
||||||
|
Token.objects.all().delete()
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.admin)
|
||||||
token_should: Token = Token.objects.create(
|
token_should: Token = Token.objects.create(
|
||||||
identifier="test", expiring=False, user=self.user
|
identifier="test", expiring=False, user=self.user
|
||||||
|
@ -7,12 +7,22 @@ from django.urls import path
|
|||||||
from django.views.decorators.csrf import ensure_csrf_cookie
|
from django.views.decorators.csrf import ensure_csrf_cookie
|
||||||
from django.views.generic import RedirectView
|
from django.views.generic import RedirectView
|
||||||
|
|
||||||
from authentik.core.views import apps, impersonate
|
from authentik.core.api.applications import ApplicationViewSet
|
||||||
|
from authentik.core.api.authenticated_sessions import AuthenticatedSessionViewSet
|
||||||
|
from authentik.core.api.devices import AdminDeviceViewSet, DeviceViewSet
|
||||||
|
from authentik.core.api.groups import GroupViewSet
|
||||||
|
from authentik.core.api.propertymappings import PropertyMappingViewSet
|
||||||
|
from authentik.core.api.providers import ProviderViewSet
|
||||||
|
from authentik.core.api.sources import SourceViewSet, UserSourceConnectionViewSet
|
||||||
|
from authentik.core.api.tokens import TokenViewSet
|
||||||
|
from authentik.core.api.users import UserViewSet
|
||||||
|
from authentik.core.views import apps
|
||||||
from authentik.core.views.debug import AccessDeniedView
|
from authentik.core.views.debug import AccessDeniedView
|
||||||
from authentik.core.views.interface import FlowInterfaceView, InterfaceView
|
from authentik.core.views.interface import FlowInterfaceView, InterfaceView
|
||||||
from authentik.core.views.session import EndSessionView
|
from authentik.core.views.session import EndSessionView
|
||||||
from authentik.root.asgi_middleware import SessionMiddleware
|
from authentik.root.asgi_middleware import SessionMiddleware
|
||||||
from authentik.root.messages.consumer import MessageConsumer
|
from authentik.root.messages.consumer import MessageConsumer
|
||||||
|
from authentik.root.middleware import ChannelsLoggingMiddleware
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path(
|
path(
|
||||||
@ -28,17 +38,6 @@ urlpatterns = [
|
|||||||
apps.RedirectToAppLaunch.as_view(),
|
apps.RedirectToAppLaunch.as_view(),
|
||||||
name="application-launch",
|
name="application-launch",
|
||||||
),
|
),
|
||||||
# Impersonation
|
|
||||||
path(
|
|
||||||
"-/impersonation/<int:user_id>/",
|
|
||||||
impersonate.ImpersonateInitView.as_view(),
|
|
||||||
name="impersonate-init",
|
|
||||||
),
|
|
||||||
path(
|
|
||||||
"-/impersonation/end/",
|
|
||||||
impersonate.ImpersonateEndView.as_view(),
|
|
||||||
name="impersonate-end",
|
|
||||||
),
|
|
||||||
# Interfaces
|
# Interfaces
|
||||||
path(
|
path(
|
||||||
"if/admin/",
|
"if/admin/",
|
||||||
@ -68,9 +67,30 @@ urlpatterns = [
|
|||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("core/authenticated_sessions", AuthenticatedSessionViewSet),
|
||||||
|
("core/applications", ApplicationViewSet),
|
||||||
|
("core/groups", GroupViewSet),
|
||||||
|
("core/users", UserViewSet),
|
||||||
|
("core/tokens", TokenViewSet),
|
||||||
|
("sources/all", SourceViewSet),
|
||||||
|
("sources/user_connections/all", UserSourceConnectionViewSet),
|
||||||
|
("providers/all", ProviderViewSet),
|
||||||
|
("propertymappings/all", PropertyMappingViewSet),
|
||||||
|
("authenticators/all", DeviceViewSet, "device"),
|
||||||
|
(
|
||||||
|
"authenticators/admin/all",
|
||||||
|
AdminDeviceViewSet,
|
||||||
|
"admin-device",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
websocket_urlpatterns = [
|
websocket_urlpatterns = [
|
||||||
path(
|
path(
|
||||||
"ws/client/", CookieMiddleware(SessionMiddleware(AuthMiddleware(MessageConsumer.as_asgi())))
|
"ws/client/",
|
||||||
|
ChannelsLoggingMiddleware(
|
||||||
|
CookieMiddleware(SessionMiddleware(AuthMiddleware(MessageConsumer.as_asgi())))
|
||||||
|
),
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
@ -1,60 +0,0 @@
|
|||||||
"""authentik impersonation views"""
|
|
||||||
|
|
||||||
from django.http import HttpRequest, HttpResponse
|
|
||||||
from django.shortcuts import get_object_or_404, redirect
|
|
||||||
from django.views import View
|
|
||||||
from structlog.stdlib import get_logger
|
|
||||||
|
|
||||||
from authentik.core.middleware import (
|
|
||||||
SESSION_KEY_IMPERSONATE_ORIGINAL_USER,
|
|
||||||
SESSION_KEY_IMPERSONATE_USER,
|
|
||||||
)
|
|
||||||
from authentik.core.models import User
|
|
||||||
from authentik.events.models import Event, EventAction
|
|
||||||
from authentik.lib.config import CONFIG
|
|
||||||
|
|
||||||
LOGGER = get_logger()
|
|
||||||
|
|
||||||
|
|
||||||
class ImpersonateInitView(View):
|
|
||||||
"""Initiate Impersonation"""
|
|
||||||
|
|
||||||
def get(self, request: HttpRequest, user_id: int) -> HttpResponse:
|
|
||||||
"""Impersonation handler, checks permissions"""
|
|
||||||
if not CONFIG.y_bool("impersonation"):
|
|
||||||
LOGGER.debug("User attempted to impersonate", user=request.user)
|
|
||||||
return HttpResponse("Unauthorized", status=401)
|
|
||||||
if not request.user.has_perm("impersonate"):
|
|
||||||
LOGGER.debug("User attempted to impersonate without permissions", user=request.user)
|
|
||||||
return HttpResponse("Unauthorized", status=401)
|
|
||||||
|
|
||||||
user_to_be = get_object_or_404(User, pk=user_id)
|
|
||||||
|
|
||||||
request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER] = request.user
|
|
||||||
request.session[SESSION_KEY_IMPERSONATE_USER] = user_to_be
|
|
||||||
|
|
||||||
Event.new(EventAction.IMPERSONATION_STARTED).from_http(request, user_to_be)
|
|
||||||
|
|
||||||
return redirect("authentik_core:if-user")
|
|
||||||
|
|
||||||
|
|
||||||
class ImpersonateEndView(View):
|
|
||||||
"""End User impersonation"""
|
|
||||||
|
|
||||||
def get(self, request: HttpRequest) -> HttpResponse:
|
|
||||||
"""End Impersonation handler"""
|
|
||||||
if (
|
|
||||||
SESSION_KEY_IMPERSONATE_USER not in request.session
|
|
||||||
or SESSION_KEY_IMPERSONATE_ORIGINAL_USER not in request.session
|
|
||||||
):
|
|
||||||
LOGGER.debug("Can't end impersonation", user=request.user)
|
|
||||||
return redirect("authentik_core:if-user")
|
|
||||||
|
|
||||||
original_user = request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER]
|
|
||||||
|
|
||||||
del request.session[SESSION_KEY_IMPERSONATE_USER]
|
|
||||||
del request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER]
|
|
||||||
|
|
||||||
Event.new(EventAction.IMPERSONATION_ENDED).from_http(request, original_user)
|
|
||||||
|
|
||||||
return redirect("authentik_core:root-redirect")
|
|
@ -160,6 +160,7 @@ class CertificateKeyPairSerializer(ModelSerializer):
|
|||||||
"managed",
|
"managed",
|
||||||
]
|
]
|
||||||
extra_kwargs = {
|
extra_kwargs = {
|
||||||
|
"managed": {"read_only": True},
|
||||||
"key_data": {"write_only": True},
|
"key_data": {"write_only": True},
|
||||||
"certificate_data": {"write_only": True},
|
"certificate_data": {"write_only": True},
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,31 @@
|
|||||||
|
# Generated by Django 4.1.7 on 2023-04-28 10:49
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
from authentik.lib.migrations import fallback_names
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("authentik_crypto", "0003_certificatekeypair_managed"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(fallback_names("authentik_crypto", "certificatekeypair", "name")),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="certificatekeypair",
|
||||||
|
name="name",
|
||||||
|
field=models.TextField(unique=True),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="certificatekeypair",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
@ -26,7 +26,7 @@ class CertificateKeyPair(SerializerModel, ManagedModel, CreatedUpdatedModel):
|
|||||||
|
|
||||||
kp_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
kp_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
|
||||||
|
|
||||||
name = models.TextField()
|
name = models.TextField(unique=True)
|
||||||
certificate_data = models.TextField(help_text=_("PEM-encoded Certificate data"))
|
certificate_data = models.TextField(help_text=_("PEM-encoded Certificate data"))
|
||||||
key_data = models.TextField(
|
key_data = models.TextField(
|
||||||
help_text=_(
|
help_text=_(
|
||||||
|
@ -37,20 +37,22 @@ class TestCrypto(APITestCase):
|
|||||||
keypair = create_test_cert()
|
keypair = create_test_cert()
|
||||||
self.assertTrue(
|
self.assertTrue(
|
||||||
CertificateKeyPairSerializer(
|
CertificateKeyPairSerializer(
|
||||||
|
instance=keypair,
|
||||||
data={
|
data={
|
||||||
"name": keypair.name,
|
"name": keypair.name,
|
||||||
"certificate_data": keypair.certificate_data,
|
"certificate_data": keypair.certificate_data,
|
||||||
"key_data": keypair.key_data,
|
"key_data": keypair.key_data,
|
||||||
}
|
},
|
||||||
).is_valid()
|
).is_valid()
|
||||||
)
|
)
|
||||||
self.assertFalse(
|
self.assertFalse(
|
||||||
CertificateKeyPairSerializer(
|
CertificateKeyPairSerializer(
|
||||||
|
instance=keypair,
|
||||||
data={
|
data={
|
||||||
"name": keypair.name,
|
"name": keypair.name,
|
||||||
"certificate_data": "test",
|
"certificate_data": "test",
|
||||||
"key_data": "test",
|
"key_data": "test",
|
||||||
}
|
},
|
||||||
).is_valid()
|
).is_valid()
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -246,7 +248,6 @@ class TestCrypto(APITestCase):
|
|||||||
with open(f"{temp_dir}/foo.bar/privkey.pem", "w+", encoding="utf-8") as _key:
|
with open(f"{temp_dir}/foo.bar/privkey.pem", "w+", encoding="utf-8") as _key:
|
||||||
_key.write(builder.private_key)
|
_key.write(builder.private_key)
|
||||||
with CONFIG.patch("cert_discovery_dir", temp_dir):
|
with CONFIG.patch("cert_discovery_dir", temp_dir):
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
certificate_discovery() # pylint: disable=no-value-for-parameter
|
certificate_discovery() # pylint: disable=no-value-for-parameter
|
||||||
keypair: CertificateKeyPair = CertificateKeyPair.objects.filter(
|
keypair: CertificateKeyPair = CertificateKeyPair.objects.filter(
|
||||||
managed=MANAGED_DISCOVERED % "foo"
|
managed=MANAGED_DISCOVERED % "foo"
|
||||||
|
6
authentik/crypto/urls.py
Normal file
6
authentik/crypto/urls.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.crypto.api import CertificateKeyPairViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("crypto/certificatekeypairs", CertificateKeyPairViewSet),
|
||||||
|
]
|
@ -7,7 +7,6 @@ from smtplib import SMTPException
|
|||||||
from typing import TYPE_CHECKING, Optional
|
from typing import TYPE_CHECKING, Optional
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.db.models import Count, ExpressionWrapper, F
|
from django.db.models import Count, ExpressionWrapper, F
|
||||||
from django.db.models.fields import DurationField
|
from django.db.models.fields import DurationField
|
||||||
@ -207,9 +206,7 @@ class Event(SerializerModel, ExpiringModel):
|
|||||||
self.user = get_user(user)
|
self.user = get_user(user)
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def from_http(
|
def from_http(self, request: HttpRequest, user: Optional[User] = None) -> "Event":
|
||||||
self, request: HttpRequest, user: Optional[settings.AUTH_USER_MODEL] = None
|
|
||||||
) -> "Event":
|
|
||||||
"""Add data from a Django-HttpRequest, allowing the creation of
|
"""Add data from a Django-HttpRequest, allowing the creation of
|
||||||
Events independently from requests.
|
Events independently from requests.
|
||||||
`user` arguments optionally overrides user from requests."""
|
`user` arguments optionally overrides user from requests."""
|
||||||
@ -219,13 +216,13 @@ class Event(SerializerModel, ExpiringModel):
|
|||||||
self.context["http_request"] = {
|
self.context["http_request"] = {
|
||||||
"path": request.path,
|
"path": request.path,
|
||||||
"method": request.method,
|
"method": request.method,
|
||||||
"args": QueryDict(request.META.get("QUERY_STRING", "")),
|
"args": cleanse_dict(QueryDict(request.META.get("QUERY_STRING", ""))),
|
||||||
}
|
}
|
||||||
# Special case for events created during flow execution
|
# Special case for events created during flow execution
|
||||||
# since they keep the http query within a wrapped query
|
# since they keep the http query within a wrapped query
|
||||||
if QS_QUERY in self.context["http_request"]["args"]:
|
if QS_QUERY in self.context["http_request"]["args"]:
|
||||||
wrapped = self.context["http_request"]["args"][QS_QUERY]
|
wrapped = self.context["http_request"]["args"][QS_QUERY]
|
||||||
self.context["http_request"]["args"] = QueryDict(wrapped)
|
self.context["http_request"]["args"] = cleanse_dict(QueryDict(wrapped))
|
||||||
if hasattr(request, "tenant"):
|
if hasattr(request, "tenant"):
|
||||||
tenant: Tenant = request.tenant
|
tenant: Tenant = request.tenant
|
||||||
# Because self.created only gets set on save, we can't use it's value here
|
# Because self.created only gets set on save, we can't use it's value here
|
||||||
@ -353,6 +350,9 @@ class NotificationTransport(SerializerModel):
|
|||||||
"user_email": notification.user.email,
|
"user_email": notification.user.email,
|
||||||
"user_username": notification.user.username,
|
"user_username": notification.user.username,
|
||||||
}
|
}
|
||||||
|
if notification.event and notification.event.user:
|
||||||
|
default_body["event_user_email"] = notification.event.user.get("email", None)
|
||||||
|
default_body["event_user_username"] = notification.event.user.get("username", None)
|
||||||
if self.webhook_mapping:
|
if self.webhook_mapping:
|
||||||
default_body = sanitize_item(
|
default_body = sanitize_item(
|
||||||
self.webhook_mapping.evaluate(
|
self.webhook_mapping.evaluate(
|
||||||
@ -391,6 +391,14 @@ class NotificationTransport(SerializerModel):
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
if notification.event:
|
if notification.event:
|
||||||
|
if notification.event.user:
|
||||||
|
fields.append(
|
||||||
|
{
|
||||||
|
"title": _("Event user"),
|
||||||
|
"value": str(notification.event.user.get("username")),
|
||||||
|
"short": True,
|
||||||
|
},
|
||||||
|
)
|
||||||
for key, value in notification.event.context.items():
|
for key, value in notification.event.context.items():
|
||||||
if not isinstance(value, str):
|
if not isinstance(value, str):
|
||||||
continue
|
continue
|
||||||
@ -429,7 +437,13 @@ class NotificationTransport(SerializerModel):
|
|||||||
def send_email(self, notification: "Notification") -> list[str]:
|
def send_email(self, notification: "Notification") -> list[str]:
|
||||||
"""Send notification via global email configuration"""
|
"""Send notification via global email configuration"""
|
||||||
subject = "authentik Notification: "
|
subject = "authentik Notification: "
|
||||||
key_value = {}
|
key_value = {
|
||||||
|
"user_email": notification.user.email,
|
||||||
|
"user_username": notification.user.username,
|
||||||
|
}
|
||||||
|
if notification.event and notification.event.user:
|
||||||
|
key_value["event_user_email"] = notification.event.user.get("email", None)
|
||||||
|
key_value["event_user_username"] = notification.event.user.get("username", None)
|
||||||
if notification.event:
|
if notification.event:
|
||||||
subject += notification.event.action
|
subject += notification.event.action
|
||||||
for key, value in notification.event.context.items():
|
for key, value in notification.event.context.items():
|
||||||
@ -453,7 +467,6 @@ class NotificationTransport(SerializerModel):
|
|||||||
try:
|
try:
|
||||||
from authentik.stages.email.tasks import send_mail
|
from authentik.stages.email.tasks import send_mail
|
||||||
|
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
return send_mail(mail.__dict__) # pylint: disable=no-value-for-parameter
|
return send_mail(mail.__dict__) # pylint: disable=no-value-for-parameter
|
||||||
except (SMTPException, ConnectionError, OSError) as exc:
|
except (SMTPException, ConnectionError, OSError) as exc:
|
||||||
raise NotificationTransportError(exc) from exc
|
raise NotificationTransportError(exc) from exc
|
||||||
|
@ -87,9 +87,9 @@ class TaskInfo:
|
|||||||
except TypeError:
|
except TypeError:
|
||||||
duration = 0
|
duration = 0
|
||||||
GAUGE_TASKS.labels(
|
GAUGE_TASKS.labels(
|
||||||
task_name=self.task_name,
|
task_name=self.task_name.split(":")[0],
|
||||||
task_uid=self.result.uid or "",
|
task_uid=self.result.uid or "",
|
||||||
status=self.result.status,
|
status=self.result.status.value,
|
||||||
).set(duration)
|
).set(duration)
|
||||||
|
|
||||||
def save(self, timeout_hours=6):
|
def save(self, timeout_hours=6):
|
||||||
|
@ -1,17 +1,25 @@
|
|||||||
"""event tests"""
|
"""event tests"""
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
from django.contrib.contenttypes.models import ContentType
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.test import TestCase
|
from django.test import RequestFactory, TestCase
|
||||||
|
from django.views.debug import SafeExceptionReporterFilter
|
||||||
from guardian.shortcuts import get_anonymous_user
|
from guardian.shortcuts import get_anonymous_user
|
||||||
|
|
||||||
from authentik.core.models import Group
|
from authentik.core.models import Group
|
||||||
from authentik.events.models import Event
|
from authentik.events.models import Event
|
||||||
|
from authentik.flows.views.executor import QS_QUERY
|
||||||
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.policies.dummy.models import DummyPolicy
|
from authentik.policies.dummy.models import DummyPolicy
|
||||||
|
from authentik.tenants.models import Tenant
|
||||||
|
|
||||||
|
|
||||||
class TestEvents(TestCase):
|
class TestEvents(TestCase):
|
||||||
"""Test Event"""
|
"""Test Event"""
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.factory = RequestFactory()
|
||||||
|
|
||||||
def test_new_with_model(self):
|
def test_new_with_model(self):
|
||||||
"""Create a new Event passing a model as kwarg"""
|
"""Create a new Event passing a model as kwarg"""
|
||||||
test_model = Group.objects.create(name="test")
|
test_model = Group.objects.create(name="test")
|
||||||
@ -40,3 +48,58 @@ class TestEvents(TestCase):
|
|||||||
model_content_type = ContentType.objects.get_for_model(temp_model)
|
model_content_type = ContentType.objects.get_for_model(temp_model)
|
||||||
self.assertEqual(event.context.get("model").get("app"), model_content_type.app_label)
|
self.assertEqual(event.context.get("model").get("app"), model_content_type.app_label)
|
||||||
self.assertEqual(event.context.get("model").get("pk"), temp_model.pk.hex)
|
self.assertEqual(event.context.get("model").get("pk"), temp_model.pk.hex)
|
||||||
|
|
||||||
|
def test_from_http_basic(self):
|
||||||
|
"""Test plain from_http"""
|
||||||
|
event = Event.new("unittest").from_http(self.factory.get("/"))
|
||||||
|
self.assertEqual(
|
||||||
|
event.context, {"http_request": {"args": {}, "method": "GET", "path": "/"}}
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_from_http_clean_querystring(self):
|
||||||
|
"""Test cleansing query string"""
|
||||||
|
request = self.factory.get(f"/?token={generate_id()}")
|
||||||
|
event = Event.new("unittest").from_http(request)
|
||||||
|
self.assertEqual(
|
||||||
|
event.context,
|
||||||
|
{
|
||||||
|
"http_request": {
|
||||||
|
"args": {"token": SafeExceptionReporterFilter.cleansed_substitute},
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_from_http_clean_querystring_flow(self):
|
||||||
|
"""Test cleansing query string (nested query string like flow executor)"""
|
||||||
|
nested_qs = {"token": generate_id()}
|
||||||
|
request = self.factory.get(f"/?{QS_QUERY}={urlencode(nested_qs)}")
|
||||||
|
event = Event.new("unittest").from_http(request)
|
||||||
|
self.assertEqual(
|
||||||
|
event.context,
|
||||||
|
{
|
||||||
|
"http_request": {
|
||||||
|
"args": {"token": SafeExceptionReporterFilter.cleansed_substitute},
|
||||||
|
"method": "GET",
|
||||||
|
"path": "/",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_from_http_tenant(self):
|
||||||
|
"""Test from_http tenant"""
|
||||||
|
# Test tenant
|
||||||
|
request = self.factory.get("/")
|
||||||
|
tenant = Tenant(domain="test-tenant")
|
||||||
|
setattr(request, "tenant", tenant)
|
||||||
|
event = Event.new("unittest").from_http(request)
|
||||||
|
self.assertEqual(
|
||||||
|
event.tenant,
|
||||||
|
{
|
||||||
|
"app": "authentik_tenants",
|
||||||
|
"model_name": "tenant",
|
||||||
|
"name": "Tenant test-tenant",
|
||||||
|
"pk": tenant.pk.hex,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
@ -52,6 +52,8 @@ class TestEventTransports(TestCase):
|
|||||||
"severity": "alert",
|
"severity": "alert",
|
||||||
"user_email": self.user.email,
|
"user_email": self.user.email,
|
||||||
"user_username": self.user.username,
|
"user_username": self.user.username,
|
||||||
|
"event_user_email": self.user.email,
|
||||||
|
"event_user_username": self.user.username,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -107,6 +109,7 @@ class TestEventTransports(TestCase):
|
|||||||
"value": self.user.username,
|
"value": self.user.username,
|
||||||
"short": True,
|
"short": True,
|
||||||
},
|
},
|
||||||
|
{"short": True, "title": "Event user", "value": self.user.username},
|
||||||
{"title": "foo", "value": "bar,"},
|
{"title": "foo", "value": "bar,"},
|
||||||
],
|
],
|
||||||
"footer": f"authentik {get_full_version()}",
|
"footer": f"authentik {get_full_version()}",
|
||||||
|
14
authentik/events/urls.py
Normal file
14
authentik/events/urls.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.events.api.events import EventViewSet
|
||||||
|
from authentik.events.api.notification_mappings import NotificationWebhookMappingViewSet
|
||||||
|
from authentik.events.api.notification_rules import NotificationRuleViewSet
|
||||||
|
from authentik.events.api.notification_transports import NotificationTransportViewSet
|
||||||
|
from authentik.events.api.notifications import NotificationViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("events/events", EventViewSet),
|
||||||
|
("events/notifications", NotificationViewSet),
|
||||||
|
("events/transports", NotificationTransportViewSet),
|
||||||
|
("events/rules", NotificationRuleViewSet),
|
||||||
|
("propertymappings/notification", NotificationWebhookMappingViewSet),
|
||||||
|
]
|
@ -2,6 +2,7 @@
|
|||||||
import re
|
import re
|
||||||
from copy import copy
|
from copy import copy
|
||||||
from dataclasses import asdict, is_dataclass
|
from dataclasses import asdict, is_dataclass
|
||||||
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from types import GeneratorType
|
from types import GeneratorType
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
@ -126,6 +127,8 @@ def sanitize_item(value: Any) -> Any:
|
|||||||
return str(value)
|
return str(value)
|
||||||
if isinstance(value, YAMLTag):
|
if isinstance(value, YAMLTag):
|
||||||
return str(value)
|
return str(value)
|
||||||
|
if isinstance(value, Enum):
|
||||||
|
return value.value
|
||||||
if isinstance(value, type):
|
if isinstance(value, type):
|
||||||
return {
|
return {
|
||||||
"type": value.__name__,
|
"type": value.__name__,
|
||||||
|
@ -6,7 +6,7 @@ from django.utils.translation import gettext as _
|
|||||||
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.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import BooleanField, DictField, ListField, ReadOnlyField
|
from rest_framework.fields import BooleanField, CharField, DictField, ListField, ReadOnlyField
|
||||||
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
|
||||||
@ -16,7 +16,7 @@ from structlog.stdlib import get_logger
|
|||||||
|
|
||||||
from authentik.api.decorators import permission_required
|
from authentik.api.decorators import permission_required
|
||||||
from authentik.blueprints.v1.exporter import FlowExporter
|
from authentik.blueprints.v1.exporter import FlowExporter
|
||||||
from authentik.blueprints.v1.importer import Importer
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, Importer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import CacheSerializer, LinkSerializer, PassiveSerializer
|
from authentik.core.api.utils import CacheSerializer, LinkSerializer, PassiveSerializer
|
||||||
from authentik.events.utils import sanitize_dict
|
from authentik.events.utils import sanitize_dict
|
||||||
@ -52,6 +52,11 @@ class FlowSerializer(ModelSerializer):
|
|||||||
"""Get export URL for flow"""
|
"""Get export URL for flow"""
|
||||||
return reverse("authentik_api:flow-export", kwargs={"slug": flow.slug})
|
return reverse("authentik_api:flow-export", kwargs={"slug": flow.slug})
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs) -> None:
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
if SERIALIZER_CONTEXT_BLUEPRINT in self.context:
|
||||||
|
self.fields["background"] = CharField(required=False)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
model = Flow
|
model = Flow
|
||||||
fields = [
|
fields = [
|
||||||
|
@ -23,7 +23,8 @@ class DiagramElement:
|
|||||||
style: list[str] = field(default_factory=lambda: ["[", "]"])
|
style: list[str] = field(default_factory=lambda: ["[", "]"])
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
element = f'{self.identifier}{self.style[0]}"{self.description}"{self.style[1]}'
|
description = self.description.replace('"', "#quot;")
|
||||||
|
element = f'{self.identifier}{self.style[0]}"{description}"{self.style[1]}'
|
||||||
if self.action is not None:
|
if self.action is not None:
|
||||||
if self.action != "":
|
if self.action != "":
|
||||||
element = f"--{self.action}--> {element}"
|
element = f"--{self.action}--> {element}"
|
||||||
|
@ -27,7 +27,6 @@ class StageSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
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"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if obj.__class__ == Stage:
|
if obj.__class__ == Stage:
|
||||||
return ""
|
return ""
|
||||||
return obj.component
|
return obj.component
|
||||||
|
@ -182,5 +182,4 @@ class HttpChallengeResponse(JsonResponse):
|
|||||||
"""Subclass of JsonResponse that uses the `DataclassEncoder`"""
|
"""Subclass of JsonResponse that uses the `DataclassEncoder`"""
|
||||||
|
|
||||||
def __init__(self, challenge, **kwargs) -> None:
|
def __init__(self, challenge, **kwargs) -> None:
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
super().__init__(challenge.data, encoder=DataclassEncoder, **kwargs)
|
super().__init__(challenge.data, encoder=DataclassEncoder, **kwargs)
|
||||||
|
@ -204,12 +204,12 @@ class ChallengeStageView(StageView):
|
|||||||
for field, errors in response.errors.items():
|
for field, errors in response.errors.items():
|
||||||
for error in errors:
|
for error in errors:
|
||||||
full_errors.setdefault(field, [])
|
full_errors.setdefault(field, [])
|
||||||
full_errors[field].append(
|
field_error = {
|
||||||
{
|
"string": str(error),
|
||||||
"string": str(error),
|
}
|
||||||
"code": error.code,
|
if hasattr(error, "code"):
|
||||||
}
|
field_error["code"] = error.code
|
||||||
)
|
full_errors[field].append(field_error)
|
||||||
challenge_response.initial_data["response_errors"] = full_errors
|
challenge_response.initial_data["response_errors"] = full_errors
|
||||||
if not challenge_response.is_valid():
|
if not challenge_response.is_valid():
|
||||||
self.logger.error(
|
self.logger.error(
|
||||||
|
@ -1,8 +1,17 @@
|
|||||||
"""flow urls"""
|
"""flow urls"""
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
|
from authentik.flows.api.bindings import FlowStageBindingViewSet
|
||||||
|
from authentik.flows.api.flows import FlowViewSet
|
||||||
|
from authentik.flows.api.stages import StageViewSet
|
||||||
from authentik.flows.models import FlowDesignation
|
from authentik.flows.models import FlowDesignation
|
||||||
from authentik.flows.views.executor import CancelView, ConfigureFlowInitView, ToDefaultFlow
|
from authentik.flows.views.executor import (
|
||||||
|
CancelView,
|
||||||
|
ConfigureFlowInitView,
|
||||||
|
FlowExecutorView,
|
||||||
|
ToDefaultFlow,
|
||||||
|
)
|
||||||
|
from authentik.flows.views.inspector import FlowInspectorView
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path(
|
path(
|
||||||
@ -22,3 +31,19 @@ urlpatterns = [
|
|||||||
name="configure",
|
name="configure",
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("flows/instances", FlowViewSet),
|
||||||
|
("flows/bindings", FlowStageBindingViewSet),
|
||||||
|
("stages/all", StageViewSet),
|
||||||
|
path(
|
||||||
|
"flows/executor/<slug:flow_slug>/",
|
||||||
|
FlowExecutorView.as_view(),
|
||||||
|
name="flow-executor",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"flows/inspector/<slug:flow_slug>/",
|
||||||
|
FlowInspectorView.as_view(),
|
||||||
|
name="flow-inspector",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
@ -5,6 +5,7 @@ from contextlib import contextmanager
|
|||||||
from glob import glob
|
from glob import glob
|
||||||
from json import dumps, loads
|
from json import dumps, loads
|
||||||
from json.decoder import JSONDecodeError
|
from json.decoder import JSONDecodeError
|
||||||
|
from pathlib import Path
|
||||||
from sys import argv, stderr
|
from sys import argv, stderr
|
||||||
from time import time
|
from time import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@ -42,22 +43,25 @@ class ConfigLoader:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.__config = {}
|
self.__config = {}
|
||||||
base_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "../.."))
|
base_dir = Path(__file__).parent.joinpath(Path("../..")).resolve()
|
||||||
for path in SEARCH_PATHS:
|
for _path in SEARCH_PATHS:
|
||||||
|
path = Path(_path)
|
||||||
# Check if path is relative, and if so join with base_dir
|
# Check if path is relative, and if so join with base_dir
|
||||||
if not os.path.isabs(path):
|
if not path.is_absolute():
|
||||||
path = os.path.join(base_dir, path)
|
path = base_dir / path
|
||||||
if os.path.isfile(path) and os.path.exists(path):
|
if path.is_file() and path.exists():
|
||||||
# Path is an existing file, so we just read it and update our config with it
|
# Path is an existing file, so we just read it and update our config with it
|
||||||
self.update_from_file(path)
|
self.update_from_file(path)
|
||||||
elif os.path.isdir(path) and os.path.exists(path):
|
elif path.is_dir() and path.exists():
|
||||||
# Path is an existing dir, so we try to read the env config from it
|
# Path is an existing dir, so we try to read the env config from it
|
||||||
env_paths = [
|
env_paths = [
|
||||||
os.path.join(path, ENVIRONMENT + ".yml"),
|
path / Path(ENVIRONMENT + ".yml"),
|
||||||
os.path.join(path, ENVIRONMENT + ".env.yml"),
|
path / Path(ENVIRONMENT + ".env.yml"),
|
||||||
|
path / Path(ENVIRONMENT + ".yaml"),
|
||||||
|
path / Path(ENVIRONMENT + ".env.yaml"),
|
||||||
]
|
]
|
||||||
for env_file in env_paths:
|
for env_file in env_paths:
|
||||||
if os.path.isfile(env_file) and os.path.exists(env_file):
|
if env_file.is_file() and env_file.exists():
|
||||||
# Update config with env file
|
# Update config with env file
|
||||||
self.update_from_file(env_file)
|
self.update_from_file(env_file)
|
||||||
self.update_from_env()
|
self.update_from_env()
|
||||||
@ -99,13 +103,13 @@ class ConfigLoader:
|
|||||||
value = url.query
|
value = url.query
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def update_from_file(self, path: str):
|
def update_from_file(self, path: Path):
|
||||||
"""Update config from file contents"""
|
"""Update config from file contents"""
|
||||||
try:
|
try:
|
||||||
with open(path, encoding="utf8") as file:
|
with open(path, encoding="utf8") as file:
|
||||||
try:
|
try:
|
||||||
self.update(self.__config, yaml.safe_load(file))
|
self.update(self.__config, yaml.safe_load(file))
|
||||||
self.log("debug", "Loaded config", file=path)
|
self.log("debug", "Loaded config", file=str(path))
|
||||||
self.loaded_file.append(path)
|
self.loaded_file.append(path)
|
||||||
except yaml.YAMLError as exc:
|
except yaml.YAMLError as exc:
|
||||||
raise ImproperlyConfigured from exc
|
raise ImproperlyConfigured from exc
|
||||||
@ -177,7 +181,6 @@ class ConfigLoader:
|
|||||||
# Walk each component of the path
|
# Walk each component of the path
|
||||||
path_parts = path.split(sep)
|
path_parts = path.split(sep)
|
||||||
for comp in path_parts[:-1]:
|
for comp in path_parts[:-1]:
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if comp not in root:
|
if comp not in root:
|
||||||
root[comp] = {}
|
root[comp] = {}
|
||||||
root = root.get(comp, {})
|
root = root.get(comp, {})
|
||||||
|
@ -5,18 +5,25 @@ postgresql:
|
|||||||
name: authentik
|
name: authentik
|
||||||
user: authentik
|
user: authentik
|
||||||
port: 5432
|
port: 5432
|
||||||
password: 'env://POSTGRES_PASSWORD'
|
password: "env://POSTGRES_PASSWORD"
|
||||||
use_pgbouncer: false
|
use_pgbouncer: false
|
||||||
|
|
||||||
listen:
|
listen:
|
||||||
listen_http: 0.0.0.0:9000
|
listen_http: 0.0.0.0:9000
|
||||||
listen_https: 0.0.0.0:9443
|
listen_https: 0.0.0.0:9443
|
||||||
listen_metrics: 0.0.0.0:9300
|
listen_metrics: 0.0.0.0:9300
|
||||||
|
trusted_proxy_cidrs:
|
||||||
|
- 127.0.0.0/8
|
||||||
|
- 10.0.0.0/8
|
||||||
|
- 172.16.0.0/12
|
||||||
|
- 192.168.0.0/16
|
||||||
|
- fe80::/10
|
||||||
|
- ::1/128
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
host: localhost
|
host: localhost
|
||||||
port: 6379
|
port: 6379
|
||||||
password: ''
|
password: ""
|
||||||
tls: false
|
tls: false
|
||||||
tls_reqs: "none"
|
tls_reqs: "none"
|
||||||
db: 0
|
db: 0
|
||||||
@ -31,7 +38,7 @@ log_level: info
|
|||||||
|
|
||||||
error_reporting:
|
error_reporting:
|
||||||
enabled: false
|
enabled: false
|
||||||
sentry_dsn: https://151ba72610234c4c97c5bcff4e1cffd8@o4504163616882688.ingest.sentry.io/4504163677503489
|
sentry_dsn: https://151ba72610234c4c97c5bcff4e1cffd8@authentik.error-reporting.a7k.io/4504163677503489
|
||||||
environment: customer
|
environment: customer
|
||||||
send_pii: false
|
send_pii: false
|
||||||
sample_rate: 0.1
|
sample_rate: 0.1
|
||||||
@ -77,8 +84,8 @@ geoip: "/geoip/GeoLite2-City.mmdb"
|
|||||||
footer_links: []
|
footer_links: []
|
||||||
|
|
||||||
default_user_change_name: true
|
default_user_change_name: true
|
||||||
default_user_change_email: true
|
default_user_change_email: false
|
||||||
default_user_change_username: true
|
default_user_change_username: false
|
||||||
|
|
||||||
gdpr_compliance: true
|
gdpr_compliance: true
|
||||||
cert_discovery_dir: /certs
|
cert_discovery_dir: /certs
|
||||||
|
@ -140,19 +140,21 @@ class BaseEvaluator:
|
|||||||
def expr_event_create(self, action: str, **kwargs):
|
def expr_event_create(self, action: str, **kwargs):
|
||||||
"""Create event with supplied data and try to extract as much relevant data
|
"""Create event with supplied data and try to extract as much relevant data
|
||||||
from the context"""
|
from the context"""
|
||||||
|
context = self._context.copy()
|
||||||
# If the result was a complex variable, we don't want to re-use it
|
# If the result was a complex variable, we don't want to re-use it
|
||||||
self._context.pop("result", None)
|
context.pop("result", None)
|
||||||
self._context.pop("handler", None)
|
context.pop("handler", None)
|
||||||
kwargs["context"] = self._context
|
event_kwargs = context
|
||||||
|
event_kwargs.update(kwargs)
|
||||||
event = Event.new(
|
event = Event.new(
|
||||||
action,
|
action,
|
||||||
app=self._filename,
|
app=self._filename,
|
||||||
**kwargs,
|
**event_kwargs,
|
||||||
)
|
)
|
||||||
if "request" in self._context and isinstance(self._context["request"], PolicyRequest):
|
if "request" in context and isinstance(context["request"], PolicyRequest):
|
||||||
policy_request: PolicyRequest = self._context["request"]
|
policy_request: PolicyRequest = context["request"]
|
||||||
if policy_request.http_request:
|
if policy_request.http_request:
|
||||||
event.from_http(policy_request)
|
event.from_http(policy_request.http_request)
|
||||||
return
|
return
|
||||||
event.save()
|
event.save()
|
||||||
|
|
||||||
|
@ -19,7 +19,15 @@ def fallback_names(app: str, model: str, field: str):
|
|||||||
if value not in seen_names:
|
if value not in seen_names:
|
||||||
seen_names.append(value)
|
seen_names.append(value)
|
||||||
continue
|
continue
|
||||||
new_value = value + "_2"
|
separator = "_"
|
||||||
|
suffix_index = 2
|
||||||
|
while (
|
||||||
|
klass.objects.using(db_alias)
|
||||||
|
.filter(**{field: f"{value}{separator}{suffix_index}"})
|
||||||
|
.exists()
|
||||||
|
):
|
||||||
|
suffix_index += 1
|
||||||
|
new_value = f"{value}{separator}{suffix_index}"
|
||||||
setattr(obj, field, new_value)
|
setattr(obj, field, new_value)
|
||||||
obj.save()
|
obj.save()
|
||||||
|
|
||||||
|
@ -2,28 +2,41 @@
|
|||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
|
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
class TestEvaluator(TestCase):
|
class TestEvaluator(TestCase):
|
||||||
"""Test Evaluator base functions"""
|
"""Test Evaluator base functions"""
|
||||||
|
|
||||||
def test_regex_match(self):
|
def test_expr_regex_match(self):
|
||||||
"""Test expr_regex_match"""
|
"""Test expr_regex_match"""
|
||||||
self.assertFalse(BaseEvaluator.expr_regex_match("foo", "bar"))
|
self.assertFalse(BaseEvaluator.expr_regex_match("foo", "bar"))
|
||||||
self.assertTrue(BaseEvaluator.expr_regex_match("foo", "foo"))
|
self.assertTrue(BaseEvaluator.expr_regex_match("foo", "foo"))
|
||||||
|
|
||||||
def test_regex_replace(self):
|
def test_expr_regex_replace(self):
|
||||||
"""Test expr_regex_replace"""
|
"""Test expr_regex_replace"""
|
||||||
self.assertEqual(BaseEvaluator.expr_regex_replace("foo", "o", "a"), "faa")
|
self.assertEqual(BaseEvaluator.expr_regex_replace("foo", "o", "a"), "faa")
|
||||||
|
|
||||||
def test_user_by(self):
|
def test_expr_user_by(self):
|
||||||
"""Test expr_user_by"""
|
"""Test expr_user_by"""
|
||||||
user = create_test_admin_user()
|
user = create_test_admin_user()
|
||||||
self.assertIsNotNone(BaseEvaluator.expr_user_by(username=user.username))
|
self.assertIsNotNone(BaseEvaluator.expr_user_by(username=user.username))
|
||||||
self.assertIsNone(BaseEvaluator.expr_user_by(username="bar"))
|
self.assertIsNone(BaseEvaluator.expr_user_by(username="bar"))
|
||||||
self.assertIsNone(BaseEvaluator.expr_user_by(foo="bar"))
|
self.assertIsNone(BaseEvaluator.expr_user_by(foo="bar"))
|
||||||
|
|
||||||
def test_is_group_member(self):
|
def test_expr_is_group_member(self):
|
||||||
"""Test expr_is_group_member"""
|
"""Test expr_is_group_member"""
|
||||||
self.assertFalse(BaseEvaluator.expr_is_group_member(create_test_admin_user(), name="test"))
|
self.assertFalse(BaseEvaluator.expr_is_group_member(create_test_admin_user(), name="test"))
|
||||||
|
|
||||||
|
def test_expr_event_create(self):
|
||||||
|
"""Test expr_event_create"""
|
||||||
|
evaluator = BaseEvaluator(generate_id())
|
||||||
|
evaluator._context = {
|
||||||
|
"foo": "bar",
|
||||||
|
}
|
||||||
|
evaluator.evaluate("ak_create_event('foo', bar='baz')")
|
||||||
|
event = Event.objects.filter(action="custom_foo").first()
|
||||||
|
self.assertIsNotNone(event)
|
||||||
|
self.assertEqual(event.context, {"bar": "baz", "foo": "bar"})
|
||||||
|
@ -16,10 +16,12 @@ LOGGER = get_logger()
|
|||||||
|
|
||||||
def _get_client_ip_from_meta(meta: dict[str, Any]) -> str:
|
def _get_client_ip_from_meta(meta: dict[str, Any]) -> str:
|
||||||
"""Attempt to get the client's IP by checking common HTTP Headers.
|
"""Attempt to get the client's IP by checking common HTTP Headers.
|
||||||
Returns none if no IP Could be found"""
|
Returns none if no IP Could be found
|
||||||
|
|
||||||
|
No additional validation is done here as requests are expected to only arrive here
|
||||||
|
via the go proxy, which deals with validating these headers for us"""
|
||||||
headers = (
|
headers = (
|
||||||
"HTTP_X_FORWARDED_FOR",
|
"HTTP_X_FORWARDED_FOR",
|
||||||
"HTTP_X_REAL_IP",
|
|
||||||
"REMOTE_ADDR",
|
"REMOTE_ADDR",
|
||||||
)
|
)
|
||||||
for _header in headers:
|
for _header in headers:
|
||||||
|
@ -31,7 +31,6 @@ class ServiceConnectionSerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
def get_component(self, obj: OutpostServiceConnection) -> str:
|
def get_component(self, obj: OutpostServiceConnection) -> 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"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if obj.__class__ == OutpostServiceConnection:
|
if obj.__class__ == OutpostServiceConnection:
|
||||||
return ""
|
return ""
|
||||||
return obj.component
|
return obj.component
|
||||||
@ -77,7 +76,6 @@ class ServiceConnectionViewSet(
|
|||||||
data = []
|
data = []
|
||||||
for subclass in all_subclasses(self.queryset.model):
|
for subclass in all_subclasses(self.queryset.model):
|
||||||
subclass: OutpostServiceConnection
|
subclass: OutpostServiceConnection
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
data.append(
|
data.append(
|
||||||
{
|
{
|
||||||
"name": subclass._meta.verbose_name,
|
"name": subclass._meta.verbose_name,
|
||||||
|
@ -24,7 +24,6 @@ class AuthentikOutpostConfig(ManagedAppConfig):
|
|||||||
label = "authentik_outposts"
|
label = "authentik_outposts"
|
||||||
verbose_name = "authentik Outpost"
|
verbose_name = "authentik Outpost"
|
||||||
default = True
|
default = True
|
||||||
ws_mountpoint = "authentik.outposts.urls"
|
|
||||||
|
|
||||||
def reconcile_load_outposts_signals(self):
|
def reconcile_load_outposts_signals(self):
|
||||||
"""Load outposts signals"""
|
"""Load outposts signals"""
|
||||||
|
@ -17,4 +17,15 @@ class Migration(migrations.Migration):
|
|||||||
default="proxy",
|
default="proxy",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="outpost",
|
||||||
|
name="managed",
|
||||||
|
field=models.TextField(
|
||||||
|
default=None,
|
||||||
|
help_text="Objects that are managed by authentik. These objects are created and updated automatically. This flag only indicates that an object can be overwritten by migrations. You can still modify the objects via the API, but expect changes to be overwritten in a later update.",
|
||||||
|
null=True,
|
||||||
|
unique=True,
|
||||||
|
verbose_name="Managed by authentik",
|
||||||
|
),
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
@ -128,7 +128,7 @@ class OutpostServiceConnection(models.Model):
|
|||||||
@property
|
@property
|
||||||
def state_key(self) -> str:
|
def state_key(self) -> str:
|
||||||
"""Key used to save connection state in cache"""
|
"""Key used to save connection state in cache"""
|
||||||
return f"outpost_service_connection_{self.pk.hex}"
|
return f"goauthentik.io/outposts/service_connection_state/{self.pk.hex}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self) -> OutpostServiceConnectionState:
|
def state(self) -> OutpostServiceConnectionState:
|
||||||
@ -278,7 +278,7 @@ class Outpost(SerializerModel, ManagedModel):
|
|||||||
@property
|
@property
|
||||||
def state_cache_prefix(self) -> str:
|
def state_cache_prefix(self) -> str:
|
||||||
"""Key by which the outposts status is saved"""
|
"""Key by which the outposts status is saved"""
|
||||||
return f"goauthentik.io/outposts/{self.uuid.hex}_state"
|
return f"goauthentik.io/outposts/state/{self.uuid.hex}"
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def state(self) -> list["OutpostState"]:
|
def state(self) -> list["OutpostState"]:
|
||||||
@ -433,19 +433,19 @@ class OutpostState:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def for_outpost(outpost: Outpost) -> list["OutpostState"]:
|
def for_outpost(outpost: Outpost) -> list["OutpostState"]:
|
||||||
"""Get all states for an outpost"""
|
"""Get all states for an outpost"""
|
||||||
keys = cache.keys(f"{outpost.state_cache_prefix}_*")
|
keys = cache.keys(f"{outpost.state_cache_prefix}/*")
|
||||||
if not keys:
|
if not keys:
|
||||||
return []
|
return []
|
||||||
states = []
|
states = []
|
||||||
for key in keys:
|
for key in keys:
|
||||||
instance_uid = key.replace(f"{outpost.state_cache_prefix}_", "")
|
instance_uid = key.replace(f"{outpost.state_cache_prefix}/", "")
|
||||||
states.append(OutpostState.for_instance_uid(outpost, instance_uid))
|
states.append(OutpostState.for_instance_uid(outpost, instance_uid))
|
||||||
return states
|
return states
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def for_instance_uid(outpost: Outpost, uid: str) -> "OutpostState":
|
def for_instance_uid(outpost: Outpost, uid: str) -> "OutpostState":
|
||||||
"""Get state for a single instance"""
|
"""Get state for a single instance"""
|
||||||
key = f"{outpost.state_cache_prefix}_{uid}"
|
key = f"{outpost.state_cache_prefix}/{uid}"
|
||||||
default_data = {"uid": uid, "channel_ids": []}
|
default_data = {"uid": uid, "channel_ids": []}
|
||||||
data = cache.get(key, default_data)
|
data = cache.get(key, default_data)
|
||||||
if isinstance(data, str):
|
if isinstance(data, str):
|
||||||
@ -458,10 +458,10 @@ class OutpostState:
|
|||||||
|
|
||||||
def save(self, timeout=OUTPOST_HELLO_INTERVAL):
|
def save(self, timeout=OUTPOST_HELLO_INTERVAL):
|
||||||
"""Save current state to cache"""
|
"""Save current state to cache"""
|
||||||
full_key = f"{self._outpost.state_cache_prefix}_{self.uid}"
|
full_key = f"{self._outpost.state_cache_prefix}/{self.uid}"
|
||||||
return cache.set(full_key, asdict(self), timeout=timeout)
|
return cache.set(full_key, asdict(self), timeout=timeout)
|
||||||
|
|
||||||
def delete(self):
|
def delete(self):
|
||||||
"""Manually delete from cache, used on channel disconnect"""
|
"""Manually delete from cache, used on channel disconnect"""
|
||||||
full_key = f"{self._outpost.state_cache_prefix}_{self.uid}"
|
full_key = f"{self._outpost.state_cache_prefix}/{self.uid}"
|
||||||
cache.delete(full_key)
|
cache.delete(full_key)
|
||||||
|
@ -42,12 +42,15 @@ from authentik.providers.ldap.controllers.docker import LDAPDockerController
|
|||||||
from authentik.providers.ldap.controllers.kubernetes import LDAPKubernetesController
|
from authentik.providers.ldap.controllers.kubernetes import LDAPKubernetesController
|
||||||
from authentik.providers.proxy.controllers.docker import ProxyDockerController
|
from authentik.providers.proxy.controllers.docker import ProxyDockerController
|
||||||
from authentik.providers.proxy.controllers.kubernetes import ProxyKubernetesController
|
from authentik.providers.proxy.controllers.kubernetes import ProxyKubernetesController
|
||||||
|
from authentik.providers.radius.controllers.docker import RadiusDockerController
|
||||||
|
from authentik.providers.radius.controllers.kubernetes import RadiusKubernetesController
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
CACHE_KEY_OUTPOST_DOWN = "outpost_teardown_%s"
|
CACHE_KEY_OUTPOST_DOWN = "goauthentik.io/outposts/teardown/%s"
|
||||||
|
|
||||||
|
|
||||||
|
# pylint: disable=too-many-return-statements
|
||||||
def controller_for_outpost(outpost: Outpost) -> Optional[type[BaseController]]:
|
def controller_for_outpost(outpost: Outpost) -> Optional[type[BaseController]]:
|
||||||
"""Get a controller for the outpost, when a service connection is defined"""
|
"""Get a controller for the outpost, when a service connection is defined"""
|
||||||
if not outpost.service_connection:
|
if not outpost.service_connection:
|
||||||
@ -63,6 +66,11 @@ def controller_for_outpost(outpost: Outpost) -> Optional[type[BaseController]]:
|
|||||||
return LDAPDockerController
|
return LDAPDockerController
|
||||||
if isinstance(service_connection, KubernetesServiceConnection):
|
if isinstance(service_connection, KubernetesServiceConnection):
|
||||||
return LDAPKubernetesController
|
return LDAPKubernetesController
|
||||||
|
if outpost.type == OutpostType.RADIUS:
|
||||||
|
if isinstance(service_connection, DockerServiceConnection):
|
||||||
|
return RadiusDockerController
|
||||||
|
if isinstance(service_connection, KubernetesServiceConnection):
|
||||||
|
return RadiusKubernetesController
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@ -148,6 +156,8 @@ def outpost_controller(
|
|||||||
except (ControllerException, ServiceConnectionInvalid) as exc:
|
except (ControllerException, ServiceConnectionInvalid) as exc:
|
||||||
self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
|
self.set_status(TaskResult(TaskResultStatus.ERROR).with_error(exc))
|
||||||
else:
|
else:
|
||||||
|
if from_cache:
|
||||||
|
cache.delete(CACHE_KEY_OUTPOST_DOWN % outpost_pk)
|
||||||
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, logs))
|
self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, logs))
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,8 +1,22 @@
|
|||||||
"""Outpost Websocket URLS"""
|
"""Outpost Websocket URLS"""
|
||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
|
from authentik.outposts.api.outposts import OutpostViewSet
|
||||||
|
from authentik.outposts.api.service_connections import (
|
||||||
|
DockerServiceConnectionViewSet,
|
||||||
|
KubernetesServiceConnectionViewSet,
|
||||||
|
ServiceConnectionViewSet,
|
||||||
|
)
|
||||||
from authentik.outposts.channels import OutpostConsumer
|
from authentik.outposts.channels import OutpostConsumer
|
||||||
|
from authentik.root.middleware import ChannelsLoggingMiddleware
|
||||||
|
|
||||||
websocket_urlpatterns = [
|
websocket_urlpatterns = [
|
||||||
path("ws/outpost/<uuid:pk>/", OutpostConsumer.as_asgi()),
|
path("ws/outpost/<uuid:pk>/", ChannelsLoggingMiddleware(OutpostConsumer.as_asgi())),
|
||||||
|
]
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("outposts/instances", OutpostViewSet),
|
||||||
|
("outposts/service_connections/all", ServiceConnectionViewSet),
|
||||||
|
("outposts/service_connections/docker", DockerServiceConnectionViewSet),
|
||||||
|
("outposts/service_connections/kubernetes", KubernetesServiceConnectionViewSet),
|
||||||
]
|
]
|
||||||
|
@ -40,7 +40,6 @@ class PolicySerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
|
|
||||||
def get_component(self, obj: Policy) -> str: # pragma: no cover
|
def get_component(self, obj: Policy) -> str: # pragma: no cover
|
||||||
"""Get object component so that we know how to edit the object"""
|
"""Get object component so that we know how to edit the object"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if obj.__class__ == Policy:
|
if obj.__class__ == Policy:
|
||||||
return ""
|
return ""
|
||||||
return obj.component
|
return obj.component
|
||||||
@ -50,7 +49,6 @@ class PolicySerializer(ModelSerializer, MetaNameSerializer):
|
|||||||
return obj.bindings.count() + obj.promptstage_set.count()
|
return obj.bindings.count() + obj.promptstage_set.count()
|
||||||
|
|
||||||
def to_representation(self, instance: Policy):
|
def to_representation(self, instance: Policy):
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if instance.__class__ == Policy or not self._resolve_inheritance:
|
if instance.__class__ == Policy or not self._resolve_inheritance:
|
||||||
return super().to_representation(instance)
|
return super().to_representation(instance)
|
||||||
return dict(instance.serializer(instance=instance, resolve_inheritance=False).data)
|
return dict(instance.serializer(instance=instance, resolve_inheritance=False).data)
|
||||||
|
@ -19,7 +19,6 @@ class AccessDeniedResponse(TemplateResponse):
|
|||||||
error_message: Optional[str] = None
|
error_message: Optional[str] = None
|
||||||
policy_result: Optional[PolicyResult] = None
|
policy_result: Optional[PolicyResult] = None
|
||||||
|
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
def __init__(self, request: HttpRequest, template="policies/denied.html") -> None:
|
def __init__(self, request: HttpRequest, template="policies/denied.html") -> None:
|
||||||
super().__init__(request, template)
|
super().__init__(request, template)
|
||||||
self.title = _("Access denied")
|
self.title = _("Access denied")
|
||||||
|
4
authentik/policies/dummy/urls.py
Normal file
4
authentik/policies/dummy/urls.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.dummy.api import DummyPolicyViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [("policies/dummy", DummyPolicyViewSet)]
|
@ -74,7 +74,6 @@ class PolicyEngine:
|
|||||||
|
|
||||||
def _check_policy_type(self, binding: PolicyBinding):
|
def _check_policy_type(self, binding: PolicyBinding):
|
||||||
"""Check policy type, make sure it's not the root class as that has no logic implemented"""
|
"""Check policy type, make sure it's not the root class as that has no logic implemented"""
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
if binding.policy is not None and binding.policy.__class__ == Policy:
|
if binding.policy is not None and binding.policy.__class__ == Policy:
|
||||||
raise PolicyEngineException(f"Policy '{binding.policy}' is root type")
|
raise PolicyEngineException(f"Policy '{binding.policy}' is root type")
|
||||||
|
|
||||||
|
4
authentik/policies/event_matcher/urls.py
Normal file
4
authentik/policies/event_matcher/urls.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.event_matcher.api import EventMatcherPolicyViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [("policies/event_matcher", EventMatcherPolicyViewSet)]
|
4
authentik/policies/expiry/urls.py
Normal file
4
authentik/policies/expiry/urls.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.expiry.api import PasswordExpiryPolicyViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [("policies/password_expiry", PasswordExpiryPolicyViewSet)]
|
4
authentik/policies/expression/urls.py
Normal file
4
authentik/policies/expression/urls.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.expression.api import ExpressionPolicyViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [("policies/expression", ExpressionPolicyViewSet)]
|
@ -15,8 +15,8 @@ class Migration(migrations.Migration):
|
|||||||
name="policy_engine_mode",
|
name="policy_engine_mode",
|
||||||
field=models.TextField(
|
field=models.TextField(
|
||||||
choices=[
|
choices=[
|
||||||
("all", "ALL, all policies must pass"),
|
("all", "all, all policies must pass"),
|
||||||
("any", "ANY, any policy must pass"),
|
("any", "any, any policy must pass"),
|
||||||
],
|
],
|
||||||
default="all",
|
default="all",
|
||||||
),
|
),
|
||||||
@ -27,8 +27,8 @@ class Migration(migrations.Migration):
|
|||||||
name="policy_engine_mode",
|
name="policy_engine_mode",
|
||||||
field=models.TextField(
|
field=models.TextField(
|
||||||
choices=[
|
choices=[
|
||||||
("all", "ALL, all policies must pass"),
|
("all", "all, all policies must pass"),
|
||||||
("any", "ANY, any policy must pass"),
|
("any", "any, any policy must pass"),
|
||||||
],
|
],
|
||||||
default="any",
|
default="any",
|
||||||
),
|
),
|
||||||
|
@ -19,10 +19,8 @@ from authentik.policies.types import PolicyRequest, PolicyResult
|
|||||||
class PolicyEngineMode(models.TextChoices):
|
class PolicyEngineMode(models.TextChoices):
|
||||||
"""Decide how results of multiple policies should be combined."""
|
"""Decide how results of multiple policies should be combined."""
|
||||||
|
|
||||||
# pyright: reportGeneralTypeIssues=false
|
MODE_ALL = "all", _("all, all policies must pass") # type: "PolicyEngineMode"
|
||||||
MODE_ALL = "all", _("ALL, all policies must pass") # type: "PolicyEngineMode"
|
MODE_ANY = "any", _("any, any policy must pass") # type: "PolicyEngineMode"
|
||||||
# pyright: reportGeneralTypeIssues=false
|
|
||||||
MODE_ANY = "any", _("ANY, any policy must pass") # type: "PolicyEngineMode"
|
|
||||||
|
|
||||||
|
|
||||||
class PolicyBindingModel(models.Model):
|
class PolicyBindingModel(models.Model):
|
||||||
|
4
authentik/policies/password/urls.py
Normal file
4
authentik/policies/password/urls.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.password.api import PasswordPolicyViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [("policies/password", PasswordPolicyViewSet)]
|
7
authentik/policies/reputation/urls.py
Normal file
7
authentik/policies/reputation/urls.py
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
"""API URLs"""
|
||||||
|
from authentik.policies.reputation.api import ReputationPolicyViewSet, ReputationViewSet
|
||||||
|
|
||||||
|
api_urlpatterns = [
|
||||||
|
("policies/reputation/scores", ReputationViewSet),
|
||||||
|
("policies/reputation", ReputationPolicyViewSet),
|
||||||
|
]
|
@ -5,7 +5,9 @@ from django.dispatch import receiver
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.core.api.applications import user_app_cache_key
|
from authentik.core.api.applications import user_app_cache_key
|
||||||
|
from authentik.core.models import Group, User
|
||||||
from authentik.policies.apps import GAUGE_POLICIES_CACHED
|
from authentik.policies.apps import GAUGE_POLICIES_CACHED
|
||||||
|
from authentik.policies.models import Policy, PolicyBinding, PolicyBindingModel
|
||||||
from authentik.policies.types import CACHE_PREFIX
|
from authentik.policies.types import CACHE_PREFIX
|
||||||
from authentik.root.monitoring import monitoring_set
|
from authentik.root.monitoring import monitoring_set
|
||||||
|
|
||||||
@ -18,12 +20,14 @@ def monitoring_set_policies(sender, **kwargs):
|
|||||||
GAUGE_POLICIES_CACHED.set(len(cache.keys(f"{CACHE_PREFIX}_*") or []))
|
GAUGE_POLICIES_CACHED.set(len(cache.keys(f"{CACHE_PREFIX}_*") or []))
|
||||||
|
|
||||||
|
|
||||||
@receiver(post_save)
|
@receiver(post_save, sender=Policy)
|
||||||
|
@receiver(post_save, sender=PolicyBinding)
|
||||||
|
@receiver(post_save, sender=PolicyBindingModel)
|
||||||
|
@receiver(post_save, sender=Group)
|
||||||
|
@receiver(post_save, sender=User)
|
||||||
def invalidate_policy_cache(sender, instance, **_):
|
def invalidate_policy_cache(sender, instance, **_):
|
||||||
"""Invalidate Policy cache when policy is updated"""
|
"""Invalidate Policy cache when policy is updated"""
|
||||||
from authentik.policies.models import Policy, PolicyBinding
|
if sender == Policy:
|
||||||
|
|
||||||
if isinstance(instance, Policy):
|
|
||||||
total = 0
|
total = 0
|
||||||
for binding in PolicyBinding.objects.filter(policy=instance):
|
for binding in PolicyBinding.objects.filter(policy=instance):
|
||||||
prefix = f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_{binding.policy.pk.hex}*"
|
prefix = f"{CACHE_PREFIX}{binding.policy_binding_uuid.hex}_{binding.policy.pk.hex}*"
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user