Compare commits
	
		
			356 Commits
		
	
	
		
			website/in
			...
			celery-2-d
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 80eb56b016 | |||
| 3a1d0fbd35 | |||
| c85471575a | |||
| 5d00dc7e9e | |||
| 6982e7d1c9 | |||
| c7fe987c5a | |||
| e48739c8a0 | |||
| b2ee585c43 | |||
| 97e8ea8e76 | |||
| 1f1e0c9db1 | |||
| ca47a803fe | |||
| c606eb53b0 | |||
| c2dc38e804 | |||
| 9aad7e29a4 | |||
| 62357133b0 | |||
| 99d2d91257 | |||
| 69d9363fce | |||
| 315f9073cc | |||
| c94fa13826 | |||
| 6b3fbb0abf | |||
| 06191d6cfc | |||
| c608dc5110 | |||
| bb05d6063d | |||
| c5b4a630c9 | |||
| 4a73c65710 | |||
| 51e645c26a | |||
| de3607b9a6 | |||
| fb5804b914 | |||
| 287f41fed8 | |||
| 172b595a9f | |||
| d61995d0e2 | |||
| cfc7f6b993 | |||
| 056460dac0 | |||
| bebbbe9b90 | |||
| 188d3c69c1 | |||
| 877f312145 | |||
| f471a98bc7 | |||
| b30b736a71 | |||
| d3aa43ced0 | |||
| 92c837f7b5 | |||
| 7fcd65e318 | |||
| e874cfc21d | |||
| ec7bdf74aa | |||
| 9c01c7d890 | |||
| bdb0564d4c | |||
| e87bc94b95 | |||
| 09688f7a55 | |||
| 31bb995490 | |||
| 5d813438f0 | |||
| a3865abaa9 | |||
| 7100d3c674 | |||
| d92764789f | |||
| c702fa1f95 | |||
| 786bada7d0 | |||
| c0c2d2ad3c | |||
| dc287989db | |||
| 03204f6943 | |||
| fcd369e466 | |||
| cb79407bc1 | |||
| 04a88daf34 | |||
| c6a49da5c3 | |||
| bfeeecf3fa | |||
| d86b5e7c8a | |||
| 690766d377 | |||
| 4990abdf4a | |||
| 76616cf1c5 | |||
| 48c0b5449e | |||
| 8956606564 | |||
| a95776891e | |||
| 0908d0b559 | |||
| 7e5c90fcdc | |||
| 4e210b8299 | |||
| bf65ca4c70 | |||
| 670a88659e | |||
| 0ebbaeea6f | |||
| 49a9911271 | |||
| f3c0ca1a59 | |||
| 64e7bff16c | |||
| f264989f9e | |||
| 031158fdba | |||
| b2fbb92498 | |||
| 8f4353181e | |||
| b1b6bf1a19 | |||
| 179d9d0721 | |||
| 8e94d58851 | |||
| 026669cfce | |||
| c83cea6963 | |||
| 8e01cc2df8 | |||
| 279cec203d | |||
| 41c5030c1e | |||
| 3206fdb7ef | |||
| d7c0868eef | |||
| 7d96a89697 | |||
| 813b7aa8ba | |||
| 3bb3e0d1ef | |||
| dfb0007777 | |||
| 816d9668eb | |||
| 371d35ec06 | |||
| 664d3593ca | |||
| 7acd27eea8 | |||
| 83550dc50d | |||
| c272dd70fd | |||
| ae1d82dc69 | |||
| dd42eeab62 | |||
| 680db9bae6 | |||
| 31b72751bc | |||
| 101e5adeba | |||
| 8210067479 | |||
| ae228c91e3 | |||
| 411c52491e | |||
| 85869806a2 | |||
| 423911d974 | |||
| d4ca070d76 | |||
| d132db475e | |||
| 13b5aa604b | |||
| 97a5acdff5 | |||
| ea38f2d120 | |||
| db1e8b291f | |||
| 44ff6fce23 | |||
| 085c22a41a | |||
| fb2887fa4b | |||
| ed41eb66de | |||
| ee8122baa7 | |||
| f0d70eef6f | |||
| ff966d763b | |||
| e00b68cafe | |||
| bf4e8dbedc | |||
| d09b7757b6 | |||
| ca2f0439f6 | |||
| 27b7b0b0e7 | |||
| 94867aaebf | |||
| 0e67c1d818 | |||
| 2a460201bb | |||
| f99cb3e9fb | |||
| 88073305eb | |||
| e4bd05f444 | |||
| 80c4eb9bef | |||
| 96b4d5aee4 | |||
| 37657e47a3 | |||
| 0d649a70c9 | |||
| 7ec3055018 | |||
| 50ffce87c4 | |||
| a4393ac9f0 | |||
| e235c854a5 | |||
| 910b69f89d | |||
| f89cc98014 | |||
| 6321537c8d | |||
| 43975ec231 | |||
| 9b13922fc2 | |||
| 031456629b | |||
| 2433ed1c9b | |||
| 9868d54320 | |||
| 747a3ed6e9 | |||
| 527e849ce2 | |||
| cfcd54ca19 | |||
| faed9cd66e | |||
| 897d0dbcbd | |||
| 91a675a5a1 | |||
| 71be3acd1a | |||
| 0b6ab171ce | |||
| 0c73572b0c | |||
| 03d0899a76 | |||
| a12e991798 | |||
| e5b86c3578 | |||
| 91f79c97d8 | |||
| 07ff433134 | |||
| 21b3e0c8cb | |||
| cbdec236dd | |||
| 2509ccde1c | |||
| 19324c61a3 | |||
| d297733614 | |||
| f201f41a1b | |||
| f58f679171 | |||
| 1bea5e38a1 | |||
| 4d1c63e7fa | |||
| e341032bf9 | |||
| e3ff242956 | |||
| c6756bf809 | |||
| cf9b7eaa64 | |||
| 53d8f9bd8c | |||
| f76becfd86 | |||
| 080e2311fe | |||
| 7e7b33dba7 | |||
| 13e1e44626 | |||
| e634f23fc8 | |||
| 8554a8e0c5 | |||
| b80abffafc | |||
| 204f21699e | |||
| 0fd478fa3e | |||
| eacc0eb546 | |||
| 7d7e47e972 | |||
| c77a54dc2a | |||
| 84781df51b | |||
| a640866534 | |||
| e070241407 | |||
| 85985c3673 | |||
| 92a33a408f | |||
| d18a54e9e6 | |||
| e6614a0705 | |||
| 4c491cf221 | |||
| 17434c84cf | |||
| 234fb2a0c6 | |||
| 00612f921d | |||
| 8b67015190 | |||
| 5a5176e21f | |||
| 8980282a02 | |||
| 2ca9edb1bc | |||
| 61d970cda4 | |||
| 16fd9cab67 | |||
| 8c7818a252 | |||
| 374779102a | |||
| 0ac854458a | |||
| 1cfaddf49d | |||
| 5ae69f5987 | |||
| c62e1d5457 | |||
| 5b8681b1af | |||
| e0dcade9ad | |||
| 1a6ab7f24b | |||
| 769844314c | |||
| e211604860 | |||
| 7ed711e8f0 | |||
| 196b276345 | |||
| 3c62c80ff1 | |||
| a031f1107a | |||
| 8f399bba3f | |||
| e354e877ea | |||
| f254b8cf8c | |||
| 814b06322a | |||
| 217063ef7b | |||
| c2f7883a5c | |||
| bd64c34787 | |||
| 7518d4391f | |||
| e67bd79c66 | |||
| 2fc6da53c1 | |||
| 250a98cf98 | |||
| f2926fa1eb | |||
| 5e2af4a740 | |||
| 41f2ca42cc | |||
| 7ef547b357 | |||
| 1a9c529e92 | |||
| 75d19bfe76 | |||
| 7f8f7376e0 | |||
| 7c49de9cba | |||
| 00ac9b6367 | |||
| 0e786f7040 | |||
| 03d363ba84 | |||
| 3f33519ec0 | |||
| cae03beb6d | |||
| e4c1e5aed0 | |||
| 5acdd67cba | |||
| 40dbac7a65 | |||
| 1b4ed02959 | |||
| a95e730cdb | |||
| d8c13159e1 | |||
| 5f951ca3ef | |||
| 338da72622 | |||
| 90debcdd70 | |||
| 3766ca86e8 | |||
| 59c8472628 | |||
| 293616e6b0 | |||
| f7305d58b1 | |||
| ba94f63705 | |||
| 06b2e0d14b | |||
| 80a5f44491 | |||
| aca0bde46d | |||
| e671811ad2 | |||
| 3140325493 | |||
| 6c0b879b30 | |||
| 0e0fb37dd7 | |||
| d2cacdc640 | |||
| e65fabf040 | |||
| 107b96e65c | |||
| 5d7ba51872 | |||
| 3037701a14 | |||
| 66f8377c79 | |||
| 86f81d92aa | |||
| 369437f2a1 | |||
| 4b8b80f1d4 | |||
| f839aef33a | |||
| eb87e30076 | |||
| 4302f91028 | |||
| b0af20b0d5 | |||
| 9b556cf4c4 | |||
| 7118219544 | |||
| 475600ea87 | |||
| 2139e0be05 | |||
| a43a0f77fb | |||
| 8a073e8c60 | |||
| 35640fcdfa | |||
| c62f73400a | |||
| c92cbd7e22 | |||
| c3b0d09e04 | |||
| c5a40fced3 | |||
| 9cc6ebabc1 | |||
| e89659fe71 | |||
| 3c1512028d | |||
| c7f80686de | |||
| 8a8386cfcb | |||
| e60165ee45 | |||
| bc6085adc7 | |||
| d413e2875c | |||
| 144986f48e | |||
| c9f1e34beb | |||
| 39f769b150 | |||
| 78180e376f | |||
| d51150102c | |||
| d5da16ad26 | |||
| 2b12e32fcf | |||
| a9b9661155 | |||
| f5f0cef275 | |||
| b756965511 | |||
| db900c4a42 | |||
| 72cb62085b | |||
| 5a42815850 | |||
| b9083a906a | |||
| 04be734c49 | |||
| 1ed6cf7517 | |||
| d6c4f97158 | |||
| 781704fa38 | |||
| 28f4d7d566 | |||
| 991778b2be | |||
| 9465dafd7d | |||
| 75c13a8801 | |||
| 8ae0f145f5 | |||
| 4d0e0e3afe | |||
| 7aeb874ded | |||
| ffc695f7b8 | |||
| 93cb621af3 | |||
| 3a34680196 | |||
| 2335a3130a | |||
| 0bc4b69f52 | |||
| 43c5c1276d | |||
| a3ebfd9bbd | |||
| af5b894e62 | |||
| c982066235 | |||
| 1f6c1522b6 | |||
| bae83ba78e | |||
| 0d0aeab4ee | |||
| 7fe91339ad | |||
| 44dea1d208 | |||
| 6d3be40022 | |||
| 07773f92a0 | |||
| dbc4a2b730 | |||
| df15a78aac | |||
| 61b517edfa | |||
| 082b342f65 | |||
| 9a536ee4b9 | |||
| 677f04cab2 | |||
| 3ddc35cddc | |||
| ae211226ef | |||
| 6662611347 | |||
| c4b988c632 | |||
| 2b1ee8cd5c | |||
| e8cfc2b91e | |||
| de54404ab7 | |||
| f8c3b64274 | 
@ -1,5 +1,5 @@
 | 
				
			|||||||
[bumpversion]
 | 
					[bumpversion]
 | 
				
			||||||
current_version = 2025.6.2
 | 
					current_version = 2025.6.3
 | 
				
			||||||
tag = True
 | 
					tag = True
 | 
				
			||||||
commit = True
 | 
					commit = True
 | 
				
			||||||
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
 | 
					parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
 | 
				
			||||||
@ -21,6 +21,8 @@ optional_value = final
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
[bumpversion:file:package.json]
 | 
					[bumpversion:file:package.json]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					[bumpversion:file:package-lock.json]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
[bumpversion:file:docker-compose.yml]
 | 
					[bumpversion:file:docker-compose.yml]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
[bumpversion:file:schema.yml]
 | 
					[bumpversion:file:schema.yml]
 | 
				
			||||||
@ -31,6 +33,4 @@ optional_value = final
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
[bumpversion:file:internal/constants/constants.go]
 | 
					[bumpversion:file:internal/constants/constants.go]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
[bumpversion:file:web/src/common/constants.ts]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
[bumpversion:file:lifecycle/aws/template.yaml]
 | 
					[bumpversion:file:lifecycle/aws/template.yaml]
 | 
				
			||||||
 | 
				
			|||||||
@ -38,6 +38,8 @@ jobs:
 | 
				
			|||||||
      # Needed for attestation
 | 
					      # Needed for attestation
 | 
				
			||||||
      id-token: write
 | 
					      id-token: write
 | 
				
			||||||
      attestations: write
 | 
					      attestations: write
 | 
				
			||||||
 | 
					      # Needed for checkout
 | 
				
			||||||
 | 
					      contents: read
 | 
				
			||||||
    steps:
 | 
					    steps:
 | 
				
			||||||
      - uses: actions/checkout@v4
 | 
					      - uses: actions/checkout@v4
 | 
				
			||||||
      - uses: docker/setup-qemu-action@v3.6.0
 | 
					      - uses: docker/setup-qemu-action@v3.6.0
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										3
									
								
								.github/workflows/ci-main-daily.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.github/workflows/ci-main-daily.yml
									
									
									
									
										vendored
									
									
								
							@ -9,14 +9,15 @@ on:
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
jobs:
 | 
					jobs:
 | 
				
			||||||
  test-container:
 | 
					  test-container:
 | 
				
			||||||
 | 
					    if: ${{ github.repository != 'goauthentik/authentik-internal' }}
 | 
				
			||||||
    runs-on: ubuntu-latest
 | 
					    runs-on: ubuntu-latest
 | 
				
			||||||
    strategy:
 | 
					    strategy:
 | 
				
			||||||
      fail-fast: false
 | 
					      fail-fast: false
 | 
				
			||||||
      matrix:
 | 
					      matrix:
 | 
				
			||||||
        version:
 | 
					        version:
 | 
				
			||||||
          - docs
 | 
					          - docs
 | 
				
			||||||
 | 
					          - version-2025-4
 | 
				
			||||||
          - version-2025-2
 | 
					          - version-2025-2
 | 
				
			||||||
          - version-2024-12
 | 
					 | 
				
			||||||
    steps:
 | 
					    steps:
 | 
				
			||||||
      - uses: actions/checkout@v4
 | 
					      - uses: actions/checkout@v4
 | 
				
			||||||
      - run: |
 | 
					      - run: |
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										4
									
								
								.github/workflows/ci-main.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										4
									
								
								.github/workflows/ci-main.yml
									
									
									
									
										vendored
									
									
								
							@ -247,11 +247,13 @@ jobs:
 | 
				
			|||||||
      # Needed for attestation
 | 
					      # Needed for attestation
 | 
				
			||||||
      id-token: write
 | 
					      id-token: write
 | 
				
			||||||
      attestations: write
 | 
					      attestations: write
 | 
				
			||||||
 | 
					      # Needed for checkout
 | 
				
			||||||
 | 
					      contents: read
 | 
				
			||||||
    needs: ci-core-mark
 | 
					    needs: ci-core-mark
 | 
				
			||||||
    uses: ./.github/workflows/_reusable-docker-build.yaml
 | 
					    uses: ./.github/workflows/_reusable-docker-build.yaml
 | 
				
			||||||
    secrets: inherit
 | 
					    secrets: inherit
 | 
				
			||||||
    with:
 | 
					    with:
 | 
				
			||||||
      image_name: ghcr.io/goauthentik/dev-server
 | 
					      image_name: ${{ github.repository == 'goauthentik/authentik-internal' && 'ghcr.io/goauthentik/internal-server' || 'ghcr.io/goauthentik/dev-server' }}
 | 
				
			||||||
      release: false
 | 
					      release: false
 | 
				
			||||||
  pr-comment:
 | 
					  pr-comment:
 | 
				
			||||||
    needs:
 | 
					    needs:
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										1
									
								
								.github/workflows/ci-outpost.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										1
									
								
								.github/workflows/ci-outpost.yml
									
									
									
									
										vendored
									
									
								
							@ -59,6 +59,7 @@ jobs:
 | 
				
			|||||||
        with:
 | 
					        with:
 | 
				
			||||||
          jobs: ${{ toJSON(needs) }}
 | 
					          jobs: ${{ toJSON(needs) }}
 | 
				
			||||||
  build-container:
 | 
					  build-container:
 | 
				
			||||||
 | 
					    if: ${{ github.repository != 'goauthentik/authentik-internal' }}
 | 
				
			||||||
    timeout-minutes: 120
 | 
					    timeout-minutes: 120
 | 
				
			||||||
    needs:
 | 
					    needs:
 | 
				
			||||||
      - ci-outpost-mark
 | 
					      - ci-outpost-mark
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										2
									
								
								.github/workflows/ci-website.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/workflows/ci-website.yml
									
									
									
									
										vendored
									
									
								
							@ -63,6 +63,7 @@ jobs:
 | 
				
			|||||||
        working-directory: website/
 | 
					        working-directory: website/
 | 
				
			||||||
        run: npm run ${{ matrix.job }}
 | 
					        run: npm run ${{ matrix.job }}
 | 
				
			||||||
  build-container:
 | 
					  build-container:
 | 
				
			||||||
 | 
					    if: ${{ github.repository != 'goauthentik/authentik-internal' }}
 | 
				
			||||||
    runs-on: ubuntu-latest
 | 
					    runs-on: ubuntu-latest
 | 
				
			||||||
    permissions:
 | 
					    permissions:
 | 
				
			||||||
      # Needed to upload container images to ghcr.io
 | 
					      # Needed to upload container images to ghcr.io
 | 
				
			||||||
@ -122,3 +123,4 @@ jobs:
 | 
				
			|||||||
      - uses: re-actors/alls-green@release/v1
 | 
					      - uses: re-actors/alls-green@release/v1
 | 
				
			||||||
        with:
 | 
					        with:
 | 
				
			||||||
          jobs: ${{ toJSON(needs) }}
 | 
					          jobs: ${{ toJSON(needs) }}
 | 
				
			||||||
 | 
					          allowed-skips: ${{ github.repository == 'goauthentik/authentik-internal' && 'build-container' || '[]' }}
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										2
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							@ -2,7 +2,7 @@ name: "CodeQL"
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
on:
 | 
					on:
 | 
				
			||||||
  push:
 | 
					  push:
 | 
				
			||||||
    branches: [main, "*", next, version*]
 | 
					    branches: [main, next, version*]
 | 
				
			||||||
  pull_request:
 | 
					  pull_request:
 | 
				
			||||||
    branches: [main]
 | 
					    branches: [main]
 | 
				
			||||||
  schedule:
 | 
					  schedule:
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										21
									
								
								.github/workflows/repo-mirror-cleanup.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								.github/workflows/repo-mirror-cleanup.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					name: "authentik-repo-mirror-cleanup"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					on:
 | 
				
			||||||
 | 
					  workflow_dispatch:
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					jobs:
 | 
				
			||||||
 | 
					  to_internal:
 | 
				
			||||||
 | 
					    if: ${{ github.repository != 'goauthentik/authentik-internal' }}
 | 
				
			||||||
 | 
					    runs-on: ubuntu-latest
 | 
				
			||||||
 | 
					    steps:
 | 
				
			||||||
 | 
					      - uses: actions/checkout@v4
 | 
				
			||||||
 | 
					        with:
 | 
				
			||||||
 | 
					          fetch-depth: 0
 | 
				
			||||||
 | 
					      - if: ${{ env.MIRROR_KEY != '' }}
 | 
				
			||||||
 | 
					        uses: BeryJu/repository-mirroring-action@5cf300935bc2e068f73ea69bcc411a8a997208eb
 | 
				
			||||||
 | 
					        with:
 | 
				
			||||||
 | 
					          target_repo_url: git@github.com:goauthentik/authentik-internal.git
 | 
				
			||||||
 | 
					          ssh_private_key: ${{ secrets.GH_MIRROR_KEY }}
 | 
				
			||||||
 | 
					          args: --tags --force --prune
 | 
				
			||||||
 | 
					        env:
 | 
				
			||||||
 | 
					          MIRROR_KEY: ${{ secrets.GH_MIRROR_KEY }}
 | 
				
			||||||
							
								
								
									
										9
									
								
								.github/workflows/repo-mirror.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										9
									
								
								.github/workflows/repo-mirror.yml
									
									
									
									
										vendored
									
									
								
							@ -11,11 +11,10 @@ jobs:
 | 
				
			|||||||
        with:
 | 
					        with:
 | 
				
			||||||
          fetch-depth: 0
 | 
					          fetch-depth: 0
 | 
				
			||||||
      - if: ${{ env.MIRROR_KEY != '' }}
 | 
					      - if: ${{ env.MIRROR_KEY != '' }}
 | 
				
			||||||
        uses: pixta-dev/repository-mirroring-action@v1
 | 
					        uses: BeryJu/repository-mirroring-action@5cf300935bc2e068f73ea69bcc411a8a997208eb
 | 
				
			||||||
        with:
 | 
					        with:
 | 
				
			||||||
          target_repo_url:
 | 
					          target_repo_url: git@github.com:goauthentik/authentik-internal.git
 | 
				
			||||||
            git@github.com:goauthentik/authentik-internal.git
 | 
					          ssh_private_key: ${{ secrets.GH_MIRROR_KEY }}
 | 
				
			||||||
          ssh_private_key:
 | 
					          args: --tags --force
 | 
				
			||||||
            ${{ secrets.GH_MIRROR_KEY }}
 | 
					 | 
				
			||||||
        env:
 | 
					        env:
 | 
				
			||||||
          MIRROR_KEY: ${{ secrets.GH_MIRROR_KEY }}
 | 
					          MIRROR_KEY: ${{ secrets.GH_MIRROR_KEY }}
 | 
				
			||||||
 | 
				
			|||||||
@ -16,6 +16,7 @@ env:
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
jobs:
 | 
					jobs:
 | 
				
			||||||
  compile:
 | 
					  compile:
 | 
				
			||||||
 | 
					    if: ${{ github.repository != 'goauthentik/authentik-internal' }}
 | 
				
			||||||
    runs-on: ubuntu-latest
 | 
					    runs-on: ubuntu-latest
 | 
				
			||||||
    steps:
 | 
					    steps:
 | 
				
			||||||
      - id: generate_token
 | 
					      - id: generate_token
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										5
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										5
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							@ -100,9 +100,6 @@ ipython_config.py
 | 
				
			|||||||
# pyenv
 | 
					# pyenv
 | 
				
			||||||
.python-version
 | 
					.python-version
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# celery beat schedule file
 | 
					 | 
				
			||||||
celerybeat-schedule
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
# SageMath parsed files
 | 
					# SageMath parsed files
 | 
				
			||||||
*.sage.py
 | 
					*.sage.py
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -166,8 +163,6 @@ dmypy.json
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
# pyenv
 | 
					# pyenv
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# celery beat schedule file
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
# SageMath parsed files
 | 
					# SageMath parsed files
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Environments
 | 
					# Environments
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										4
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										4
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							@ -6,13 +6,15 @@
 | 
				
			|||||||
        "!Context scalar",
 | 
					        "!Context scalar",
 | 
				
			||||||
        "!Enumerate sequence",
 | 
					        "!Enumerate sequence",
 | 
				
			||||||
        "!Env scalar",
 | 
					        "!Env scalar",
 | 
				
			||||||
 | 
					        "!Env sequence",
 | 
				
			||||||
        "!Find sequence",
 | 
					        "!Find sequence",
 | 
				
			||||||
        "!Format sequence",
 | 
					        "!Format sequence",
 | 
				
			||||||
        "!If sequence",
 | 
					        "!If sequence",
 | 
				
			||||||
        "!Index scalar",
 | 
					        "!Index scalar",
 | 
				
			||||||
        "!KeyOf scalar",
 | 
					        "!KeyOf scalar",
 | 
				
			||||||
        "!Value scalar",
 | 
					        "!Value scalar",
 | 
				
			||||||
        "!AtIndex scalar"
 | 
					        "!AtIndex scalar",
 | 
				
			||||||
 | 
					        "!ParseJSON scalar"
 | 
				
			||||||
    ],
 | 
					    ],
 | 
				
			||||||
    "typescript.preferences.importModuleSpecifier": "non-relative",
 | 
					    "typescript.preferences.importModuleSpecifier": "non-relative",
 | 
				
			||||||
    "typescript.preferences.importModuleSpecifierEnding": "index",
 | 
					    "typescript.preferences.importModuleSpecifierEnding": "index",
 | 
				
			||||||
 | 
				
			|||||||
@ -75,7 +75,7 @@ RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
 | 
				
			|||||||
    /bin/sh -c "GEOIPUPDATE_LICENSE_KEY_FILE=/run/secrets/GEOIPUPDATE_LICENSE_KEY /usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
 | 
					    /bin/sh -c "GEOIPUPDATE_LICENSE_KEY_FILE=/run/secrets/GEOIPUPDATE_LICENSE_KEY /usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Stage 4: Download uv
 | 
					# Stage 4: Download uv
 | 
				
			||||||
FROM ghcr.io/astral-sh/uv:0.7.13 AS uv
 | 
					FROM ghcr.io/astral-sh/uv:0.7.17 AS uv
 | 
				
			||||||
# Stage 5: Base python image
 | 
					# Stage 5: Base python image
 | 
				
			||||||
FROM ghcr.io/goauthentik/fips-python:3.13.5-slim-bookworm-fips AS python-base
 | 
					FROM ghcr.io/goauthentik/fips-python:3.13.5-slim-bookworm-fips AS python-base
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -122,6 +122,7 @@ ENV UV_NO_BINARY_PACKAGE="cryptography lxml python-kadmin-rs xmlsec"
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
RUN --mount=type=bind,target=pyproject.toml,src=pyproject.toml \
 | 
					RUN --mount=type=bind,target=pyproject.toml,src=pyproject.toml \
 | 
				
			||||||
    --mount=type=bind,target=uv.lock,src=uv.lock \
 | 
					    --mount=type=bind,target=uv.lock,src=uv.lock \
 | 
				
			||||||
 | 
					    --mount=type=bind,target=packages,src=packages \
 | 
				
			||||||
    --mount=type=cache,target=/root/.cache/uv \
 | 
					    --mount=type=cache,target=/root/.cache/uv \
 | 
				
			||||||
    uv sync --frozen --no-install-project --no-dev
 | 
					    uv sync --frozen --no-install-project --no-dev
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -167,6 +168,7 @@ COPY ./blueprints /blueprints
 | 
				
			|||||||
COPY ./lifecycle/ /lifecycle
 | 
					COPY ./lifecycle/ /lifecycle
 | 
				
			||||||
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
 | 
					COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
 | 
				
			||||||
COPY --from=go-builder /go/authentik /bin/authentik
 | 
					COPY --from=go-builder /go/authentik /bin/authentik
 | 
				
			||||||
 | 
					COPY ./packages/ /ak-root/packages
 | 
				
			||||||
COPY --from=python-deps /ak-root/.venv /ak-root/.venv
 | 
					COPY --from=python-deps /ak-root/.venv /ak-root/.venv
 | 
				
			||||||
COPY --from=node-builder /work/web/dist/ /web/dist/
 | 
					COPY --from=node-builder /work/web/dist/ /web/dist/
 | 
				
			||||||
COPY --from=node-builder /work/web/authentik/ /web/authentik/
 | 
					COPY --from=node-builder /work/web/authentik/ /web/authentik/
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										12
									
								
								Makefile
									
									
									
									
									
								
							
							
						
						
									
										12
									
								
								Makefile
									
									
									
									
									
								
							@ -6,7 +6,7 @@ PWD = $(shell pwd)
 | 
				
			|||||||
UID = $(shell id -u)
 | 
					UID = $(shell id -u)
 | 
				
			||||||
GID = $(shell id -g)
 | 
					GID = $(shell id -g)
 | 
				
			||||||
NPM_VERSION = $(shell python -m scripts.generate_semver)
 | 
					NPM_VERSION = $(shell python -m scripts.generate_semver)
 | 
				
			||||||
PY_SOURCES = authentik tests scripts lifecycle .github
 | 
					PY_SOURCES = authentik packages tests scripts lifecycle .github
 | 
				
			||||||
DOCKER_IMAGE ?= "authentik:test"
 | 
					DOCKER_IMAGE ?= "authentik:test"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
GEN_API_TS = gen-ts-api
 | 
					GEN_API_TS = gen-ts-api
 | 
				
			||||||
@ -86,6 +86,10 @@ dev-create-db:
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
dev-reset: dev-drop-db dev-create-db migrate  ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
 | 
					dev-reset: dev-drop-db dev-create-db migrate  ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					update-test-mmdb:  ## Update test GeoIP and ASN Databases
 | 
				
			||||||
 | 
						curl -L https://raw.githubusercontent.com/maxmind/MaxMind-DB/refs/heads/main/test-data/GeoLite2-ASN-Test.mmdb -o ${PWD}/tests/GeoLite2-ASN-Test.mmdb
 | 
				
			||||||
 | 
						curl -L https://raw.githubusercontent.com/maxmind/MaxMind-DB/refs/heads/main/test-data/GeoLite2-City-Test.mmdb -o ${PWD}/tests/GeoLite2-City-Test.mmdb
 | 
				
			||||||
 | 
					
 | 
				
			||||||
#########################
 | 
					#########################
 | 
				
			||||||
## API Schema
 | 
					## API Schema
 | 
				
			||||||
#########################
 | 
					#########################
 | 
				
			||||||
@ -146,9 +150,9 @@ gen-client-ts: gen-clean-ts  ## Build and install the authentik API for Typescri
 | 
				
			|||||||
		--additional-properties=npmVersion=${NPM_VERSION} \
 | 
							--additional-properties=npmVersion=${NPM_VERSION} \
 | 
				
			||||||
		--git-repo-id authentik \
 | 
							--git-repo-id authentik \
 | 
				
			||||||
		--git-user-id goauthentik
 | 
							--git-user-id goauthentik
 | 
				
			||||||
	mkdir -p web/node_modules/@goauthentik/api
 | 
					
 | 
				
			||||||
	cd ${PWD}/${GEN_API_TS} && npm i
 | 
						cd ${PWD}/${GEN_API_TS} && npm link
 | 
				
			||||||
	\cp -rf ${PWD}/${GEN_API_TS}/* web/node_modules/@goauthentik/api
 | 
						cd ${PWD}/web && npm link @goauthentik/api
 | 
				
			||||||
 | 
					
 | 
				
			||||||
gen-client-py: gen-clean-py ## Build and install the authentik API for Python
 | 
					gen-client-py: gen-clean-py ## Build and install the authentik API for Python
 | 
				
			||||||
	docker run \
 | 
						docker run \
 | 
				
			||||||
 | 
				
			|||||||
@ -2,7 +2,7 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from os import environ
 | 
					from os import environ
 | 
				
			||||||
 | 
					
 | 
				
			||||||
__version__ = "2025.6.2"
 | 
					__version__ = "2025.6.3"
 | 
				
			||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
 | 
					ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -41,7 +41,7 @@ class VersionSerializer(PassiveSerializer):
 | 
				
			|||||||
            return __version__
 | 
					            return __version__
 | 
				
			||||||
        version_in_cache = cache.get(VERSION_CACHE_KEY)
 | 
					        version_in_cache = cache.get(VERSION_CACHE_KEY)
 | 
				
			||||||
        if not version_in_cache:  # pragma: no cover
 | 
					        if not version_in_cache:  # pragma: no cover
 | 
				
			||||||
            update_latest_version.delay()
 | 
					            update_latest_version.send()
 | 
				
			||||||
            return __version__
 | 
					            return __version__
 | 
				
			||||||
        return version_in_cache
 | 
					        return version_in_cache
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -1,57 +0,0 @@
 | 
				
			|||||||
"""authentik administration overview"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from socket import gethostname
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.conf import settings
 | 
					 | 
				
			||||||
from drf_spectacular.utils import extend_schema, inline_serializer
 | 
					 | 
				
			||||||
from packaging.version import parse
 | 
					 | 
				
			||||||
from rest_framework.fields import BooleanField, CharField
 | 
					 | 
				
			||||||
from rest_framework.request import Request
 | 
					 | 
				
			||||||
from rest_framework.response import Response
 | 
					 | 
				
			||||||
from rest_framework.views import APIView
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik import get_full_version
 | 
					 | 
				
			||||||
from authentik.rbac.permissions import HasPermission
 | 
					 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class WorkerView(APIView):
 | 
					 | 
				
			||||||
    """Get currently connected worker count."""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    permission_classes = [HasPermission("authentik_rbac.view_system_info")]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    @extend_schema(
 | 
					 | 
				
			||||||
        responses=inline_serializer(
 | 
					 | 
				
			||||||
            "Worker",
 | 
					 | 
				
			||||||
            fields={
 | 
					 | 
				
			||||||
                "worker_id": CharField(),
 | 
					 | 
				
			||||||
                "version": CharField(),
 | 
					 | 
				
			||||||
                "version_matching": BooleanField(),
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
            many=True,
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
    def get(self, request: Request) -> Response:
 | 
					 | 
				
			||||||
        """Get currently connected worker count."""
 | 
					 | 
				
			||||||
        raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
 | 
					 | 
				
			||||||
        our_version = parse(get_full_version())
 | 
					 | 
				
			||||||
        response = []
 | 
					 | 
				
			||||||
        for worker in raw:
 | 
					 | 
				
			||||||
            key = list(worker.keys())[0]
 | 
					 | 
				
			||||||
            version = worker[key].get("version")
 | 
					 | 
				
			||||||
            version_matching = False
 | 
					 | 
				
			||||||
            if version:
 | 
					 | 
				
			||||||
                version_matching = parse(version) == our_version
 | 
					 | 
				
			||||||
            response.append(
 | 
					 | 
				
			||||||
                {"worker_id": key, "version": version, "version_matching": version_matching}
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        # In debug we run with `task_always_eager`, so tasks are ran on the main process
 | 
					 | 
				
			||||||
        if settings.DEBUG:  # pragma: no cover
 | 
					 | 
				
			||||||
            response.append(
 | 
					 | 
				
			||||||
                {
 | 
					 | 
				
			||||||
                    "worker_id": f"authentik-debug@{gethostname()}",
 | 
					 | 
				
			||||||
                    "version": get_full_version(),
 | 
					 | 
				
			||||||
                    "version_matching": True,
 | 
					 | 
				
			||||||
                }
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        return Response(response)
 | 
					 | 
				
			||||||
@ -3,6 +3,9 @@
 | 
				
			|||||||
from prometheus_client import Info
 | 
					from prometheus_client import Info
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.blueprints.apps import ManagedAppConfig
 | 
					from authentik.blueprints.apps import ManagedAppConfig
 | 
				
			||||||
 | 
					from authentik.lib.config import CONFIG
 | 
				
			||||||
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
PROM_INFO = Info("authentik_version", "Currently running authentik version")
 | 
					PROM_INFO = Info("authentik_version", "Currently running authentik version")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -30,3 +33,15 @@ class AuthentikAdminConfig(ManagedAppConfig):
 | 
				
			|||||||
            notification_version = notification.event.context["new_version"]
 | 
					            notification_version = notification.event.context["new_version"]
 | 
				
			||||||
            if LOCAL_VERSION >= parse(notification_version):
 | 
					            if LOCAL_VERSION >= parse(notification_version):
 | 
				
			||||||
                notification.delete()
 | 
					                notification.delete()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def global_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.admin.tasks import update_latest_version
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=update_latest_version,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('admin_latest_version')} * * * *",
 | 
				
			||||||
 | 
					                paused=CONFIG.get_bool("disable_update_check"),
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -1,15 +0,0 @@
 | 
				
			|||||||
"""authentik admin settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
from django_tenants.utils import get_public_schema_name
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "admin_latest_version": {
 | 
					 | 
				
			||||||
        "task": "authentik.admin.tasks.update_latest_version",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("admin_latest_version"), hour="*"),
 | 
					 | 
				
			||||||
        "tenant_schemas": [get_public_schema_name()],
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -1,35 +0,0 @@
 | 
				
			|||||||
"""admin signals"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.dispatch import receiver
 | 
					 | 
				
			||||||
from packaging.version import parse
 | 
					 | 
				
			||||||
from prometheus_client import Gauge
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik import get_full_version
 | 
					 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
from authentik.root.monitoring import monitoring_set
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
GAUGE_WORKERS = Gauge(
 | 
					 | 
				
			||||||
    "authentik_admin_workers",
 | 
					 | 
				
			||||||
    "Currently connected workers, their versions and if they are the same version as authentik",
 | 
					 | 
				
			||||||
    ["version", "version_matched"],
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
_version = parse(get_full_version())
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@receiver(monitoring_set)
 | 
					 | 
				
			||||||
def monitoring_set_workers(sender, **kwargs):
 | 
					 | 
				
			||||||
    """Set worker gauge"""
 | 
					 | 
				
			||||||
    raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
 | 
					 | 
				
			||||||
    worker_version_count = {}
 | 
					 | 
				
			||||||
    for worker in raw:
 | 
					 | 
				
			||||||
        key = list(worker.keys())[0]
 | 
					 | 
				
			||||||
        version = worker[key].get("version")
 | 
					 | 
				
			||||||
        version_matching = False
 | 
					 | 
				
			||||||
        if version:
 | 
					 | 
				
			||||||
            version_matching = parse(version) == _version
 | 
					 | 
				
			||||||
        worker_version_count.setdefault(version, {"count": 0, "matching": version_matching})
 | 
					 | 
				
			||||||
        worker_version_count[version]["count"] += 1
 | 
					 | 
				
			||||||
    for version, stats in worker_version_count.items():
 | 
					 | 
				
			||||||
        GAUGE_WORKERS.labels(version, stats["matching"]).set(stats["count"])
 | 
					 | 
				
			||||||
@ -2,6 +2,8 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from django.core.cache import cache
 | 
					from django.core.cache import cache
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq import actor
 | 
				
			||||||
from packaging.version import parse
 | 
					from packaging.version import parse
 | 
				
			||||||
from requests import RequestException
 | 
					from requests import RequestException
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
@ -9,10 +11,9 @@ from structlog.stdlib import get_logger
 | 
				
			|||||||
from authentik import __version__, get_build_hash
 | 
					from authentik import __version__, get_build_hash
 | 
				
			||||||
from authentik.admin.apps import PROM_INFO
 | 
					from authentik.admin.apps import PROM_INFO
 | 
				
			||||||
from authentik.events.models import Event, EventAction
 | 
					from authentik.events.models import Event, EventAction
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
 | 
					 | 
				
			||||||
from authentik.lib.config import CONFIG
 | 
					from authentik.lib.config import CONFIG
 | 
				
			||||||
from authentik.lib.utils.http import get_http_session
 | 
					from authentik.lib.utils.http import get_http_session
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
VERSION_NULL = "0.0.0"
 | 
					VERSION_NULL = "0.0.0"
 | 
				
			||||||
@ -32,13 +33,12 @@ def _set_prom_info():
 | 
				
			|||||||
    )
 | 
					    )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Update latest version info."))
 | 
				
			||||||
@prefill_task
 | 
					def update_latest_version():
 | 
				
			||||||
def update_latest_version(self: SystemTask):
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    """Update latest version info"""
 | 
					 | 
				
			||||||
    if CONFIG.get_bool("disable_update_check"):
 | 
					    if CONFIG.get_bool("disable_update_check"):
 | 
				
			||||||
        cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
 | 
					        cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
 | 
				
			||||||
        self.set_status(TaskStatus.WARNING, "Version check disabled.")
 | 
					        self.info("Version check disabled.")
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
        response = get_http_session().get(
 | 
					        response = get_http_session().get(
 | 
				
			||||||
@ -48,7 +48,7 @@ def update_latest_version(self: SystemTask):
 | 
				
			|||||||
        data = response.json()
 | 
					        data = response.json()
 | 
				
			||||||
        upstream_version = data.get("stable", {}).get("version")
 | 
					        upstream_version = data.get("stable", {}).get("version")
 | 
				
			||||||
        cache.set(VERSION_CACHE_KEY, upstream_version, VERSION_CACHE_TIMEOUT)
 | 
					        cache.set(VERSION_CACHE_KEY, upstream_version, VERSION_CACHE_TIMEOUT)
 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL, "Successfully updated latest Version")
 | 
					        self.info("Successfully updated latest Version")
 | 
				
			||||||
        _set_prom_info()
 | 
					        _set_prom_info()
 | 
				
			||||||
        # Check if upstream version is newer than what we're running,
 | 
					        # Check if upstream version is newer than what we're running,
 | 
				
			||||||
        # and if no event exists yet, create one.
 | 
					        # and if no event exists yet, create one.
 | 
				
			||||||
@ -71,7 +71,7 @@ def update_latest_version(self: SystemTask):
 | 
				
			|||||||
            ).save()
 | 
					            ).save()
 | 
				
			||||||
    except (RequestException, IndexError) as exc:
 | 
					    except (RequestException, IndexError) as exc:
 | 
				
			||||||
        cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
 | 
					        cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
 | 
				
			||||||
        self.set_error(exc)
 | 
					        raise exc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
_set_prom_info()
 | 
					_set_prom_info()
 | 
				
			||||||
 | 
				
			|||||||
@ -29,13 +29,6 @@ class TestAdminAPI(TestCase):
 | 
				
			|||||||
        body = loads(response.content)
 | 
					        body = loads(response.content)
 | 
				
			||||||
        self.assertEqual(body["version_current"], __version__)
 | 
					        self.assertEqual(body["version_current"], __version__)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def test_workers(self):
 | 
					 | 
				
			||||||
        """Test Workers API"""
 | 
					 | 
				
			||||||
        response = self.client.get(reverse("authentik_api:admin_workers"))
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 200)
 | 
					 | 
				
			||||||
        body = loads(response.content)
 | 
					 | 
				
			||||||
        self.assertEqual(len(body), 0)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_apps(self):
 | 
					    def test_apps(self):
 | 
				
			||||||
        """Test apps API"""
 | 
					        """Test apps API"""
 | 
				
			||||||
        response = self.client.get(reverse("authentik_api:apps-list"))
 | 
					        response = self.client.get(reverse("authentik_api:apps-list"))
 | 
				
			||||||
 | 
				
			|||||||
@ -30,7 +30,7 @@ class TestAdminTasks(TestCase):
 | 
				
			|||||||
        """Test Update checker with valid response"""
 | 
					        """Test Update checker with valid response"""
 | 
				
			||||||
        with Mocker() as mocker, CONFIG.patch("disable_update_check", False):
 | 
					        with Mocker() as mocker, CONFIG.patch("disable_update_check", False):
 | 
				
			||||||
            mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
 | 
					            mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
 | 
				
			||||||
            update_latest_version.delay().get()
 | 
					            update_latest_version.send()
 | 
				
			||||||
            self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
 | 
					            self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
 | 
				
			||||||
            self.assertTrue(
 | 
					            self.assertTrue(
 | 
				
			||||||
                Event.objects.filter(
 | 
					                Event.objects.filter(
 | 
				
			||||||
@ -40,7 +40,7 @@ class TestAdminTasks(TestCase):
 | 
				
			|||||||
                ).exists()
 | 
					                ).exists()
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
            # test that a consecutive check doesn't create a duplicate event
 | 
					            # test that a consecutive check doesn't create a duplicate event
 | 
				
			||||||
            update_latest_version.delay().get()
 | 
					            update_latest_version.send()
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
                len(
 | 
					                len(
 | 
				
			||||||
                    Event.objects.filter(
 | 
					                    Event.objects.filter(
 | 
				
			||||||
@ -56,7 +56,7 @@ class TestAdminTasks(TestCase):
 | 
				
			|||||||
        """Test Update checker with invalid response"""
 | 
					        """Test Update checker with invalid response"""
 | 
				
			||||||
        with Mocker() as mocker:
 | 
					        with Mocker() as mocker:
 | 
				
			||||||
            mocker.get("https://version.goauthentik.io/version.json", status_code=400)
 | 
					            mocker.get("https://version.goauthentik.io/version.json", status_code=400)
 | 
				
			||||||
            update_latest_version.delay().get()
 | 
					            update_latest_version.send()
 | 
				
			||||||
            self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
 | 
					            self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
 | 
				
			||||||
            self.assertFalse(
 | 
					            self.assertFalse(
 | 
				
			||||||
                Event.objects.filter(
 | 
					                Event.objects.filter(
 | 
				
			||||||
@ -67,14 +67,15 @@ class TestAdminTasks(TestCase):
 | 
				
			|||||||
    def test_version_disabled(self):
 | 
					    def test_version_disabled(self):
 | 
				
			||||||
        """Test Update checker while its disabled"""
 | 
					        """Test Update checker while its disabled"""
 | 
				
			||||||
        with CONFIG.patch("disable_update_check", True):
 | 
					        with CONFIG.patch("disable_update_check", True):
 | 
				
			||||||
            update_latest_version.delay().get()
 | 
					            update_latest_version.send()
 | 
				
			||||||
            self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
 | 
					            self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def test_clear_update_notifications(self):
 | 
					    def test_clear_update_notifications(self):
 | 
				
			||||||
        """Test clear of previous notification"""
 | 
					        """Test clear of previous notification"""
 | 
				
			||||||
        admin_config = apps.get_app_config("authentik_admin")
 | 
					        admin_config = apps.get_app_config("authentik_admin")
 | 
				
			||||||
        Event.objects.create(
 | 
					        Event.objects.create(
 | 
				
			||||||
            action=EventAction.UPDATE_AVAILABLE, context={"new_version": "99999999.9999999.9999999"}
 | 
					            action=EventAction.UPDATE_AVAILABLE,
 | 
				
			||||||
 | 
					            context={"new_version": "99999999.9999999.9999999"},
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        Event.objects.create(action=EventAction.UPDATE_AVAILABLE, context={"new_version": "1.1.1"})
 | 
					        Event.objects.create(action=EventAction.UPDATE_AVAILABLE, context={"new_version": "1.1.1"})
 | 
				
			||||||
        Event.objects.create(action=EventAction.UPDATE_AVAILABLE, context={})
 | 
					        Event.objects.create(action=EventAction.UPDATE_AVAILABLE, context={})
 | 
				
			||||||
 | 
				
			|||||||
@ -6,13 +6,11 @@ from authentik.admin.api.meta import AppsViewSet, ModelViewSet
 | 
				
			|||||||
from authentik.admin.api.system import SystemView
 | 
					from authentik.admin.api.system import SystemView
 | 
				
			||||||
from authentik.admin.api.version import VersionView
 | 
					from authentik.admin.api.version import VersionView
 | 
				
			||||||
from authentik.admin.api.version_history import VersionHistoryViewSet
 | 
					from authentik.admin.api.version_history import VersionHistoryViewSet
 | 
				
			||||||
from authentik.admin.api.workers import WorkerView
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
api_urlpatterns = [
 | 
					api_urlpatterns = [
 | 
				
			||||||
    ("admin/apps", AppsViewSet, "apps"),
 | 
					    ("admin/apps", AppsViewSet, "apps"),
 | 
				
			||||||
    ("admin/models", ModelViewSet, "models"),
 | 
					    ("admin/models", ModelViewSet, "models"),
 | 
				
			||||||
    path("admin/version/", VersionView.as_view(), name="admin_version"),
 | 
					    path("admin/version/", VersionView.as_view(), name="admin_version"),
 | 
				
			||||||
    ("admin/version/history", VersionHistoryViewSet, "version_history"),
 | 
					    ("admin/version/history", VersionHistoryViewSet, "version_history"),
 | 
				
			||||||
    path("admin/workers/", WorkerView.as_view(), name="admin_workers"),
 | 
					 | 
				
			||||||
    path("admin/system/", SystemView.as_view(), name="admin_system"),
 | 
					    path("admin/system/", SystemView.as_view(), name="admin_system"),
 | 
				
			||||||
]
 | 
					]
 | 
				
			||||||
 | 
				
			|||||||
@ -39,7 +39,7 @@ class BlueprintInstanceSerializer(ModelSerializer):
 | 
				
			|||||||
        """Ensure the path (if set) specified is retrievable"""
 | 
					        """Ensure the path (if set) specified is retrievable"""
 | 
				
			||||||
        if path == "" or path.startswith(OCI_PREFIX):
 | 
					        if path == "" or path.startswith(OCI_PREFIX):
 | 
				
			||||||
            return path
 | 
					            return path
 | 
				
			||||||
        files: list[dict] = blueprints_find_dict.delay().get()
 | 
					        files: list[dict] = blueprints_find_dict.send().get_result(block=True)
 | 
				
			||||||
        if path not in [file["path"] for file in files]:
 | 
					        if path not in [file["path"] for file in files]:
 | 
				
			||||||
            raise ValidationError(_("Blueprint file does not exist"))
 | 
					            raise ValidationError(_("Blueprint file does not exist"))
 | 
				
			||||||
        return path
 | 
					        return path
 | 
				
			||||||
@ -115,7 +115,7 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
 | 
				
			|||||||
    @action(detail=False, pagination_class=None, filter_backends=[])
 | 
					    @action(detail=False, pagination_class=None, filter_backends=[])
 | 
				
			||||||
    def available(self, request: Request) -> Response:
 | 
					    def available(self, request: Request) -> Response:
 | 
				
			||||||
        """Get blueprints"""
 | 
					        """Get blueprints"""
 | 
				
			||||||
        files: list[dict] = blueprints_find_dict.delay().get()
 | 
					        files: list[dict] = blueprints_find_dict.send().get_result(block=True)
 | 
				
			||||||
        return Response(files)
 | 
					        return Response(files)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @permission_required("authentik_blueprints.view_blueprintinstance")
 | 
					    @permission_required("authentik_blueprints.view_blueprintinstance")
 | 
				
			||||||
@ -129,5 +129,5 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
 | 
				
			|||||||
    def apply(self, request: Request, *args, **kwargs) -> Response:
 | 
					    def apply(self, request: Request, *args, **kwargs) -> Response:
 | 
				
			||||||
        """Apply a blueprint"""
 | 
					        """Apply a blueprint"""
 | 
				
			||||||
        blueprint = self.get_object()
 | 
					        blueprint = self.get_object()
 | 
				
			||||||
        apply_blueprint.delay(str(blueprint.pk)).get()
 | 
					        apply_blueprint.send_with_options(args=(blueprint.pk,), rel_obj=blueprint)
 | 
				
			||||||
        return self.retrieve(request, *args, **kwargs)
 | 
					        return self.retrieve(request, *args, **kwargs)
 | 
				
			||||||
 | 
				
			|||||||
@ -6,9 +6,12 @@ from inspect import ismethod
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from django.apps import AppConfig
 | 
					from django.apps import AppConfig
 | 
				
			||||||
from django.db import DatabaseError, InternalError, ProgrammingError
 | 
					from django.db import DatabaseError, InternalError, ProgrammingError
 | 
				
			||||||
 | 
					from dramatiq.broker import get_broker
 | 
				
			||||||
from structlog.stdlib import BoundLogger, get_logger
 | 
					from structlog.stdlib import BoundLogger, get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
from authentik.root.signals import startup
 | 
					from authentik.root.signals import startup
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class ManagedAppConfig(AppConfig):
 | 
					class ManagedAppConfig(AppConfig):
 | 
				
			||||||
@ -34,7 +37,7 @@ class ManagedAppConfig(AppConfig):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    def import_related(self):
 | 
					    def import_related(self):
 | 
				
			||||||
        """Automatically import related modules which rely on just being imported
 | 
					        """Automatically import related modules which rely on just being imported
 | 
				
			||||||
        to register themselves (mainly django signals and celery tasks)"""
 | 
					        to register themselves (mainly django signals and tasks)"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        def import_relative(rel_module: str):
 | 
					        def import_relative(rel_module: str):
 | 
				
			||||||
            try:
 | 
					            try:
 | 
				
			||||||
@ -80,6 +83,16 @@ class ManagedAppConfig(AppConfig):
 | 
				
			|||||||
        func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_GLOBAL_CATEGORY
 | 
					        func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_GLOBAL_CATEGORY
 | 
				
			||||||
        return func
 | 
					        return func
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        """Get a list of schedule specs that must exist in each tenant"""
 | 
				
			||||||
 | 
					        return []
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def global_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        """Get a list of schedule specs that must exist in the default tenant"""
 | 
				
			||||||
 | 
					        return []
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def _reconcile_tenant(self) -> None:
 | 
					    def _reconcile_tenant(self) -> None:
 | 
				
			||||||
        """reconcile ourselves for tenanted methods"""
 | 
					        """reconcile ourselves for tenanted methods"""
 | 
				
			||||||
        from authentik.tenants.models import Tenant
 | 
					        from authentik.tenants.models import Tenant
 | 
				
			||||||
@ -100,8 +113,12 @@ class ManagedAppConfig(AppConfig):
 | 
				
			|||||||
        """
 | 
					        """
 | 
				
			||||||
        from django_tenants.utils import get_public_schema_name, schema_context
 | 
					        from django_tenants.utils import get_public_schema_name, schema_context
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        with schema_context(get_public_schema_name()):
 | 
					        try:
 | 
				
			||||||
            self._reconcile(self.RECONCILE_GLOBAL_CATEGORY)
 | 
					            with schema_context(get_public_schema_name()):
 | 
				
			||||||
 | 
					                self._reconcile(self.RECONCILE_GLOBAL_CATEGORY)
 | 
				
			||||||
 | 
					        except (DatabaseError, ProgrammingError, InternalError) as exc:
 | 
				
			||||||
 | 
					            self.logger.debug("Failed to access database to run reconcile", exc=exc)
 | 
				
			||||||
 | 
					            return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class AuthentikBlueprintsConfig(ManagedAppConfig):
 | 
					class AuthentikBlueprintsConfig(ManagedAppConfig):
 | 
				
			||||||
@ -112,19 +129,29 @@ class AuthentikBlueprintsConfig(ManagedAppConfig):
 | 
				
			|||||||
    verbose_name = "authentik Blueprints"
 | 
					    verbose_name = "authentik Blueprints"
 | 
				
			||||||
    default = True
 | 
					    default = True
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @ManagedAppConfig.reconcile_global
 | 
					 | 
				
			||||||
    def load_blueprints_v1_tasks(self):
 | 
					 | 
				
			||||||
        """Load v1 tasks"""
 | 
					 | 
				
			||||||
        self.import_module("authentik.blueprints.v1.tasks")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    @ManagedAppConfig.reconcile_tenant
 | 
					 | 
				
			||||||
    def blueprints_discovery(self):
 | 
					 | 
				
			||||||
        """Run blueprint discovery"""
 | 
					 | 
				
			||||||
        from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        blueprints_discovery.delay()
 | 
					 | 
				
			||||||
        clear_failed_blueprints.delay()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def import_models(self):
 | 
					    def import_models(self):
 | 
				
			||||||
        super().import_models()
 | 
					        super().import_models()
 | 
				
			||||||
        self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
 | 
					        self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @ManagedAppConfig.reconcile_global
 | 
				
			||||||
 | 
					    def tasks_middlewares(self):
 | 
				
			||||||
 | 
					        from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        get_broker().add_middleware(BlueprintWatcherMiddleware())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=blueprints_discovery,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('blueprints_v1_discover')} * * * *",
 | 
				
			||||||
 | 
					                send_on_startup=True,
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=clear_failed_blueprints,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('blueprints_v1_cleanup')} * * * *",
 | 
				
			||||||
 | 
					                send_on_startup=True,
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -3,6 +3,7 @@
 | 
				
			|||||||
from pathlib import Path
 | 
					from pathlib import Path
 | 
				
			||||||
from uuid import uuid4
 | 
					from uuid import uuid4
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.contrib.contenttypes.fields import GenericRelation
 | 
				
			||||||
from django.contrib.postgres.fields import ArrayField
 | 
					from django.contrib.postgres.fields import ArrayField
 | 
				
			||||||
from django.db import models
 | 
					from django.db import models
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
@ -71,6 +72,13 @@ class BlueprintInstance(SerializerModel, ManagedModel, CreatedUpdatedModel):
 | 
				
			|||||||
    enabled = models.BooleanField(default=True)
 | 
					    enabled = models.BooleanField(default=True)
 | 
				
			||||||
    managed_models = ArrayField(models.TextField(), default=list)
 | 
					    managed_models = ArrayField(models.TextField(), default=list)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    # Manual link to tasks instead of using TasksModel because of loop imports
 | 
				
			||||||
 | 
					    tasks = GenericRelation(
 | 
				
			||||||
 | 
					        "authentik_tasks.Task",
 | 
				
			||||||
 | 
					        content_type_field="rel_obj_content_type",
 | 
				
			||||||
 | 
					        object_id_field="rel_obj_id",
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    class Meta:
 | 
					    class Meta:
 | 
				
			||||||
        verbose_name = _("Blueprint Instance")
 | 
					        verbose_name = _("Blueprint Instance")
 | 
				
			||||||
        verbose_name_plural = _("Blueprint Instances")
 | 
					        verbose_name_plural = _("Blueprint Instances")
 | 
				
			||||||
 | 
				
			|||||||
@ -1,18 +0,0 @@
 | 
				
			|||||||
"""blueprint Settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "blueprints_v1_discover": {
 | 
					 | 
				
			||||||
        "task": "authentik.blueprints.v1.tasks.blueprints_discovery",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("blueprints_v1_discover"), hour="*"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
    "blueprints_v1_cleanup": {
 | 
					 | 
				
			||||||
        "task": "authentik.blueprints.v1.tasks.clear_failed_blueprints",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("blueprints_v1_cleanup"), hour="*"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
							
								
								
									
										2
									
								
								authentik/blueprints/tasks.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								authentik/blueprints/tasks.py
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,2 @@
 | 
				
			|||||||
 | 
					# Import all v1 tasks for auto task discovery
 | 
				
			||||||
 | 
					from authentik.blueprints.v1.tasks import *  # noqa: F403
 | 
				
			||||||
@ -37,6 +37,7 @@ entries:
 | 
				
			|||||||
    - attrs:
 | 
					    - attrs:
 | 
				
			||||||
          attributes:
 | 
					          attributes:
 | 
				
			||||||
              env_null: !Env [bar-baz, null]
 | 
					              env_null: !Env [bar-baz, null]
 | 
				
			||||||
 | 
					              json_parse: !ParseJSON '{"foo": "bar"}'
 | 
				
			||||||
              policy_pk1:
 | 
					              policy_pk1:
 | 
				
			||||||
                  !Format [
 | 
					                  !Format [
 | 
				
			||||||
                      "%s-%s",
 | 
					                      "%s-%s",
 | 
				
			||||||
 | 
				
			|||||||
@ -35,6 +35,6 @@ def blueprint_tester(file_name: Path) -> Callable:
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
for blueprint_file in Path("blueprints/").glob("**/*.yaml"):
 | 
					for blueprint_file in Path("blueprints/").glob("**/*.yaml"):
 | 
				
			||||||
    if "local" in str(blueprint_file):
 | 
					    if "local" in str(blueprint_file) or "testing" in str(blueprint_file):
 | 
				
			||||||
        continue
 | 
					        continue
 | 
				
			||||||
    setattr(TestPackaged, f"test_blueprint_{blueprint_file}", blueprint_tester(blueprint_file))
 | 
					    setattr(TestPackaged, f"test_blueprint_{blueprint_file}", blueprint_tester(blueprint_file))
 | 
				
			||||||
 | 
				
			|||||||
@ -5,7 +5,6 @@ from collections.abc import Callable
 | 
				
			|||||||
from django.apps import apps
 | 
					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.lib.models import SerializerModel
 | 
					from authentik.lib.models import SerializerModel
 | 
				
			||||||
from authentik.providers.oauth2.models import RefreshToken
 | 
					from authentik.providers.oauth2.models import RefreshToken
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -22,10 +21,13 @@ def serializer_tester_factory(test_model: type[SerializerModel]) -> Callable:
 | 
				
			|||||||
            return
 | 
					            return
 | 
				
			||||||
        model_class = test_model()
 | 
					        model_class = test_model()
 | 
				
			||||||
        self.assertTrue(isinstance(model_class, SerializerModel))
 | 
					        self.assertTrue(isinstance(model_class, SerializerModel))
 | 
				
			||||||
 | 
					        # Models that have subclasses don't have to have a serializer
 | 
				
			||||||
 | 
					        if len(test_model.__subclasses__()) > 0:
 | 
				
			||||||
 | 
					            return
 | 
				
			||||||
        self.assertIsNotNone(model_class.serializer)
 | 
					        self.assertIsNotNone(model_class.serializer)
 | 
				
			||||||
        if model_class.serializer.Meta().model == RefreshToken:
 | 
					        if model_class.serializer.Meta().model == RefreshToken:
 | 
				
			||||||
            return
 | 
					            return
 | 
				
			||||||
        self.assertEqual(model_class.serializer.Meta().model, test_model)
 | 
					        self.assertTrue(issubclass(test_model, model_class.serializer.Meta().model))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    return tester
 | 
					    return tester
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -34,6 +36,6 @@ for app in apps.get_app_configs():
 | 
				
			|||||||
    if not app.label.startswith("authentik"):
 | 
					    if not app.label.startswith("authentik"):
 | 
				
			||||||
        continue
 | 
					        continue
 | 
				
			||||||
    for model in app.get_models():
 | 
					    for model in app.get_models():
 | 
				
			||||||
        if not is_model_allowed(model):
 | 
					        if not issubclass(model, SerializerModel):
 | 
				
			||||||
            continue
 | 
					            continue
 | 
				
			||||||
        setattr(TestModels, f"test_{app.label}_{model.__name__}", serializer_tester_factory(model))
 | 
					        setattr(TestModels, f"test_{app.label}_{model.__name__}", serializer_tester_factory(model))
 | 
				
			||||||
 | 
				
			|||||||
@ -215,6 +215,7 @@ class TestBlueprintsV1(TransactionTestCase):
 | 
				
			|||||||
                    },
 | 
					                    },
 | 
				
			||||||
                    "nested_context": "context-nested-value",
 | 
					                    "nested_context": "context-nested-value",
 | 
				
			||||||
                    "env_null": None,
 | 
					                    "env_null": None,
 | 
				
			||||||
 | 
					                    "json_parse": {"foo": "bar"},
 | 
				
			||||||
                    "at_index_sequence": "foo",
 | 
					                    "at_index_sequence": "foo",
 | 
				
			||||||
                    "at_index_sequence_default": "non existent",
 | 
					                    "at_index_sequence_default": "non existent",
 | 
				
			||||||
                    "at_index_mapping": 2,
 | 
					                    "at_index_mapping": 2,
 | 
				
			||||||
 | 
				
			|||||||
@ -54,7 +54,7 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
 | 
				
			|||||||
            file.seek(0)
 | 
					            file.seek(0)
 | 
				
			||||||
            file_hash = sha512(file.read().encode()).hexdigest()
 | 
					            file_hash = sha512(file.read().encode()).hexdigest()
 | 
				
			||||||
            file.flush()
 | 
					            file.flush()
 | 
				
			||||||
            blueprints_discovery()
 | 
					            blueprints_discovery.send()
 | 
				
			||||||
            instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
 | 
					            instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
 | 
				
			||||||
            self.assertEqual(instance.last_applied_hash, file_hash)
 | 
					            self.assertEqual(instance.last_applied_hash, file_hash)
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
@ -82,7 +82,7 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
 | 
				
			|||||||
                )
 | 
					                )
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
            file.flush()
 | 
					            file.flush()
 | 
				
			||||||
            blueprints_discovery()
 | 
					            blueprints_discovery.send()
 | 
				
			||||||
            blueprint = BlueprintInstance.objects.filter(name="foo").first()
 | 
					            blueprint = BlueprintInstance.objects.filter(name="foo").first()
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
                blueprint.last_applied_hash,
 | 
					                blueprint.last_applied_hash,
 | 
				
			||||||
@ -107,7 +107,7 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
 | 
				
			|||||||
                )
 | 
					                )
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
            file.flush()
 | 
					            file.flush()
 | 
				
			||||||
            blueprints_discovery()
 | 
					            blueprints_discovery.send()
 | 
				
			||||||
            blueprint.refresh_from_db()
 | 
					            blueprint.refresh_from_db()
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
                blueprint.last_applied_hash,
 | 
					                blueprint.last_applied_hash,
 | 
				
			||||||
 | 
				
			|||||||
@ -6,6 +6,7 @@ from copy import copy
 | 
				
			|||||||
from dataclasses import asdict, dataclass, field, is_dataclass
 | 
					from dataclasses import asdict, dataclass, field, is_dataclass
 | 
				
			||||||
from enum import Enum
 | 
					from enum import Enum
 | 
				
			||||||
from functools import reduce
 | 
					from functools import reduce
 | 
				
			||||||
 | 
					from json import JSONDecodeError, loads
 | 
				
			||||||
from operator import ixor
 | 
					from operator import ixor
 | 
				
			||||||
from os import getenv
 | 
					from os import getenv
 | 
				
			||||||
from typing import Any, Literal, Union
 | 
					from typing import Any, Literal, Union
 | 
				
			||||||
@ -291,6 +292,22 @@ class Context(YAMLTag):
 | 
				
			|||||||
        return value
 | 
					        return value
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class ParseJSON(YAMLTag):
 | 
				
			||||||
 | 
					    """Parse JSON from context/env/etc value"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    raw: str
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def __init__(self, loader: "BlueprintLoader", node: ScalarNode) -> None:
 | 
				
			||||||
 | 
					        super().__init__()
 | 
				
			||||||
 | 
					        self.raw = node.value
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
 | 
				
			||||||
 | 
					        try:
 | 
				
			||||||
 | 
					            return loads(self.raw)
 | 
				
			||||||
 | 
					        except JSONDecodeError as exc:
 | 
				
			||||||
 | 
					            raise EntryInvalidError.from_entry(exc, entry) from exc
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class Format(YAMLTag):
 | 
					class Format(YAMLTag):
 | 
				
			||||||
    """Format a string"""
 | 
					    """Format a string"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -666,6 +683,7 @@ class BlueprintLoader(SafeLoader):
 | 
				
			|||||||
        self.add_constructor("!Value", Value)
 | 
					        self.add_constructor("!Value", Value)
 | 
				
			||||||
        self.add_constructor("!Index", Index)
 | 
					        self.add_constructor("!Index", Index)
 | 
				
			||||||
        self.add_constructor("!AtIndex", AtIndex)
 | 
					        self.add_constructor("!AtIndex", AtIndex)
 | 
				
			||||||
 | 
					        self.add_constructor("!ParseJSON", ParseJSON)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class EntryInvalidError(SentryIgnoredException):
 | 
					class EntryInvalidError(SentryIgnoredException):
 | 
				
			||||||
 | 
				
			|||||||
@ -57,7 +57,6 @@ from authentik.enterprise.stages.authenticator_endpoint_gdtc.models import (
 | 
				
			|||||||
    EndpointDeviceConnection,
 | 
					    EndpointDeviceConnection,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.events.logs import LogEvent, capture_logs
 | 
					from authentik.events.logs import LogEvent, capture_logs
 | 
				
			||||||
from authentik.events.models import SystemTask
 | 
					 | 
				
			||||||
from authentik.events.utils import cleanse_dict
 | 
					from authentik.events.utils import cleanse_dict
 | 
				
			||||||
from authentik.flows.models import FlowToken, Stage
 | 
					from authentik.flows.models import FlowToken, Stage
 | 
				
			||||||
from authentik.lib.models import SerializerModel
 | 
					from authentik.lib.models import SerializerModel
 | 
				
			||||||
@ -77,6 +76,7 @@ from authentik.providers.scim.models import SCIMProviderGroup, SCIMProviderUser
 | 
				
			|||||||
from authentik.rbac.models import Role
 | 
					from authentik.rbac.models import Role
 | 
				
			||||||
from authentik.sources.scim.models import SCIMSourceGroup, SCIMSourceUser
 | 
					from authentik.sources.scim.models import SCIMSourceGroup, SCIMSourceUser
 | 
				
			||||||
from authentik.stages.authenticator_webauthn.models import WebAuthnDeviceType
 | 
					from authentik.stages.authenticator_webauthn.models import WebAuthnDeviceType
 | 
				
			||||||
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
from authentik.tenants.models import Tenant
 | 
					from authentik.tenants.models import Tenant
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Context set when the serializer is created in a blueprint context
 | 
					# Context set when the serializer is created in a blueprint context
 | 
				
			||||||
@ -118,7 +118,7 @@ def excluded_models() -> list[type[Model]]:
 | 
				
			|||||||
        SCIMProviderGroup,
 | 
					        SCIMProviderGroup,
 | 
				
			||||||
        SCIMProviderUser,
 | 
					        SCIMProviderUser,
 | 
				
			||||||
        Tenant,
 | 
					        Tenant,
 | 
				
			||||||
        SystemTask,
 | 
					        Task,
 | 
				
			||||||
        ConnectionToken,
 | 
					        ConnectionToken,
 | 
				
			||||||
        AuthorizationCode,
 | 
					        AuthorizationCode,
 | 
				
			||||||
        AccessToken,
 | 
					        AccessToken,
 | 
				
			||||||
 | 
				
			|||||||
@ -44,7 +44,7 @@ class ApplyBlueprintMetaSerializer(PassiveSerializer):
 | 
				
			|||||||
            return MetaResult()
 | 
					            return MetaResult()
 | 
				
			||||||
        LOGGER.debug("Applying blueprint from meta model", blueprint=self.blueprint_instance)
 | 
					        LOGGER.debug("Applying blueprint from meta model", blueprint=self.blueprint_instance)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        apply_blueprint(str(self.blueprint_instance.pk))
 | 
					        apply_blueprint(self.blueprint_instance.pk)
 | 
				
			||||||
        return MetaResult()
 | 
					        return MetaResult()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -4,12 +4,17 @@ from dataclasses import asdict, dataclass, field
 | 
				
			|||||||
from hashlib import sha512
 | 
					from hashlib import sha512
 | 
				
			||||||
from pathlib import Path
 | 
					from pathlib import Path
 | 
				
			||||||
from sys import platform
 | 
					from sys import platform
 | 
				
			||||||
 | 
					from uuid import UUID
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from dacite.core import from_dict
 | 
					from dacite.core import from_dict
 | 
				
			||||||
 | 
					from django.conf import settings
 | 
				
			||||||
from django.db import DatabaseError, InternalError, ProgrammingError
 | 
					from django.db import DatabaseError, InternalError, ProgrammingError
 | 
				
			||||||
from django.utils.text import slugify
 | 
					from django.utils.text import slugify
 | 
				
			||||||
from django.utils.timezone import now
 | 
					from django.utils.timezone import now
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask, CurrentTaskNotFound
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
 | 
					from dramatiq.middleware import Middleware
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
from watchdog.events import (
 | 
					from watchdog.events import (
 | 
				
			||||||
    FileCreatedEvent,
 | 
					    FileCreatedEvent,
 | 
				
			||||||
@ -31,15 +36,13 @@ 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.blueprints.v1.oci import OCI_PREFIX
 | 
				
			||||||
from authentik.events.logs import capture_logs
 | 
					from authentik.events.logs import capture_logs
 | 
				
			||||||
from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, prefill_task
 | 
					 | 
				
			||||||
from authentik.events.utils import sanitize_dict
 | 
					from authentik.events.utils import sanitize_dict
 | 
				
			||||||
from authentik.lib.config import CONFIG
 | 
					from authentik.lib.config import CONFIG
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.models import Schedule
 | 
				
			||||||
from authentik.tenants.models import Tenant
 | 
					from authentik.tenants.models import Tenant
 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
_file_watcher_started = False
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@dataclass
 | 
					@dataclass
 | 
				
			||||||
@ -53,22 +56,21 @@ class BlueprintFile:
 | 
				
			|||||||
    meta: BlueprintMetadata | None = field(default=None)
 | 
					    meta: BlueprintMetadata | None = field(default=None)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def start_blueprint_watcher():
 | 
					class BlueprintWatcherMiddleware(Middleware):
 | 
				
			||||||
    """Start blueprint watcher, if it's not running already."""
 | 
					    def start_blueprint_watcher(self):
 | 
				
			||||||
    # This function might be called twice since it's called on celery startup
 | 
					        """Start blueprint watcher"""
 | 
				
			||||||
 | 
					        observer = Observer()
 | 
				
			||||||
 | 
					        kwargs = {}
 | 
				
			||||||
 | 
					        if platform.startswith("linux"):
 | 
				
			||||||
 | 
					            kwargs["event_filter"] = (FileCreatedEvent, FileModifiedEvent)
 | 
				
			||||||
 | 
					        observer.schedule(
 | 
				
			||||||
 | 
					            BlueprintEventHandler(), CONFIG.get("blueprints_dir"), recursive=True, **kwargs
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					        observer.start()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    global _file_watcher_started  # noqa: PLW0603
 | 
					    def after_worker_boot(self, broker, worker):
 | 
				
			||||||
    if _file_watcher_started:
 | 
					        if not settings.TEST:
 | 
				
			||||||
        return
 | 
					            self.start_blueprint_watcher()
 | 
				
			||||||
    observer = Observer()
 | 
					 | 
				
			||||||
    kwargs = {}
 | 
					 | 
				
			||||||
    if platform.startswith("linux"):
 | 
					 | 
				
			||||||
        kwargs["event_filter"] = (FileCreatedEvent, FileModifiedEvent)
 | 
					 | 
				
			||||||
    observer.schedule(
 | 
					 | 
				
			||||||
        BlueprintEventHandler(), CONFIG.get("blueprints_dir"), recursive=True, **kwargs
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
    observer.start()
 | 
					 | 
				
			||||||
    _file_watcher_started = True
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class BlueprintEventHandler(FileSystemEventHandler):
 | 
					class BlueprintEventHandler(FileSystemEventHandler):
 | 
				
			||||||
@ -92,7 +94,7 @@ class BlueprintEventHandler(FileSystemEventHandler):
 | 
				
			|||||||
        LOGGER.debug("new blueprint file created, starting discovery")
 | 
					        LOGGER.debug("new blueprint file created, starting discovery")
 | 
				
			||||||
        for tenant in Tenant.objects.filter(ready=True):
 | 
					        for tenant in Tenant.objects.filter(ready=True):
 | 
				
			||||||
            with tenant:
 | 
					            with tenant:
 | 
				
			||||||
                blueprints_discovery.delay()
 | 
					                Schedule.dispatch_by_actor(blueprints_discovery)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def on_modified(self, event: FileSystemEvent):
 | 
					    def on_modified(self, event: FileSystemEvent):
 | 
				
			||||||
        """Process file modification"""
 | 
					        """Process file modification"""
 | 
				
			||||||
@ -103,14 +105,14 @@ class BlueprintEventHandler(FileSystemEventHandler):
 | 
				
			|||||||
            with tenant:
 | 
					            with tenant:
 | 
				
			||||||
                for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
 | 
					                for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
 | 
				
			||||||
                    LOGGER.debug("modified blueprint file, starting apply", instance=instance)
 | 
					                    LOGGER.debug("modified blueprint file, starting apply", instance=instance)
 | 
				
			||||||
                    apply_blueprint.delay(instance.pk.hex)
 | 
					                    apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(
 | 
				
			||||||
 | 
					    description=_("Find blueprints as `blueprints_find` does, but return a safe dict."),
 | 
				
			||||||
    throws=(DatabaseError, ProgrammingError, InternalError),
 | 
					    throws=(DatabaseError, ProgrammingError, InternalError),
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
def blueprints_find_dict():
 | 
					def blueprints_find_dict():
 | 
				
			||||||
    """Find blueprints as `blueprints_find` does, but return a safe dict"""
 | 
					 | 
				
			||||||
    blueprints = []
 | 
					    blueprints = []
 | 
				
			||||||
    for blueprint in blueprints_find():
 | 
					    for blueprint in blueprints_find():
 | 
				
			||||||
        blueprints.append(sanitize_dict(asdict(blueprint)))
 | 
					        blueprints.append(sanitize_dict(asdict(blueprint)))
 | 
				
			||||||
@ -146,21 +148,19 @@ def blueprints_find() -> list[BlueprintFile]:
 | 
				
			|||||||
    return blueprints
 | 
					    return blueprints
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(
 | 
				
			||||||
    throws=(DatabaseError, ProgrammingError, InternalError), base=SystemTask, bind=True
 | 
					    description=_("Find blueprints and check if they need to be created in the database."),
 | 
				
			||||||
 | 
					    throws=(DatabaseError, ProgrammingError, InternalError),
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
@prefill_task
 | 
					def blueprints_discovery(path: str | None = None):
 | 
				
			||||||
def blueprints_discovery(self: SystemTask, path: str | None = None):
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    """Find blueprints and check if they need to be created in the database"""
 | 
					 | 
				
			||||||
    count = 0
 | 
					    count = 0
 | 
				
			||||||
    for blueprint in blueprints_find():
 | 
					    for blueprint in blueprints_find():
 | 
				
			||||||
        if path and blueprint.path != path:
 | 
					        if path and blueprint.path != path:
 | 
				
			||||||
            continue
 | 
					            continue
 | 
				
			||||||
        check_blueprint_v1_file(blueprint)
 | 
					        check_blueprint_v1_file(blueprint)
 | 
				
			||||||
        count += 1
 | 
					        count += 1
 | 
				
			||||||
    self.set_status(
 | 
					    self.info(f"Successfully imported {count} files.")
 | 
				
			||||||
        TaskStatus.SUCCESSFUL, _("Successfully imported {count} files.".format(count=count))
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def check_blueprint_v1_file(blueprint: BlueprintFile):
 | 
					def check_blueprint_v1_file(blueprint: BlueprintFile):
 | 
				
			||||||
@ -187,22 +187,26 @@ def check_blueprint_v1_file(blueprint: BlueprintFile):
 | 
				
			|||||||
        )
 | 
					        )
 | 
				
			||||||
    if instance.last_applied_hash != blueprint.hash:
 | 
					    if instance.last_applied_hash != blueprint.hash:
 | 
				
			||||||
        LOGGER.info("Applying blueprint due to changed file", instance=instance, path=instance.path)
 | 
					        LOGGER.info("Applying blueprint due to changed file", instance=instance, path=instance.path)
 | 
				
			||||||
        apply_blueprint.delay(str(instance.pk))
 | 
					        apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(description=_("Apply single blueprint."))
 | 
				
			||||||
    bind=True,
 | 
					def apply_blueprint(instance_pk: UUID):
 | 
				
			||||||
    base=SystemTask,
 | 
					    try:
 | 
				
			||||||
)
 | 
					        self: Task = CurrentTask.get_task()
 | 
				
			||||||
def apply_blueprint(self: SystemTask, instance_pk: str):
 | 
					    except CurrentTaskNotFound:
 | 
				
			||||||
    """Apply single blueprint"""
 | 
					        self = Task()
 | 
				
			||||||
    self.save_on_success = False
 | 
					    self.set_uid(str(instance_pk))
 | 
				
			||||||
    instance: BlueprintInstance | None = None
 | 
					    instance: BlueprintInstance | None = None
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
        instance: BlueprintInstance = BlueprintInstance.objects.filter(pk=instance_pk).first()
 | 
					        instance: BlueprintInstance = BlueprintInstance.objects.filter(pk=instance_pk).first()
 | 
				
			||||||
        if not instance or not instance.enabled:
 | 
					        if not instance:
 | 
				
			||||||
 | 
					            self.warning(f"Could not find blueprint {instance_pk}, skipping")
 | 
				
			||||||
            return
 | 
					            return
 | 
				
			||||||
        self.set_uid(slugify(instance.name))
 | 
					        self.set_uid(slugify(instance.name))
 | 
				
			||||||
 | 
					        if not instance.enabled:
 | 
				
			||||||
 | 
					            self.info(f"Blueprint {instance.name} is disabled, skipping")
 | 
				
			||||||
 | 
					            return
 | 
				
			||||||
        blueprint_content = instance.retrieve()
 | 
					        blueprint_content = instance.retrieve()
 | 
				
			||||||
        file_hash = sha512(blueprint_content.encode()).hexdigest()
 | 
					        file_hash = sha512(blueprint_content.encode()).hexdigest()
 | 
				
			||||||
        importer = Importer.from_string(blueprint_content, instance.context)
 | 
					        importer = Importer.from_string(blueprint_content, instance.context)
 | 
				
			||||||
@ -212,19 +216,18 @@ def apply_blueprint(self: SystemTask, instance_pk: str):
 | 
				
			|||||||
        if not valid:
 | 
					        if not valid:
 | 
				
			||||||
            instance.status = BlueprintInstanceStatus.ERROR
 | 
					            instance.status = BlueprintInstanceStatus.ERROR
 | 
				
			||||||
            instance.save()
 | 
					            instance.save()
 | 
				
			||||||
            self.set_status(TaskStatus.ERROR, *logs)
 | 
					            self.logs(logs)
 | 
				
			||||||
            return
 | 
					            return
 | 
				
			||||||
        with capture_logs() as logs:
 | 
					        with capture_logs() as logs:
 | 
				
			||||||
            applied = importer.apply()
 | 
					            applied = importer.apply()
 | 
				
			||||||
            if not applied:
 | 
					            if not applied:
 | 
				
			||||||
                instance.status = BlueprintInstanceStatus.ERROR
 | 
					                instance.status = BlueprintInstanceStatus.ERROR
 | 
				
			||||||
                instance.save()
 | 
					                instance.save()
 | 
				
			||||||
                self.set_status(TaskStatus.ERROR, *logs)
 | 
					                self.logs(logs)
 | 
				
			||||||
                return
 | 
					                return
 | 
				
			||||||
        instance.status = BlueprintInstanceStatus.SUCCESSFUL
 | 
					        instance.status = BlueprintInstanceStatus.SUCCESSFUL
 | 
				
			||||||
        instance.last_applied_hash = file_hash
 | 
					        instance.last_applied_hash = file_hash
 | 
				
			||||||
        instance.last_applied = now()
 | 
					        instance.last_applied = now()
 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
    except (
 | 
					    except (
 | 
				
			||||||
        OSError,
 | 
					        OSError,
 | 
				
			||||||
        DatabaseError,
 | 
					        DatabaseError,
 | 
				
			||||||
@ -235,15 +238,14 @@ def apply_blueprint(self: SystemTask, instance_pk: str):
 | 
				
			|||||||
    ) as exc:
 | 
					    ) as exc:
 | 
				
			||||||
        if instance:
 | 
					        if instance:
 | 
				
			||||||
            instance.status = BlueprintInstanceStatus.ERROR
 | 
					            instance.status = BlueprintInstanceStatus.ERROR
 | 
				
			||||||
        self.set_error(exc)
 | 
					        self.error(exc)
 | 
				
			||||||
    finally:
 | 
					    finally:
 | 
				
			||||||
        if instance:
 | 
					        if instance:
 | 
				
			||||||
            instance.save()
 | 
					            instance.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Remove blueprints which couldn't be fetched."))
 | 
				
			||||||
def clear_failed_blueprints():
 | 
					def clear_failed_blueprints():
 | 
				
			||||||
    """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_PREFIX):
 | 
					    for blueprint in BlueprintInstance.objects.exclude(path__startswith=OCI_PREFIX):
 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
 | 
				
			|||||||
@ -9,6 +9,7 @@ class AuthentikBrandsConfig(ManagedAppConfig):
 | 
				
			|||||||
    name = "authentik.brands"
 | 
					    name = "authentik.brands"
 | 
				
			||||||
    label = "authentik_brands"
 | 
					    label = "authentik_brands"
 | 
				
			||||||
    verbose_name = "authentik Brands"
 | 
					    verbose_name = "authentik Brands"
 | 
				
			||||||
 | 
					    default = True
 | 
				
			||||||
    mountpoints = {
 | 
					    mountpoints = {
 | 
				
			||||||
        "authentik.brands.urls_root": "",
 | 
					        "authentik.brands.urls_root": "",
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
				
			|||||||
@ -1,8 +1,6 @@
 | 
				
			|||||||
"""Authenticator Devices API Views"""
 | 
					"""Authenticator Devices API Views"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from drf_spectacular.utils import extend_schema
 | 
				
			||||||
from drf_spectacular.types import OpenApiTypes
 | 
					 | 
				
			||||||
from drf_spectacular.utils import OpenApiParameter, extend_schema
 | 
					 | 
				
			||||||
from guardian.shortcuts import get_objects_for_user
 | 
					from guardian.shortcuts import get_objects_for_user
 | 
				
			||||||
from rest_framework.fields import (
 | 
					from rest_framework.fields import (
 | 
				
			||||||
    BooleanField,
 | 
					    BooleanField,
 | 
				
			||||||
@ -15,6 +13,7 @@ from rest_framework.request import Request
 | 
				
			|||||||
from rest_framework.response import Response
 | 
					from rest_framework.response import Response
 | 
				
			||||||
from rest_framework.viewsets import ViewSet
 | 
					from rest_framework.viewsets import ViewSet
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from authentik.core.api.users import ParamUserSerializer
 | 
				
			||||||
from authentik.core.api.utils import MetaNameSerializer
 | 
					from authentik.core.api.utils import MetaNameSerializer
 | 
				
			||||||
from authentik.enterprise.stages.authenticator_endpoint_gdtc.models import EndpointDevice
 | 
					from authentik.enterprise.stages.authenticator_endpoint_gdtc.models import EndpointDevice
 | 
				
			||||||
from authentik.stages.authenticator import device_classes, devices_for_user
 | 
					from authentik.stages.authenticator import device_classes, devices_for_user
 | 
				
			||||||
@ -23,7 +22,7 @@ from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class DeviceSerializer(MetaNameSerializer):
 | 
					class DeviceSerializer(MetaNameSerializer):
 | 
				
			||||||
    """Serializer for Duo authenticator devices"""
 | 
					    """Serializer for authenticator devices"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    pk = CharField()
 | 
					    pk = CharField()
 | 
				
			||||||
    name = CharField()
 | 
					    name = CharField()
 | 
				
			||||||
@ -33,22 +32,27 @@ class DeviceSerializer(MetaNameSerializer):
 | 
				
			|||||||
    last_updated = DateTimeField(read_only=True)
 | 
					    last_updated = DateTimeField(read_only=True)
 | 
				
			||||||
    last_used = DateTimeField(read_only=True, allow_null=True)
 | 
					    last_used = DateTimeField(read_only=True, allow_null=True)
 | 
				
			||||||
    extra_description = SerializerMethodField()
 | 
					    extra_description = SerializerMethodField()
 | 
				
			||||||
 | 
					    external_id = SerializerMethodField()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_type(self, instance: Device) -> str:
 | 
					    def get_type(self, instance: Device) -> str:
 | 
				
			||||||
        """Get type of device"""
 | 
					        """Get type of device"""
 | 
				
			||||||
        return instance._meta.label
 | 
					        return instance._meta.label
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_extra_description(self, instance: Device) -> str:
 | 
					    def get_extra_description(self, instance: Device) -> str | None:
 | 
				
			||||||
        """Get extra description"""
 | 
					        """Get extra description"""
 | 
				
			||||||
        if isinstance(instance, WebAuthnDevice):
 | 
					        if isinstance(instance, WebAuthnDevice):
 | 
				
			||||||
            return (
 | 
					            return instance.device_type.description if instance.device_type else None
 | 
				
			||||||
                instance.device_type.description
 | 
					 | 
				
			||||||
                if instance.device_type
 | 
					 | 
				
			||||||
                else _("Extra description not available")
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        if isinstance(instance, EndpointDevice):
 | 
					        if isinstance(instance, EndpointDevice):
 | 
				
			||||||
            return instance.data.get("deviceSignals", {}).get("deviceModel")
 | 
					            return instance.data.get("deviceSignals", {}).get("deviceModel")
 | 
				
			||||||
        return ""
 | 
					        return None
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def get_external_id(self, instance: Device) -> str | None:
 | 
				
			||||||
 | 
					        """Get external Device ID"""
 | 
				
			||||||
 | 
					        if isinstance(instance, WebAuthnDevice):
 | 
				
			||||||
 | 
					            return instance.device_type.aaguid if instance.device_type else None
 | 
				
			||||||
 | 
					        if isinstance(instance, EndpointDevice):
 | 
				
			||||||
 | 
					            return instance.data.get("deviceSignals", {}).get("deviceModel")
 | 
				
			||||||
 | 
					        return None
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class DeviceViewSet(ViewSet):
 | 
					class DeviceViewSet(ViewSet):
 | 
				
			||||||
@ -57,7 +61,6 @@ class DeviceViewSet(ViewSet):
 | 
				
			|||||||
    serializer_class = DeviceSerializer
 | 
					    serializer_class = DeviceSerializer
 | 
				
			||||||
    permission_classes = [IsAuthenticated]
 | 
					    permission_classes = [IsAuthenticated]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @extend_schema(responses={200: DeviceSerializer(many=True)})
 | 
					 | 
				
			||||||
    def list(self, request: Request) -> Response:
 | 
					    def list(self, request: Request) -> Response:
 | 
				
			||||||
        """Get all devices for current user"""
 | 
					        """Get all devices for current user"""
 | 
				
			||||||
        devices = devices_for_user(request.user)
 | 
					        devices = devices_for_user(request.user)
 | 
				
			||||||
@ -79,18 +82,11 @@ class AdminDeviceViewSet(ViewSet):
 | 
				
			|||||||
            yield from device_set
 | 
					            yield from device_set
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @extend_schema(
 | 
					    @extend_schema(
 | 
				
			||||||
        parameters=[
 | 
					        parameters=[ParamUserSerializer],
 | 
				
			||||||
            OpenApiParameter(
 | 
					 | 
				
			||||||
                name="user",
 | 
					 | 
				
			||||||
                location=OpenApiParameter.QUERY,
 | 
					 | 
				
			||||||
                type=OpenApiTypes.INT,
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        ],
 | 
					 | 
				
			||||||
        responses={200: DeviceSerializer(many=True)},
 | 
					        responses={200: DeviceSerializer(many=True)},
 | 
				
			||||||
    )
 | 
					    )
 | 
				
			||||||
    def list(self, request: Request) -> Response:
 | 
					    def list(self, request: Request) -> Response:
 | 
				
			||||||
        """Get all devices for current user"""
 | 
					        """Get all devices for current user"""
 | 
				
			||||||
        kwargs = {}
 | 
					        args = ParamUserSerializer(data=request.query_params)
 | 
				
			||||||
        if "user" in request.query_params:
 | 
					        args.is_valid(raise_exception=True)
 | 
				
			||||||
            kwargs = {"user": request.query_params["user"]}
 | 
					        return Response(DeviceSerializer(self.get_devices(**args.validated_data), many=True).data)
 | 
				
			||||||
        return Response(DeviceSerializer(self.get_devices(**kwargs), many=True).data)
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -90,6 +90,12 @@ from authentik.stages.email.utils import TemplateEmailMessage
 | 
				
			|||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class ParamUserSerializer(PassiveSerializer):
 | 
				
			||||||
 | 
					    """Partial serializer for query parameters to select a user"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    user = PrimaryKeyRelatedField(queryset=User.objects.all().exclude_anonymous(), required=False)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class UserGroupSerializer(ModelSerializer):
 | 
					class UserGroupSerializer(ModelSerializer):
 | 
				
			||||||
    """Simplified Group Serializer for user's groups"""
 | 
					    """Simplified Group Serializer for user's groups"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -401,7 +407,7 @@ class UserViewSet(UsedByMixin, ModelViewSet):
 | 
				
			|||||||
            StrField(User, "path"),
 | 
					            StrField(User, "path"),
 | 
				
			||||||
            BoolField(User, "is_active", nullable=True),
 | 
					            BoolField(User, "is_active", nullable=True),
 | 
				
			||||||
            ChoiceSearchField(User, "type"),
 | 
					            ChoiceSearchField(User, "type"),
 | 
				
			||||||
            JSONSearchField(User, "attributes"),
 | 
					            JSONSearchField(User, "attributes", suggest_nested=False),
 | 
				
			||||||
        ]
 | 
					        ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_queryset(self):
 | 
					    def get_queryset(self):
 | 
				
			||||||
 | 
				
			|||||||
@ -2,6 +2,7 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from typing import Any
 | 
					from typing import Any
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.db import models
 | 
				
			||||||
from django.db.models import Model
 | 
					from django.db.models import Model
 | 
				
			||||||
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
 | 
					from drf_spectacular.extensions import OpenApiSerializerFieldExtension
 | 
				
			||||||
from drf_spectacular.plumbing import build_basic_type
 | 
					from drf_spectacular.plumbing import build_basic_type
 | 
				
			||||||
@ -30,7 +31,27 @@ def is_dict(value: Any):
 | 
				
			|||||||
    raise ValidationError("Value must be a dictionary, and not have any duplicate keys.")
 | 
					    raise ValidationError("Value must be a dictionary, and not have any duplicate keys.")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class JSONDictField(JSONField):
 | 
				
			||||||
 | 
					    """JSON Field which only allows dictionaries"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    default_validators = [is_dict]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class JSONExtension(OpenApiSerializerFieldExtension):
 | 
				
			||||||
 | 
					    """Generate API Schema for JSON fields as"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    target_class = "authentik.core.api.utils.JSONDictField"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def map_serializer_field(self, auto_schema, direction):
 | 
				
			||||||
 | 
					        return build_basic_type(OpenApiTypes.OBJECT)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class ModelSerializer(BaseModelSerializer):
 | 
					class ModelSerializer(BaseModelSerializer):
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    # By default, JSON fields we have are used to store dictionaries
 | 
				
			||||||
 | 
					    serializer_field_mapping = BaseModelSerializer.serializer_field_mapping.copy()
 | 
				
			||||||
 | 
					    serializer_field_mapping[models.JSONField] = JSONDictField
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def create(self, validated_data):
 | 
					    def create(self, validated_data):
 | 
				
			||||||
        instance = super().create(validated_data)
 | 
					        instance = super().create(validated_data)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -71,21 +92,6 @@ class ModelSerializer(BaseModelSerializer):
 | 
				
			|||||||
        return instance
 | 
					        return instance
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class JSONDictField(JSONField):
 | 
					 | 
				
			||||||
    """JSON Field which only allows dictionaries"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    default_validators = [is_dict]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class JSONExtension(OpenApiSerializerFieldExtension):
 | 
					 | 
				
			||||||
    """Generate API Schema for JSON fields as"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    target_class = "authentik.core.api.utils.JSONDictField"
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def map_serializer_field(self, auto_schema, direction):
 | 
					 | 
				
			||||||
        return build_basic_type(OpenApiTypes.OBJECT)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class PassiveSerializer(Serializer):
 | 
					class PassiveSerializer(Serializer):
 | 
				
			||||||
    """Base serializer class which doesn't implement create/update methods"""
 | 
					    """Base serializer class which doesn't implement create/update methods"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -1,8 +1,7 @@
 | 
				
			|||||||
"""authentik core app config"""
 | 
					"""authentik core app config"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.conf import settings
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.blueprints.apps import ManagedAppConfig
 | 
					from authentik.blueprints.apps import ManagedAppConfig
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class AuthentikCoreConfig(ManagedAppConfig):
 | 
					class AuthentikCoreConfig(ManagedAppConfig):
 | 
				
			||||||
@ -14,14 +13,6 @@ class AuthentikCoreConfig(ManagedAppConfig):
 | 
				
			|||||||
    mountpoint = ""
 | 
					    mountpoint = ""
 | 
				
			||||||
    default = True
 | 
					    default = True
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @ManagedAppConfig.reconcile_global
 | 
					 | 
				
			||||||
    def debug_worker_hook(self):
 | 
					 | 
				
			||||||
        """Dispatch startup tasks inline when debugging"""
 | 
					 | 
				
			||||||
        if settings.DEBUG:
 | 
					 | 
				
			||||||
            from authentik.root.celery import worker_ready_hook
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
            worker_ready_hook()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    @ManagedAppConfig.reconcile_tenant
 | 
					    @ManagedAppConfig.reconcile_tenant
 | 
				
			||||||
    def source_inbuilt(self):
 | 
					    def source_inbuilt(self):
 | 
				
			||||||
        """Reconcile inbuilt source"""
 | 
					        """Reconcile inbuilt source"""
 | 
				
			||||||
@ -34,3 +25,18 @@ class AuthentikCoreConfig(ManagedAppConfig):
 | 
				
			|||||||
            },
 | 
					            },
 | 
				
			||||||
            managed=Source.MANAGED_INBUILT,
 | 
					            managed=Source.MANAGED_INBUILT,
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.core.tasks import clean_expired_models, clean_temporary_users
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=clean_expired_models,
 | 
				
			||||||
 | 
					                crontab="2-59/5 * * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=clean_temporary_users,
 | 
				
			||||||
 | 
					                crontab="9-59/5 * * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -1,21 +0,0 @@
 | 
				
			|||||||
"""Run bootstrap tasks"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.core.management.base import BaseCommand
 | 
					 | 
				
			||||||
from django_tenants.utils import get_public_schema_name
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.root.celery import _get_startup_tasks_all_tenants, _get_startup_tasks_default_tenant
 | 
					 | 
				
			||||||
from authentik.tenants.models import Tenant
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class Command(BaseCommand):
 | 
					 | 
				
			||||||
    """Run bootstrap tasks to ensure certain objects are created"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def handle(self, **options):
 | 
					 | 
				
			||||||
        for task in _get_startup_tasks_default_tenant():
 | 
					 | 
				
			||||||
            with Tenant.objects.get(schema_name=get_public_schema_name()):
 | 
					 | 
				
			||||||
                task()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        for task in _get_startup_tasks_all_tenants():
 | 
					 | 
				
			||||||
            for tenant in Tenant.objects.filter(ready=True):
 | 
					 | 
				
			||||||
                with tenant:
 | 
					 | 
				
			||||||
                    task()
 | 
					 | 
				
			||||||
@ -13,7 +13,6 @@ class Command(TenantCommand):
 | 
				
			|||||||
        parser.add_argument("usernames", nargs="*", type=str)
 | 
					        parser.add_argument("usernames", nargs="*", type=str)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def handle_per_tenant(self, **options):
 | 
					    def handle_per_tenant(self, **options):
 | 
				
			||||||
        print(options)
 | 
					 | 
				
			||||||
        new_type = UserTypes(options["type"])
 | 
					        new_type = UserTypes(options["type"])
 | 
				
			||||||
        qs = (
 | 
					        qs = (
 | 
				
			||||||
            User.objects.exclude_anonymous()
 | 
					            User.objects.exclude_anonymous()
 | 
				
			||||||
 | 
				
			|||||||
@ -1,47 +0,0 @@
 | 
				
			|||||||
"""Run worker"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from sys import exit as sysexit
 | 
					 | 
				
			||||||
from tempfile import tempdir
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.apps.worker import Worker
 | 
					 | 
				
			||||||
from django.core.management.base import BaseCommand
 | 
					 | 
				
			||||||
from django.db import close_old_connections
 | 
					 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.config import CONFIG
 | 
					 | 
				
			||||||
from authentik.lib.debug import start_debug_server
 | 
					 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
LOGGER = get_logger()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class Command(BaseCommand):
 | 
					 | 
				
			||||||
    """Run worker"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def add_arguments(self, parser):
 | 
					 | 
				
			||||||
        parser.add_argument(
 | 
					 | 
				
			||||||
            "-b",
 | 
					 | 
				
			||||||
            "--beat",
 | 
					 | 
				
			||||||
            action="store_false",
 | 
					 | 
				
			||||||
            help="When set, this worker will _not_ run Beat (scheduled) tasks",
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def handle(self, **options):
 | 
					 | 
				
			||||||
        LOGGER.debug("Celery options", **options)
 | 
					 | 
				
			||||||
        close_old_connections()
 | 
					 | 
				
			||||||
        start_debug_server()
 | 
					 | 
				
			||||||
        worker: Worker = CELERY_APP.Worker(
 | 
					 | 
				
			||||||
            no_color=False,
 | 
					 | 
				
			||||||
            quiet=True,
 | 
					 | 
				
			||||||
            optimization="fair",
 | 
					 | 
				
			||||||
            autoscale=(CONFIG.get_int("worker.concurrency"), 1),
 | 
					 | 
				
			||||||
            task_events=True,
 | 
					 | 
				
			||||||
            beat=options.get("beat", True),
 | 
					 | 
				
			||||||
            schedule_filename=f"{tempdir}/celerybeat-schedule",
 | 
					 | 
				
			||||||
            queues=["authentik", "authentik_scheduled", "authentik_events"],
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        for task in CELERY_APP.tasks:
 | 
					 | 
				
			||||||
            LOGGER.debug("Registered task", task=task)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        worker.start()
 | 
					 | 
				
			||||||
        sysexit(worker.exitcode)
 | 
					 | 
				
			||||||
@ -1082,6 +1082,12 @@ class AuthenticatedSession(SerializerModel):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    user = models.ForeignKey(User, on_delete=models.CASCADE)
 | 
					    user = models.ForeignKey(User, on_delete=models.CASCADE)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def serializer(self) -> type[Serializer]:
 | 
				
			||||||
 | 
					        from authentik.core.api.authenticated_sessions import AuthenticatedSessionSerializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return AuthenticatedSessionSerializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    class Meta:
 | 
					    class Meta:
 | 
				
			||||||
        verbose_name = _("Authenticated Session")
 | 
					        verbose_name = _("Authenticated Session")
 | 
				
			||||||
        verbose_name_plural = _("Authenticated Sessions")
 | 
					        verbose_name_plural = _("Authenticated Sessions")
 | 
				
			||||||
 | 
				
			|||||||
@ -3,6 +3,9 @@
 | 
				
			|||||||
from datetime import datetime, timedelta
 | 
					from datetime import datetime, timedelta
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.utils.timezone import now
 | 
					from django.utils.timezone import now
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.core.models import (
 | 
					from authentik.core.models import (
 | 
				
			||||||
@ -11,17 +14,14 @@ from authentik.core.models import (
 | 
				
			|||||||
    ExpiringModel,
 | 
					    ExpiringModel,
 | 
				
			||||||
    User,
 | 
					    User,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Remove expired objects."))
 | 
				
			||||||
@prefill_task
 | 
					def clean_expired_models():
 | 
				
			||||||
def clean_expired_models(self: SystemTask):
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    """Remove expired objects"""
 | 
					 | 
				
			||||||
    messages = []
 | 
					 | 
				
			||||||
    for cls in ExpiringModel.__subclasses__():
 | 
					    for cls in ExpiringModel.__subclasses__():
 | 
				
			||||||
        cls: ExpiringModel
 | 
					        cls: ExpiringModel
 | 
				
			||||||
        objects = (
 | 
					        objects = (
 | 
				
			||||||
@ -31,16 +31,13 @@ def clean_expired_models(self: SystemTask):
 | 
				
			|||||||
        for obj in objects:
 | 
					        for obj in objects:
 | 
				
			||||||
            obj.expire_action()
 | 
					            obj.expire_action()
 | 
				
			||||||
        LOGGER.debug("Expired models", model=cls, amount=amount)
 | 
					        LOGGER.debug("Expired models", model=cls, amount=amount)
 | 
				
			||||||
        messages.append(f"Expired {amount} {cls._meta.verbose_name_plural}")
 | 
					        self.info(f"Expired {amount} {cls._meta.verbose_name_plural}")
 | 
				
			||||||
    self.set_status(TaskStatus.SUCCESSFUL, *messages)
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Remove temporary users created by SAML Sources."))
 | 
				
			||||||
@prefill_task
 | 
					def clean_temporary_users():
 | 
				
			||||||
def clean_temporary_users(self: SystemTask):
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    """Remove temporary users created by SAML Sources"""
 | 
					 | 
				
			||||||
    _now = datetime.now()
 | 
					    _now = datetime.now()
 | 
				
			||||||
    messages = []
 | 
					 | 
				
			||||||
    deleted_users = 0
 | 
					    deleted_users = 0
 | 
				
			||||||
    for user in User.objects.filter(**{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}):
 | 
					    for user in User.objects.filter(**{f"attributes__{USER_ATTRIBUTE_GENERATED}": True}):
 | 
				
			||||||
        if not user.attributes.get(USER_ATTRIBUTE_EXPIRES):
 | 
					        if not user.attributes.get(USER_ATTRIBUTE_EXPIRES):
 | 
				
			||||||
@ -52,5 +49,4 @@ def clean_temporary_users(self: SystemTask):
 | 
				
			|||||||
            LOGGER.debug("User is expired and will be deleted.", user=user, delta=delta)
 | 
					            LOGGER.debug("User is expired and will be deleted.", user=user, delta=delta)
 | 
				
			||||||
            user.delete()
 | 
					            user.delete()
 | 
				
			||||||
            deleted_users += 1
 | 
					            deleted_users += 1
 | 
				
			||||||
    messages.append(f"Successfully deleted {deleted_users} users.")
 | 
					    self.info(f"Successfully deleted {deleted_users} users.")
 | 
				
			||||||
    self.set_status(TaskStatus.SUCCESSFUL, *messages)
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -36,7 +36,7 @@ class TestTasks(APITestCase):
 | 
				
			|||||||
            expires=now(), user=get_anonymous_user(), intent=TokenIntents.INTENT_API
 | 
					            expires=now(), user=get_anonymous_user(), intent=TokenIntents.INTENT_API
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        key = token.key
 | 
					        key = token.key
 | 
				
			||||||
        clean_expired_models.delay().get()
 | 
					        clean_expired_models.send()
 | 
				
			||||||
        token.refresh_from_db()
 | 
					        token.refresh_from_db()
 | 
				
			||||||
        self.assertNotEqual(key, token.key)
 | 
					        self.assertNotEqual(key, token.key)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -50,5 +50,5 @@ class TestTasks(APITestCase):
 | 
				
			|||||||
                USER_ATTRIBUTE_EXPIRES: mktime(now().timetuple()),
 | 
					                USER_ATTRIBUTE_EXPIRES: mktime(now().timetuple()),
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        clean_temporary_users.delay().get()
 | 
					        clean_temporary_users.send()
 | 
				
			||||||
        self.assertFalse(User.objects.filter(username=username))
 | 
					        self.assertFalse(User.objects.filter(username=username))
 | 
				
			||||||
 | 
				
			|||||||
@ -4,6 +4,8 @@ from datetime import UTC, datetime
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from authentik.blueprints.apps import ManagedAppConfig
 | 
					from authentik.blueprints.apps import ManagedAppConfig
 | 
				
			||||||
from authentik.lib.generators import generate_id
 | 
					from authentik.lib.generators import generate_id
 | 
				
			||||||
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
MANAGED_KEY = "goauthentik.io/crypto/jwt-managed"
 | 
					MANAGED_KEY = "goauthentik.io/crypto/jwt-managed"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -67,3 +69,14 @@ class AuthentikCryptoConfig(ManagedAppConfig):
 | 
				
			|||||||
                "key_data": builder.private_key,
 | 
					                "key_data": builder.private_key,
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.crypto.tasks import certificate_discovery
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=certificate_discovery,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('crypto_certificate_discovery')} * * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -1,13 +0,0 @@
 | 
				
			|||||||
"""Crypto task Settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "crypto_certificate_discovery": {
 | 
					 | 
				
			||||||
        "task": "authentik.crypto.tasks.certificate_discovery",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("crypto_certificate_discovery"), hour="*"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -7,13 +7,13 @@ from cryptography.hazmat.backends import default_backend
 | 
				
			|||||||
from cryptography.hazmat.primitives.serialization import load_pem_private_key
 | 
					from cryptography.hazmat.primitives.serialization import load_pem_private_key
 | 
				
			||||||
from cryptography.x509.base import load_pem_x509_certificate
 | 
					from cryptography.x509.base import load_pem_x509_certificate
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.crypto.models import CertificateKeyPair
 | 
					from authentik.crypto.models import CertificateKeyPair
 | 
				
			||||||
from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, prefill_task
 | 
					 | 
				
			||||||
from authentik.lib.config import CONFIG
 | 
					from authentik.lib.config import CONFIG
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -36,10 +36,9 @@ def ensure_certificate_valid(body: str):
 | 
				
			|||||||
    return body
 | 
					    return body
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Discover, import and update certificates from the filesystem."))
 | 
				
			||||||
@prefill_task
 | 
					def certificate_discovery():
 | 
				
			||||||
def certificate_discovery(self: SystemTask):
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    """Discover, import and update certificates from the filesystem"""
 | 
					 | 
				
			||||||
    certs = {}
 | 
					    certs = {}
 | 
				
			||||||
    private_keys = {}
 | 
					    private_keys = {}
 | 
				
			||||||
    discovered = 0
 | 
					    discovered = 0
 | 
				
			||||||
@ -84,6 +83,4 @@ def certificate_discovery(self: SystemTask):
 | 
				
			|||||||
                dirty = True
 | 
					                dirty = True
 | 
				
			||||||
        if dirty:
 | 
					        if dirty:
 | 
				
			||||||
            cert.save()
 | 
					            cert.save()
 | 
				
			||||||
    self.set_status(
 | 
					    self.info(f"Successfully imported {discovered} files.")
 | 
				
			||||||
        TaskStatus.SUCCESSFUL, _("Successfully imported {count} files.".format(count=discovered))
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -338,7 +338,7 @@ 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):
 | 
				
			||||||
                certificate_discovery()
 | 
					                certificate_discovery.send()
 | 
				
			||||||
        keypair: CertificateKeyPair = CertificateKeyPair.objects.filter(
 | 
					        keypair: CertificateKeyPair = CertificateKeyPair.objects.filter(
 | 
				
			||||||
            managed=MANAGED_DISCOVERED % "foo"
 | 
					            managed=MANAGED_DISCOVERED % "foo"
 | 
				
			||||||
        ).first()
 | 
					        ).first()
 | 
				
			||||||
 | 
				
			|||||||
@ -3,6 +3,8 @@
 | 
				
			|||||||
from django.conf import settings
 | 
					from django.conf import settings
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.blueprints.apps import ManagedAppConfig
 | 
					from authentik.blueprints.apps import ManagedAppConfig
 | 
				
			||||||
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class EnterpriseConfig(ManagedAppConfig):
 | 
					class EnterpriseConfig(ManagedAppConfig):
 | 
				
			||||||
@ -26,3 +28,14 @@ class AuthentikEnterpriseConfig(EnterpriseConfig):
 | 
				
			|||||||
        from authentik.enterprise.license import LicenseKey
 | 
					        from authentik.enterprise.license import LicenseKey
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return LicenseKey.cached_summary().status.is_valid
 | 
					        return LicenseKey.cached_summary().status.is_valid
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.enterprise.tasks import enterprise_update_usage
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=enterprise_update_usage,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('enterprise_update_usage')} */2 * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -1,6 +1,8 @@
 | 
				
			|||||||
"""authentik Unique Password policy app config"""
 | 
					"""authentik Unique Password policy app config"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.apps import EnterpriseConfig
 | 
					from authentik.enterprise.apps import EnterpriseConfig
 | 
				
			||||||
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class AuthentikEnterprisePoliciesUniquePasswordConfig(EnterpriseConfig):
 | 
					class AuthentikEnterprisePoliciesUniquePasswordConfig(EnterpriseConfig):
 | 
				
			||||||
@ -8,3 +10,21 @@ class AuthentikEnterprisePoliciesUniquePasswordConfig(EnterpriseConfig):
 | 
				
			|||||||
    label = "authentik_policies_unique_password"
 | 
					    label = "authentik_policies_unique_password"
 | 
				
			||||||
    verbose_name = "authentik Enterprise.Policies.Unique Password"
 | 
					    verbose_name = "authentik Enterprise.Policies.Unique Password"
 | 
				
			||||||
    default = True
 | 
					    default = True
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.enterprise.policies.unique_password.tasks import (
 | 
				
			||||||
 | 
					            check_and_purge_password_history,
 | 
				
			||||||
 | 
					            trim_password_histories,
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=trim_password_histories,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('policies_unique_password_trim')} */12 * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=check_and_purge_password_history,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('policies_unique_password_purge')} */24 * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
				
			|||||||
@ -1,20 +0,0 @@
 | 
				
			|||||||
"""Unique Password Policy settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "policies_unique_password_trim_history": {
 | 
					 | 
				
			||||||
        "task": "authentik.enterprise.policies.unique_password.tasks.trim_password_histories",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("policies_unique_password_trim"), hour="*/12"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
    "policies_unique_password_check_purge": {
 | 
					 | 
				
			||||||
        "task": (
 | 
					 | 
				
			||||||
            "authentik.enterprise.policies.unique_password.tasks.check_and_purge_password_history"
 | 
					 | 
				
			||||||
        ),
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("policies_unique_password_purge"), hour="*/24"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -1,35 +1,37 @@
 | 
				
			|||||||
from django.db.models.aggregates import Count
 | 
					from django.db.models.aggregates import Count
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
from structlog import get_logger
 | 
					from structlog import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.policies.unique_password.models import (
 | 
					from authentik.enterprise.policies.unique_password.models import (
 | 
				
			||||||
    UniquePasswordPolicy,
 | 
					    UniquePasswordPolicy,
 | 
				
			||||||
    UserPasswordHistory,
 | 
					    UserPasswordHistory,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(
 | 
				
			||||||
@prefill_task
 | 
					    description=_(
 | 
				
			||||||
def check_and_purge_password_history(self: SystemTask):
 | 
					        "Check if any UniquePasswordPolicy exists, and if not, purge the password history table."
 | 
				
			||||||
    """Check if any UniquePasswordPolicy exists, and if not, purge the password history table.
 | 
					    )
 | 
				
			||||||
    This is run on a schedule instead of being triggered by policy binding deletion.
 | 
					)
 | 
				
			||||||
    """
 | 
					def check_and_purge_password_history():
 | 
				
			||||||
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    if not UniquePasswordPolicy.objects.exists():
 | 
					    if not UniquePasswordPolicy.objects.exists():
 | 
				
			||||||
        UserPasswordHistory.objects.all().delete()
 | 
					        UserPasswordHistory.objects.all().delete()
 | 
				
			||||||
        LOGGER.debug("Purged UserPasswordHistory table as no policies are in use")
 | 
					        LOGGER.debug("Purged UserPasswordHistory table as no policies are in use")
 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL, "Successfully purged UserPasswordHistory")
 | 
					        self.info("Successfully purged UserPasswordHistory")
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    self.set_status(
 | 
					    self.info("Not purging password histories, a unique password policy exists")
 | 
				
			||||||
        TaskStatus.SUCCESSFUL, "Not purging password histories, a unique password policy exists"
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Remove user password history that are too old."))
 | 
				
			||||||
def trim_password_histories(self: SystemTask):
 | 
					def trim_password_histories():
 | 
				
			||||||
    """Removes rows from UserPasswordHistory older than
 | 
					    """Removes rows from UserPasswordHistory older than
 | 
				
			||||||
    the `n` most recent entries.
 | 
					    the `n` most recent entries.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -37,6 +39,8 @@ def trim_password_histories(self: SystemTask):
 | 
				
			|||||||
    UniquePasswordPolicy policies.
 | 
					    UniquePasswordPolicy policies.
 | 
				
			||||||
    """
 | 
					    """
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    # No policy, we'll let the cleanup above do its thing
 | 
					    # No policy, we'll let the cleanup above do its thing
 | 
				
			||||||
    if not UniquePasswordPolicy.objects.exists():
 | 
					    if not UniquePasswordPolicy.objects.exists():
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
@ -63,4 +67,4 @@ def trim_password_histories(self: SystemTask):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    num_deleted, _ = UserPasswordHistory.objects.exclude(pk__in=all_pks_to_keep).delete()
 | 
					    num_deleted, _ = UserPasswordHistory.objects.exclude(pk__in=all_pks_to_keep).delete()
 | 
				
			||||||
    LOGGER.debug("Deleted stale password history records", count=num_deleted)
 | 
					    LOGGER.debug("Deleted stale password history records", count=num_deleted)
 | 
				
			||||||
    self.set_status(TaskStatus.SUCCESSFUL, f"Delete {num_deleted} stale password history records")
 | 
					    self.info(f"Delete {num_deleted} stale password history records")
 | 
				
			||||||
 | 
				
			|||||||
@ -76,7 +76,7 @@ class TestCheckAndPurgePasswordHistory(TestCase):
 | 
				
			|||||||
        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
					        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        # Run the task - should purge since no policy is in use
 | 
					        # Run the task - should purge since no policy is in use
 | 
				
			||||||
        check_and_purge_password_history()
 | 
					        check_and_purge_password_history.send()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        # Verify the table is empty
 | 
					        # Verify the table is empty
 | 
				
			||||||
        self.assertFalse(UserPasswordHistory.objects.exists())
 | 
					        self.assertFalse(UserPasswordHistory.objects.exists())
 | 
				
			||||||
@ -99,7 +99,7 @@ class TestCheckAndPurgePasswordHistory(TestCase):
 | 
				
			|||||||
        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
					        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        # Run the task - should NOT purge since a policy is in use
 | 
					        # Run the task - should NOT purge since a policy is in use
 | 
				
			||||||
        check_and_purge_password_history()
 | 
					        check_and_purge_password_history.send()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        # Verify the entries still exist
 | 
					        # Verify the entries still exist
 | 
				
			||||||
        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
					        self.assertTrue(UserPasswordHistory.objects.exists())
 | 
				
			||||||
@ -142,7 +142,7 @@ class TestTrimPasswordHistory(TestCase):
 | 
				
			|||||||
            enabled=True,
 | 
					            enabled=True,
 | 
				
			||||||
            order=0,
 | 
					            order=0,
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        trim_password_histories.delay()
 | 
					        trim_password_histories.send()
 | 
				
			||||||
        user_pwd_history_qs = UserPasswordHistory.objects.filter(user=self.user)
 | 
					        user_pwd_history_qs = UserPasswordHistory.objects.filter(user=self.user)
 | 
				
			||||||
        self.assertEqual(len(user_pwd_history_qs), 1)
 | 
					        self.assertEqual(len(user_pwd_history_qs), 1)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -159,7 +159,7 @@ class TestTrimPasswordHistory(TestCase):
 | 
				
			|||||||
            enabled=False,
 | 
					            enabled=False,
 | 
				
			||||||
            order=0,
 | 
					            order=0,
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        trim_password_histories.delay()
 | 
					        trim_password_histories.send()
 | 
				
			||||||
        self.assertTrue(UserPasswordHistory.objects.filter(user=self.user).exists())
 | 
					        self.assertTrue(UserPasswordHistory.objects.filter(user=self.user).exists())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def test_trim_password_history_fewer_records_than_maximum_is_no_op(self):
 | 
					    def test_trim_password_history_fewer_records_than_maximum_is_no_op(self):
 | 
				
			||||||
@ -174,5 +174,5 @@ class TestTrimPasswordHistory(TestCase):
 | 
				
			|||||||
            enabled=True,
 | 
					            enabled=True,
 | 
				
			||||||
            order=0,
 | 
					            order=0,
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        trim_password_histories.delay()
 | 
					        trim_password_histories.send()
 | 
				
			||||||
        self.assertTrue(UserPasswordHistory.objects.filter(user=self.user).exists())
 | 
					        self.assertTrue(UserPasswordHistory.objects.filter(user=self.user).exists())
 | 
				
			||||||
 | 
				
			|||||||
@ -55,5 +55,5 @@ class GoogleWorkspaceProviderViewSet(OutgoingSyncProviderStatusMixin, UsedByMixi
 | 
				
			|||||||
    ]
 | 
					    ]
 | 
				
			||||||
    search_fields = ["name"]
 | 
					    search_fields = ["name"]
 | 
				
			||||||
    ordering = ["name"]
 | 
					    ordering = ["name"]
 | 
				
			||||||
    sync_single_task = google_workspace_sync
 | 
					    sync_task = google_workspace_sync
 | 
				
			||||||
    sync_objects_task = google_workspace_sync_objects
 | 
					    sync_objects_task = google_workspace_sync_objects
 | 
				
			||||||
 | 
				
			|||||||
@ -7,6 +7,7 @@ from django.db import models
 | 
				
			|||||||
from django.db.models import QuerySet
 | 
					from django.db.models import QuerySet
 | 
				
			||||||
from django.templatetags.static import static
 | 
					from django.templatetags.static import static
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from dramatiq.actor import Actor
 | 
				
			||||||
from google.oauth2.service_account import Credentials
 | 
					from google.oauth2.service_account import Credentials
 | 
				
			||||||
from rest_framework.serializers import Serializer
 | 
					from rest_framework.serializers import Serializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -110,6 +111,12 @@ class GoogleWorkspaceProvider(OutgoingSyncProvider, BackchannelProvider):
 | 
				
			|||||||
        help_text=_("Property mappings used for group creation/updating."),
 | 
					        help_text=_("Property mappings used for group creation/updating."),
 | 
				
			||||||
    )
 | 
					    )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def sync_actor(self) -> Actor:
 | 
				
			||||||
 | 
					        from authentik.enterprise.providers.google_workspace.tasks import google_workspace_sync
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return google_workspace_sync
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def client_for_model(
 | 
					    def client_for_model(
 | 
				
			||||||
        self,
 | 
					        self,
 | 
				
			||||||
        model: type[User | Group | GoogleWorkspaceProviderUser | GoogleWorkspaceProviderGroup],
 | 
					        model: type[User | Group | GoogleWorkspaceProviderUser | GoogleWorkspaceProviderGroup],
 | 
				
			||||||
 | 
				
			|||||||
@ -1,13 +0,0 @@
 | 
				
			|||||||
"""Google workspace provider task Settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "providers_google_workspace_sync": {
 | 
					 | 
				
			||||||
        "task": "authentik.enterprise.providers.google_workspace.tasks.google_workspace_sync_all",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("google_workspace_sync_all"), hour="*/4"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -2,15 +2,13 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
 | 
					from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
 | 
				
			||||||
from authentik.enterprise.providers.google_workspace.tasks import (
 | 
					from authentik.enterprise.providers.google_workspace.tasks import (
 | 
				
			||||||
    google_workspace_sync,
 | 
					    google_workspace_sync_direct_dispatch,
 | 
				
			||||||
    google_workspace_sync_direct,
 | 
					    google_workspace_sync_m2m_dispatch,
 | 
				
			||||||
    google_workspace_sync_m2m,
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.lib.sync.outgoing.signals import register_signals
 | 
					from authentik.lib.sync.outgoing.signals import register_signals
 | 
				
			||||||
 | 
					
 | 
				
			||||||
register_signals(
 | 
					register_signals(
 | 
				
			||||||
    GoogleWorkspaceProvider,
 | 
					    GoogleWorkspaceProvider,
 | 
				
			||||||
    task_sync_single=google_workspace_sync,
 | 
					    task_sync_direct_dispatch=google_workspace_sync_direct_dispatch,
 | 
				
			||||||
    task_sync_direct=google_workspace_sync_direct,
 | 
					    task_sync_m2m_dispatch=google_workspace_sync_m2m_dispatch,
 | 
				
			||||||
    task_sync_m2m=google_workspace_sync_m2m,
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
				
			|||||||
@ -1,37 +1,48 @@
 | 
				
			|||||||
"""Google Provider tasks"""
 | 
					"""Google Provider tasks"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
 | 
					from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask
 | 
					 | 
				
			||||||
from authentik.lib.sync.outgoing.exceptions import TransientSyncException
 | 
					 | 
				
			||||||
from authentik.lib.sync.outgoing.tasks import SyncTasks
 | 
					from authentik.lib.sync.outgoing.tasks import SyncTasks
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
sync_tasks = SyncTasks(GoogleWorkspaceProvider)
 | 
					sync_tasks = SyncTasks(GoogleWorkspaceProvider)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					@actor(description=_("Sync Google Workspace provider objects."))
 | 
				
			||||||
def google_workspace_sync_objects(*args, **kwargs):
 | 
					def google_workspace_sync_objects(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_objects(*args, **kwargs)
 | 
					    return sync_tasks.sync_objects(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(description=_("Full sync for Google Workspace provider."))
 | 
				
			||||||
    base=SystemTask, bind=True, autoretry_for=(TransientSyncException,), retry_backoff=True
 | 
					def google_workspace_sync(provider_pk: int, *args, **kwargs):
 | 
				
			||||||
)
 | 
					 | 
				
			||||||
def google_workspace_sync(self, provider_pk: int, *args, **kwargs):
 | 
					 | 
				
			||||||
    """Run full sync for Google Workspace provider"""
 | 
					    """Run full sync for Google Workspace provider"""
 | 
				
			||||||
    return sync_tasks.sync_single(self, provider_pk, google_workspace_sync_objects)
 | 
					    return sync_tasks.sync(provider_pk, google_workspace_sync_objects)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Sync a direct object (user, group) for Google Workspace provider."))
 | 
				
			||||||
def google_workspace_sync_all():
 | 
					 | 
				
			||||||
    return sync_tasks.sync_all(google_workspace_sync)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					 | 
				
			||||||
def google_workspace_sync_direct(*args, **kwargs):
 | 
					def google_workspace_sync_direct(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_signal_direct(*args, **kwargs)
 | 
					    return sync_tasks.sync_signal_direct(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					@actor(
 | 
				
			||||||
 | 
					    description=_(
 | 
				
			||||||
 | 
					        "Dispatch syncs for a direct object (user, group) for Google Workspace providers."
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					def google_workspace_sync_direct_dispatch(*args, **kwargs):
 | 
				
			||||||
 | 
					    return sync_tasks.sync_signal_direct_dispatch(google_workspace_sync_direct, *args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					@actor(description=_("Sync a related object (memberships) for Google Workspace provider."))
 | 
				
			||||||
def google_workspace_sync_m2m(*args, **kwargs):
 | 
					def google_workspace_sync_m2m(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_signal_m2m(*args, **kwargs)
 | 
					    return sync_tasks.sync_signal_m2m(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					@actor(
 | 
				
			||||||
 | 
					    description=_(
 | 
				
			||||||
 | 
					        "Dispatch syncs for a related object (memberships) for Google Workspace providers."
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					def google_workspace_sync_m2m_dispatch(*args, **kwargs):
 | 
				
			||||||
 | 
					    return sync_tasks.sync_signal_m2m_dispatch(google_workspace_sync_m2m, *args, **kwargs)
 | 
				
			||||||
 | 
				
			|||||||
@ -324,7 +324,7 @@ class GoogleWorkspaceGroupTests(TestCase):
 | 
				
			|||||||
            "authentik.enterprise.providers.google_workspace.models.GoogleWorkspaceProvider.google_credentials",
 | 
					            "authentik.enterprise.providers.google_workspace.models.GoogleWorkspaceProvider.google_credentials",
 | 
				
			||||||
            MagicMock(return_value={"developerKey": self.api_key, "http": http}),
 | 
					            MagicMock(return_value={"developerKey": self.api_key, "http": http}),
 | 
				
			||||||
        ):
 | 
					        ):
 | 
				
			||||||
            google_workspace_sync.delay(self.provider.pk).get()
 | 
					            google_workspace_sync.send(self.provider.pk).get_result()
 | 
				
			||||||
            self.assertTrue(
 | 
					            self.assertTrue(
 | 
				
			||||||
                GoogleWorkspaceProviderGroup.objects.filter(
 | 
					                GoogleWorkspaceProviderGroup.objects.filter(
 | 
				
			||||||
                    group=different_group, provider=self.provider
 | 
					                    group=different_group, provider=self.provider
 | 
				
			||||||
 | 
				
			|||||||
@ -302,7 +302,7 @@ class GoogleWorkspaceUserTests(TestCase):
 | 
				
			|||||||
            "authentik.enterprise.providers.google_workspace.models.GoogleWorkspaceProvider.google_credentials",
 | 
					            "authentik.enterprise.providers.google_workspace.models.GoogleWorkspaceProvider.google_credentials",
 | 
				
			||||||
            MagicMock(return_value={"developerKey": self.api_key, "http": http}),
 | 
					            MagicMock(return_value={"developerKey": self.api_key, "http": http}),
 | 
				
			||||||
        ):
 | 
					        ):
 | 
				
			||||||
            google_workspace_sync.delay(self.provider.pk).get()
 | 
					            google_workspace_sync.send(self.provider.pk).get_result()
 | 
				
			||||||
            self.assertTrue(
 | 
					            self.assertTrue(
 | 
				
			||||||
                GoogleWorkspaceProviderUser.objects.filter(
 | 
					                GoogleWorkspaceProviderUser.objects.filter(
 | 
				
			||||||
                    user=different_user, provider=self.provider
 | 
					                    user=different_user, provider=self.provider
 | 
				
			||||||
 | 
				
			|||||||
@ -53,5 +53,5 @@ class MicrosoftEntraProviderViewSet(OutgoingSyncProviderStatusMixin, UsedByMixin
 | 
				
			|||||||
    ]
 | 
					    ]
 | 
				
			||||||
    search_fields = ["name"]
 | 
					    search_fields = ["name"]
 | 
				
			||||||
    ordering = ["name"]
 | 
					    ordering = ["name"]
 | 
				
			||||||
    sync_single_task = microsoft_entra_sync
 | 
					    sync_task = microsoft_entra_sync
 | 
				
			||||||
    sync_objects_task = microsoft_entra_sync_objects
 | 
					    sync_objects_task = microsoft_entra_sync_objects
 | 
				
			||||||
 | 
				
			|||||||
@ -8,6 +8,7 @@ from django.db import models
 | 
				
			|||||||
from django.db.models import QuerySet
 | 
					from django.db.models import QuerySet
 | 
				
			||||||
from django.templatetags.static import static
 | 
					from django.templatetags.static import static
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from dramatiq.actor import Actor
 | 
				
			||||||
from rest_framework.serializers import Serializer
 | 
					from rest_framework.serializers import Serializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.core.models import (
 | 
					from authentik.core.models import (
 | 
				
			||||||
@ -99,6 +100,12 @@ class MicrosoftEntraProvider(OutgoingSyncProvider, BackchannelProvider):
 | 
				
			|||||||
        help_text=_("Property mappings used for group creation/updating."),
 | 
					        help_text=_("Property mappings used for group creation/updating."),
 | 
				
			||||||
    )
 | 
					    )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def sync_actor(self) -> Actor:
 | 
				
			||||||
 | 
					        from authentik.enterprise.providers.microsoft_entra.tasks import microsoft_entra_sync
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return microsoft_entra_sync
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def client_for_model(
 | 
					    def client_for_model(
 | 
				
			||||||
        self,
 | 
					        self,
 | 
				
			||||||
        model: type[User | Group | MicrosoftEntraProviderUser | MicrosoftEntraProviderGroup],
 | 
					        model: type[User | Group | MicrosoftEntraProviderUser | MicrosoftEntraProviderGroup],
 | 
				
			||||||
 | 
				
			|||||||
@ -1,13 +0,0 @@
 | 
				
			|||||||
"""Microsoft Entra provider task Settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "providers_microsoft_entra_sync": {
 | 
					 | 
				
			||||||
        "task": "authentik.enterprise.providers.microsoft_entra.tasks.microsoft_entra_sync_all",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("microsoft_entra_sync_all"), hour="*/4"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -2,15 +2,13 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
 | 
					from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
 | 
				
			||||||
from authentik.enterprise.providers.microsoft_entra.tasks import (
 | 
					from authentik.enterprise.providers.microsoft_entra.tasks import (
 | 
				
			||||||
    microsoft_entra_sync,
 | 
					    microsoft_entra_sync_direct_dispatch,
 | 
				
			||||||
    microsoft_entra_sync_direct,
 | 
					    microsoft_entra_sync_m2m_dispatch,
 | 
				
			||||||
    microsoft_entra_sync_m2m,
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.lib.sync.outgoing.signals import register_signals
 | 
					from authentik.lib.sync.outgoing.signals import register_signals
 | 
				
			||||||
 | 
					
 | 
				
			||||||
register_signals(
 | 
					register_signals(
 | 
				
			||||||
    MicrosoftEntraProvider,
 | 
					    MicrosoftEntraProvider,
 | 
				
			||||||
    task_sync_single=microsoft_entra_sync,
 | 
					    task_sync_direct_dispatch=microsoft_entra_sync_direct_dispatch,
 | 
				
			||||||
    task_sync_direct=microsoft_entra_sync_direct,
 | 
					    task_sync_m2m_dispatch=microsoft_entra_sync_m2m_dispatch,
 | 
				
			||||||
    task_sync_m2m=microsoft_entra_sync_m2m,
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
				
			|||||||
@ -1,37 +1,46 @@
 | 
				
			|||||||
"""Microsoft Entra Provider tasks"""
 | 
					"""Microsoft Entra Provider tasks"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
 | 
					from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask
 | 
					 | 
				
			||||||
from authentik.lib.sync.outgoing.exceptions import TransientSyncException
 | 
					 | 
				
			||||||
from authentik.lib.sync.outgoing.tasks import SyncTasks
 | 
					from authentik.lib.sync.outgoing.tasks import SyncTasks
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
sync_tasks = SyncTasks(MicrosoftEntraProvider)
 | 
					sync_tasks = SyncTasks(MicrosoftEntraProvider)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					@actor(description=_("Sync Microsoft Entra provider objects."))
 | 
				
			||||||
def microsoft_entra_sync_objects(*args, **kwargs):
 | 
					def microsoft_entra_sync_objects(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_objects(*args, **kwargs)
 | 
					    return sync_tasks.sync_objects(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(description=_("Full sync for Microsoft Entra provider."))
 | 
				
			||||||
    base=SystemTask, bind=True, autoretry_for=(TransientSyncException,), retry_backoff=True
 | 
					def microsoft_entra_sync(provider_pk: int, *args, **kwargs):
 | 
				
			||||||
)
 | 
					 | 
				
			||||||
def microsoft_entra_sync(self, provider_pk: int, *args, **kwargs):
 | 
					 | 
				
			||||||
    """Run full sync for Microsoft Entra provider"""
 | 
					    """Run full sync for Microsoft Entra provider"""
 | 
				
			||||||
    return sync_tasks.sync_single(self, provider_pk, microsoft_entra_sync_objects)
 | 
					    return sync_tasks.sync(provider_pk, microsoft_entra_sync_objects)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Sync a direct object (user, group) for Microsoft Entra provider."))
 | 
				
			||||||
def microsoft_entra_sync_all():
 | 
					 | 
				
			||||||
    return sync_tasks.sync_all(microsoft_entra_sync)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					 | 
				
			||||||
def microsoft_entra_sync_direct(*args, **kwargs):
 | 
					def microsoft_entra_sync_direct(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_signal_direct(*args, **kwargs)
 | 
					    return sync_tasks.sync_signal_direct(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(autoretry_for=(TransientSyncException,), retry_backoff=True)
 | 
					@actor(
 | 
				
			||||||
 | 
					    description=_("Dispatch syncs for a direct object (user, group) for Microsoft Entra providers.")
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					def microsoft_entra_sync_direct_dispatch(*args, **kwargs):
 | 
				
			||||||
 | 
					    return sync_tasks.sync_signal_direct_dispatch(microsoft_entra_sync_direct, *args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					@actor(description=_("Sync a related object (memberships) for Microsoft Entra provider."))
 | 
				
			||||||
def microsoft_entra_sync_m2m(*args, **kwargs):
 | 
					def microsoft_entra_sync_m2m(*args, **kwargs):
 | 
				
			||||||
    return sync_tasks.sync_signal_m2m(*args, **kwargs)
 | 
					    return sync_tasks.sync_signal_m2m(*args, **kwargs)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					@actor(
 | 
				
			||||||
 | 
					    description=_(
 | 
				
			||||||
 | 
					        "Dispatch syncs for a related object (memberships) for Microsoft Entra providers."
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					def microsoft_entra_sync_m2m_dispatch(*args, **kwargs):
 | 
				
			||||||
 | 
					    return sync_tasks.sync_signal_m2m_dispatch(microsoft_entra_sync_m2m, *args, **kwargs)
 | 
				
			||||||
 | 
				
			|||||||
@ -252,9 +252,13 @@ class MicrosoftEntraGroupTests(TestCase):
 | 
				
			|||||||
            member_add.assert_called_once()
 | 
					            member_add.assert_called_once()
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
                member_add.call_args[0][0].odata_id,
 | 
					                member_add.call_args[0][0].odata_id,
 | 
				
			||||||
                f"https://graph.microsoft.com/v1.0/directoryObjects/{MicrosoftEntraProviderUser.objects.filter(
 | 
					                f"https://graph.microsoft.com/v1.0/directoryObjects/{
 | 
				
			||||||
 | 
					                    MicrosoftEntraProviderUser.objects.filter(
 | 
				
			||||||
                        provider=self.provider,
 | 
					                        provider=self.provider,
 | 
				
			||||||
                    ).first().microsoft_id}",
 | 
					                    )
 | 
				
			||||||
 | 
					                    .first()
 | 
				
			||||||
 | 
					                    .microsoft_id
 | 
				
			||||||
 | 
					                }",
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def test_group_create_member_remove(self):
 | 
					    def test_group_create_member_remove(self):
 | 
				
			||||||
@ -311,9 +315,13 @@ class MicrosoftEntraGroupTests(TestCase):
 | 
				
			|||||||
            member_add.assert_called_once()
 | 
					            member_add.assert_called_once()
 | 
				
			||||||
            self.assertEqual(
 | 
					            self.assertEqual(
 | 
				
			||||||
                member_add.call_args[0][0].odata_id,
 | 
					                member_add.call_args[0][0].odata_id,
 | 
				
			||||||
                f"https://graph.microsoft.com/v1.0/directoryObjects/{MicrosoftEntraProviderUser.objects.filter(
 | 
					                f"https://graph.microsoft.com/v1.0/directoryObjects/{
 | 
				
			||||||
 | 
					                    MicrosoftEntraProviderUser.objects.filter(
 | 
				
			||||||
                        provider=self.provider,
 | 
					                        provider=self.provider,
 | 
				
			||||||
                    ).first().microsoft_id}",
 | 
					                    )
 | 
				
			||||||
 | 
					                    .first()
 | 
				
			||||||
 | 
					                    .microsoft_id
 | 
				
			||||||
 | 
					                }",
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
            member_remove.assert_called_once()
 | 
					            member_remove.assert_called_once()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -413,7 +421,7 @@ class MicrosoftEntraGroupTests(TestCase):
 | 
				
			|||||||
                ),
 | 
					                ),
 | 
				
			||||||
            ) as group_list,
 | 
					            ) as group_list,
 | 
				
			||||||
        ):
 | 
					        ):
 | 
				
			||||||
            microsoft_entra_sync.delay(self.provider.pk).get()
 | 
					            microsoft_entra_sync.send(self.provider.pk).get_result()
 | 
				
			||||||
            self.assertTrue(
 | 
					            self.assertTrue(
 | 
				
			||||||
                MicrosoftEntraProviderGroup.objects.filter(
 | 
					                MicrosoftEntraProviderGroup.objects.filter(
 | 
				
			||||||
                    group=different_group, provider=self.provider
 | 
					                    group=different_group, provider=self.provider
 | 
				
			||||||
 | 
				
			|||||||
@ -397,7 +397,7 @@ class MicrosoftEntraUserTests(APITestCase):
 | 
				
			|||||||
                AsyncMock(return_value=GroupCollectionResponse(value=[])),
 | 
					                AsyncMock(return_value=GroupCollectionResponse(value=[])),
 | 
				
			||||||
            ),
 | 
					            ),
 | 
				
			||||||
        ):
 | 
					        ):
 | 
				
			||||||
            microsoft_entra_sync.delay(self.provider.pk).get()
 | 
					            microsoft_entra_sync.send(self.provider.pk).get_result()
 | 
				
			||||||
            self.assertTrue(
 | 
					            self.assertTrue(
 | 
				
			||||||
                MicrosoftEntraProviderUser.objects.filter(
 | 
					                MicrosoftEntraProviderUser.objects.filter(
 | 
				
			||||||
                    user=different_user, provider=self.provider
 | 
					                    user=different_user, provider=self.provider
 | 
				
			||||||
 | 
				
			|||||||
@ -17,6 +17,7 @@ from authentik.crypto.models import CertificateKeyPair
 | 
				
			|||||||
from authentik.lib.models import CreatedUpdatedModel
 | 
					from authentik.lib.models import CreatedUpdatedModel
 | 
				
			||||||
from authentik.lib.utils.time import timedelta_from_string, timedelta_string_validator
 | 
					from authentik.lib.utils.time import timedelta_from_string, timedelta_string_validator
 | 
				
			||||||
from authentik.providers.oauth2.models import JWTAlgorithms, OAuth2Provider
 | 
					from authentik.providers.oauth2.models import JWTAlgorithms, OAuth2Provider
 | 
				
			||||||
 | 
					from authentik.tasks.models import TasksModel
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class EventTypes(models.TextChoices):
 | 
					class EventTypes(models.TextChoices):
 | 
				
			||||||
@ -42,7 +43,7 @@ class SSFEventStatus(models.TextChoices):
 | 
				
			|||||||
    SENT = "sent"
 | 
					    SENT = "sent"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class SSFProvider(BackchannelProvider):
 | 
					class SSFProvider(TasksModel, BackchannelProvider):
 | 
				
			||||||
    """Shared Signals Framework provider to allow applications to
 | 
					    """Shared Signals Framework provider to allow applications to
 | 
				
			||||||
    receive user events from authentik."""
 | 
					    receive user events from authentik."""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -1,10 +1,8 @@
 | 
				
			|||||||
from hashlib import sha256
 | 
					from hashlib import sha256
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.contrib.auth.signals import user_logged_out
 | 
					 | 
				
			||||||
from django.db.models import Model
 | 
					from django.db.models import Model
 | 
				
			||||||
from django.db.models.signals import post_delete, post_save, pre_delete
 | 
					from django.db.models.signals import post_delete, post_save, pre_delete
 | 
				
			||||||
from django.dispatch import receiver
 | 
					from django.dispatch import receiver
 | 
				
			||||||
from django.http.request import HttpRequest
 | 
					 | 
				
			||||||
from guardian.shortcuts import assign_perm
 | 
					from guardian.shortcuts import assign_perm
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.core.models import (
 | 
					from authentik.core.models import (
 | 
				
			||||||
@ -20,7 +18,7 @@ from authentik.enterprise.providers.ssf.models import (
 | 
				
			|||||||
    EventTypes,
 | 
					    EventTypes,
 | 
				
			||||||
    SSFProvider,
 | 
					    SSFProvider,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.enterprise.providers.ssf.tasks import send_ssf_event
 | 
					from authentik.enterprise.providers.ssf.tasks import send_ssf_events
 | 
				
			||||||
from authentik.events.middleware import audit_ignore
 | 
					from authentik.events.middleware import audit_ignore
 | 
				
			||||||
from authentik.stages.authenticator.models import Device
 | 
					from authentik.stages.authenticator.models import Device
 | 
				
			||||||
from authentik.stages.authenticator_duo.models import DuoDevice
 | 
					from authentik.stages.authenticator_duo.models import DuoDevice
 | 
				
			||||||
@ -62,38 +60,13 @@ def ssf_providers_post_save(sender: type[Model], instance: SSFProvider, created:
 | 
				
			|||||||
            instance.save()
 | 
					            instance.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@receiver(user_logged_out)
 | 
					 | 
				
			||||||
def ssf_user_logged_out_session_revoked(sender, request: HttpRequest, user: User, **_):
 | 
					 | 
				
			||||||
    """Session revoked trigger (user logged out)"""
 | 
					 | 
				
			||||||
    if not request.session or not request.session.session_key or not user:
 | 
					 | 
				
			||||||
        return
 | 
					 | 
				
			||||||
    send_ssf_event(
 | 
					 | 
				
			||||||
        EventTypes.CAEP_SESSION_REVOKED,
 | 
					 | 
				
			||||||
        {
 | 
					 | 
				
			||||||
            "initiating_entity": "user",
 | 
					 | 
				
			||||||
        },
 | 
					 | 
				
			||||||
        sub_id={
 | 
					 | 
				
			||||||
            "format": "complex",
 | 
					 | 
				
			||||||
            "session": {
 | 
					 | 
				
			||||||
                "format": "opaque",
 | 
					 | 
				
			||||||
                "id": sha256(request.session.session_key.encode("ascii")).hexdigest(),
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
            "user": {
 | 
					 | 
				
			||||||
                "format": "email",
 | 
					 | 
				
			||||||
                "email": user.email,
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
        },
 | 
					 | 
				
			||||||
        request=request,
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@receiver(pre_delete, sender=AuthenticatedSession)
 | 
					@receiver(pre_delete, sender=AuthenticatedSession)
 | 
				
			||||||
def ssf_user_session_delete_session_revoked(sender, instance: AuthenticatedSession, **_):
 | 
					def ssf_user_session_delete_session_revoked(sender, instance: AuthenticatedSession, **_):
 | 
				
			||||||
    """Session revoked trigger (users' session has been deleted)
 | 
					    """Session revoked trigger (users' session has been deleted)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    As this signal is also triggered with a regular logout, we can't be sure
 | 
					    As this signal is also triggered with a regular logout, we can't be sure
 | 
				
			||||||
    if the session has been deleted by an admin or by the user themselves."""
 | 
					    if the session has been deleted by an admin or by the user themselves."""
 | 
				
			||||||
    send_ssf_event(
 | 
					    send_ssf_events(
 | 
				
			||||||
        EventTypes.CAEP_SESSION_REVOKED,
 | 
					        EventTypes.CAEP_SESSION_REVOKED,
 | 
				
			||||||
        {
 | 
					        {
 | 
				
			||||||
            "initiating_entity": "user",
 | 
					            "initiating_entity": "user",
 | 
				
			||||||
@ -115,7 +88,7 @@ def ssf_user_session_delete_session_revoked(sender, instance: AuthenticatedSessi
 | 
				
			|||||||
@receiver(password_changed)
 | 
					@receiver(password_changed)
 | 
				
			||||||
def ssf_password_changed_cred_change(sender, user: User, password: str | None, **_):
 | 
					def ssf_password_changed_cred_change(sender, user: User, password: str | None, **_):
 | 
				
			||||||
    """Credential change trigger (password changed)"""
 | 
					    """Credential change trigger (password changed)"""
 | 
				
			||||||
    send_ssf_event(
 | 
					    send_ssf_events(
 | 
				
			||||||
        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
					        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
				
			||||||
        {
 | 
					        {
 | 
				
			||||||
            "credential_type": "password",
 | 
					            "credential_type": "password",
 | 
				
			||||||
@ -153,7 +126,7 @@ def ssf_device_post_save(sender: type[Model], instance: Device, created: bool, *
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
 | 
					    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
 | 
				
			||||||
        data["fido2_aaguid"] = instance.aaguid
 | 
					        data["fido2_aaguid"] = instance.aaguid
 | 
				
			||||||
    send_ssf_event(
 | 
					    send_ssf_events(
 | 
				
			||||||
        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
					        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
				
			||||||
        data,
 | 
					        data,
 | 
				
			||||||
        sub_id={
 | 
					        sub_id={
 | 
				
			||||||
@ -180,7 +153,7 @@ def ssf_device_post_delete(sender: type[Model], instance: Device, **_):
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
 | 
					    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
 | 
				
			||||||
        data["fido2_aaguid"] = instance.aaguid
 | 
					        data["fido2_aaguid"] = instance.aaguid
 | 
				
			||||||
    send_ssf_event(
 | 
					    send_ssf_events(
 | 
				
			||||||
        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
					        EventTypes.CAEP_CREDENTIAL_CHANGE,
 | 
				
			||||||
        data,
 | 
					        data,
 | 
				
			||||||
        sub_id={
 | 
					        sub_id={
 | 
				
			||||||
 | 
				
			|||||||
@ -1,7 +1,11 @@
 | 
				
			|||||||
from celery import group
 | 
					from typing import Any
 | 
				
			||||||
 | 
					from uuid import UUID
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.http import HttpRequest
 | 
					from django.http import HttpRequest
 | 
				
			||||||
from django.utils.timezone import now
 | 
					from django.utils.timezone import now
 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
from requests.exceptions import RequestException
 | 
					from requests.exceptions import RequestException
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -13,19 +17,16 @@ from authentik.enterprise.providers.ssf.models import (
 | 
				
			|||||||
    Stream,
 | 
					    Stream,
 | 
				
			||||||
    StreamEvent,
 | 
					    StreamEvent,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.events.logs import LogEvent
 | 
					 | 
				
			||||||
from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.system_tasks import SystemTask
 | 
					 | 
				
			||||||
from authentik.lib.utils.http import get_http_session
 | 
					from authentik.lib.utils.http import get_http_session
 | 
				
			||||||
from authentik.lib.utils.time import timedelta_from_string
 | 
					from authentik.lib.utils.time import timedelta_from_string
 | 
				
			||||||
from authentik.policies.engine import PolicyEngine
 | 
					from authentik.policies.engine import PolicyEngine
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
 | 
					
 | 
				
			||||||
session = get_http_session()
 | 
					session = get_http_session()
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def send_ssf_event(
 | 
					def send_ssf_events(
 | 
				
			||||||
    event_type: EventTypes,
 | 
					    event_type: EventTypes,
 | 
				
			||||||
    data: dict,
 | 
					    data: dict,
 | 
				
			||||||
    stream_filter: dict | None = None,
 | 
					    stream_filter: dict | None = None,
 | 
				
			||||||
@ -33,7 +34,7 @@ def send_ssf_event(
 | 
				
			|||||||
    **extra_data,
 | 
					    **extra_data,
 | 
				
			||||||
):
 | 
					):
 | 
				
			||||||
    """Wrapper to send an SSF event to multiple streams"""
 | 
					    """Wrapper to send an SSF event to multiple streams"""
 | 
				
			||||||
    payload = []
 | 
					    events_data = {}
 | 
				
			||||||
    if not stream_filter:
 | 
					    if not stream_filter:
 | 
				
			||||||
        stream_filter = {}
 | 
					        stream_filter = {}
 | 
				
			||||||
    stream_filter["events_requested__contains"] = [event_type]
 | 
					    stream_filter["events_requested__contains"] = [event_type]
 | 
				
			||||||
@ -41,16 +42,22 @@ def send_ssf_event(
 | 
				
			|||||||
        extra_data.setdefault("txn", request.request_id)
 | 
					        extra_data.setdefault("txn", request.request_id)
 | 
				
			||||||
    for stream in Stream.objects.filter(**stream_filter):
 | 
					    for stream in Stream.objects.filter(**stream_filter):
 | 
				
			||||||
        event_data = stream.prepare_event_payload(event_type, data, **extra_data)
 | 
					        event_data = stream.prepare_event_payload(event_type, data, **extra_data)
 | 
				
			||||||
        payload.append((str(stream.uuid), event_data))
 | 
					        events_data[stream.uuid] = event_data
 | 
				
			||||||
    return _send_ssf_event.delay(payload)
 | 
					    ssf_events_dispatch.send(events_data)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def _check_app_access(stream_uuid: str, event_data: dict) -> bool:
 | 
					@actor(description=_("Dispatch SSF events."))
 | 
				
			||||||
 | 
					def ssf_events_dispatch(events_data: dict[str, dict[str, Any]]):
 | 
				
			||||||
 | 
					    for stream_uuid, event_data in events_data.items():
 | 
				
			||||||
 | 
					        stream = Stream.objects.filter(pk=stream_uuid).first()
 | 
				
			||||||
 | 
					        if not stream:
 | 
				
			||||||
 | 
					            continue
 | 
				
			||||||
 | 
					        send_ssf_event.send_with_options(args=(stream_uuid, event_data), rel_obj=stream.provider)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					def _check_app_access(stream: Stream, event_data: dict) -> bool:
 | 
				
			||||||
    """Check if event is related to user and if so, check
 | 
					    """Check if event is related to user and if so, check
 | 
				
			||||||
    if the user has access to the application"""
 | 
					    if the user has access to the application"""
 | 
				
			||||||
    stream = Stream.objects.filter(pk=stream_uuid).first()
 | 
					 | 
				
			||||||
    if not stream:
 | 
					 | 
				
			||||||
        return False
 | 
					 | 
				
			||||||
    # `event_data` is a dict version of a StreamEvent
 | 
					    # `event_data` is a dict version of a StreamEvent
 | 
				
			||||||
    sub_id = event_data.get("payload", {}).get("sub_id", {})
 | 
					    sub_id = event_data.get("payload", {}).get("sub_id", {})
 | 
				
			||||||
    email = sub_id.get("user", {}).get("email", None)
 | 
					    email = sub_id.get("user", {}).get("email", None)
 | 
				
			||||||
@ -65,42 +72,22 @@ def _check_app_access(stream_uuid: str, event_data: dict) -> bool:
 | 
				
			|||||||
    return engine.passing
 | 
					    return engine.passing
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Send an SSF event."))
 | 
				
			||||||
def _send_ssf_event(event_data: list[tuple[str, dict]]):
 | 
					def send_ssf_event(stream_uuid: UUID, event_data: dict[str, Any]):
 | 
				
			||||||
    tasks = []
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    for stream, data in event_data:
 | 
					 | 
				
			||||||
        if not _check_app_access(stream, data):
 | 
					 | 
				
			||||||
            continue
 | 
					 | 
				
			||||||
        event = StreamEvent.objects.create(**data)
 | 
					 | 
				
			||||||
        tasks.extend(send_single_ssf_event(stream, str(event.uuid)))
 | 
					 | 
				
			||||||
    main_task = group(*tasks)
 | 
					 | 
				
			||||||
    main_task()
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    stream = Stream.objects.filter(pk=stream_uuid).first()
 | 
				
			||||||
def send_single_ssf_event(stream_id: str, evt_id: str):
 | 
					 | 
				
			||||||
    stream = Stream.objects.filter(pk=stream_id).first()
 | 
					 | 
				
			||||||
    if not stream:
 | 
					    if not stream:
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
    event = StreamEvent.objects.filter(pk=evt_id).first()
 | 
					    if not _check_app_access(stream, event_data):
 | 
				
			||||||
    if not event:
 | 
					 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
 | 
					    event = StreamEvent.objects.create(**event_data)
 | 
				
			||||||
 | 
					    self.set_uid(event.pk)
 | 
				
			||||||
    if event.status == SSFEventStatus.SENT:
 | 
					    if event.status == SSFEventStatus.SENT:
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
    if stream.delivery_method == DeliveryMethods.RISC_PUSH:
 | 
					    if stream.delivery_method != DeliveryMethods.RISC_PUSH:
 | 
				
			||||||
        return [ssf_push_event.si(str(event.pk))]
 | 
					 | 
				
			||||||
    return []
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					 | 
				
			||||||
def ssf_push_event(self: SystemTask, event_id: str):
 | 
					 | 
				
			||||||
    self.save_on_success = False
 | 
					 | 
				
			||||||
    event = StreamEvent.objects.filter(pk=event_id).first()
 | 
					 | 
				
			||||||
    if not event:
 | 
					 | 
				
			||||||
        return
 | 
					 | 
				
			||||||
    self.set_uid(event_id)
 | 
					 | 
				
			||||||
    if event.status == SSFEventStatus.SENT:
 | 
					 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
        response = session.post(
 | 
					        response = session.post(
 | 
				
			||||||
            event.stream.endpoint_url,
 | 
					            event.stream.endpoint_url,
 | 
				
			||||||
@ -110,26 +97,17 @@ def ssf_push_event(self: SystemTask, event_id: str):
 | 
				
			|||||||
        response.raise_for_status()
 | 
					        response.raise_for_status()
 | 
				
			||||||
        event.status = SSFEventStatus.SENT
 | 
					        event.status = SSFEventStatus.SENT
 | 
				
			||||||
        event.save()
 | 
					        event.save()
 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
    except RequestException as exc:
 | 
					    except RequestException as exc:
 | 
				
			||||||
        LOGGER.warning("Failed to send SSF event", exc=exc)
 | 
					        LOGGER.warning("Failed to send SSF event", exc=exc)
 | 
				
			||||||
        self.set_status(TaskStatus.ERROR)
 | 
					 | 
				
			||||||
        attrs = {}
 | 
					        attrs = {}
 | 
				
			||||||
        if exc.response:
 | 
					        if exc.response:
 | 
				
			||||||
            attrs["response"] = {
 | 
					            attrs["response"] = {
 | 
				
			||||||
                "content": exc.response.text,
 | 
					                "content": exc.response.text,
 | 
				
			||||||
                "status": exc.response.status_code,
 | 
					                "status": exc.response.status_code,
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
        self.set_error(
 | 
					        self.warning(exc)
 | 
				
			||||||
            exc,
 | 
					        self.warning("Failed to send request", **attrs)
 | 
				
			||||||
            LogEvent(
 | 
					 | 
				
			||||||
                _("Failed to send request"),
 | 
					 | 
				
			||||||
                log_level="warning",
 | 
					 | 
				
			||||||
                logger=self.__name__,
 | 
					 | 
				
			||||||
                attributes=attrs,
 | 
					 | 
				
			||||||
            ),
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        # Re-up the expiry of the stream event
 | 
					        # Re-up the expiry of the stream event
 | 
				
			||||||
        event.expires = now() + timedelta_from_string(event.stream.provider.event_retention)
 | 
					        event.expires = now() + timedelta_from_string(event.stream.provider.event_retention)
 | 
				
			||||||
        event.status = SSFEventStatus.PENDING_FAILED
 | 
					        event.status = SSFEventStatus.PENDING_FAILED
 | 
				
			||||||
 | 
				
			|||||||
@ -13,7 +13,7 @@ from authentik.enterprise.providers.ssf.models import (
 | 
				
			|||||||
    SSFProvider,
 | 
					    SSFProvider,
 | 
				
			||||||
    Stream,
 | 
					    Stream,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.enterprise.providers.ssf.tasks import send_ssf_event
 | 
					from authentik.enterprise.providers.ssf.tasks import send_ssf_events
 | 
				
			||||||
from authentik.enterprise.providers.ssf.views.base import SSFView
 | 
					from authentik.enterprise.providers.ssf.views.base import SSFView
 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
@ -109,7 +109,7 @@ class StreamView(SSFView):
 | 
				
			|||||||
                "User does not have permission to create stream for this provider."
 | 
					                "User does not have permission to create stream for this provider."
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
        instance: Stream = stream.save(provider=self.provider)
 | 
					        instance: Stream = stream.save(provider=self.provider)
 | 
				
			||||||
        send_ssf_event(
 | 
					        send_ssf_events(
 | 
				
			||||||
            EventTypes.SET_VERIFICATION,
 | 
					            EventTypes.SET_VERIFICATION,
 | 
				
			||||||
            {
 | 
					            {
 | 
				
			||||||
                "state": None,
 | 
					                "state": None,
 | 
				
			||||||
 | 
				
			|||||||
@ -6,7 +6,7 @@ from djangoql.ast import Name
 | 
				
			|||||||
from djangoql.exceptions import DjangoQLError
 | 
					from djangoql.exceptions import DjangoQLError
 | 
				
			||||||
from djangoql.queryset import apply_search
 | 
					from djangoql.queryset import apply_search
 | 
				
			||||||
from djangoql.schema import DjangoQLSchema
 | 
					from djangoql.schema import DjangoQLSchema
 | 
				
			||||||
from rest_framework.filters import SearchFilter
 | 
					from rest_framework.filters import BaseFilterBackend, SearchFilter
 | 
				
			||||||
from rest_framework.request import Request
 | 
					from rest_framework.request import Request
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -39,19 +39,21 @@ class BaseSchema(DjangoQLSchema):
 | 
				
			|||||||
        return super().resolve_name(name)
 | 
					        return super().resolve_name(name)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class QLSearch(SearchFilter):
 | 
					class QLSearch(BaseFilterBackend):
 | 
				
			||||||
    """rest_framework search filter which uses DjangoQL"""
 | 
					    """rest_framework search filter which uses DjangoQL"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def __init__(self):
 | 
				
			||||||
 | 
					        super().__init__()
 | 
				
			||||||
 | 
					        self._fallback = SearchFilter()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @property
 | 
					    @property
 | 
				
			||||||
    def enabled(self):
 | 
					    def enabled(self):
 | 
				
			||||||
        return apps.get_app_config("authentik_enterprise").enabled()
 | 
					        return apps.get_app_config("authentik_enterprise").enabled()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def get_search_terms(self, request) -> str:
 | 
					    def get_search_terms(self, request: Request) -> str:
 | 
				
			||||||
        """
 | 
					        """Search terms are set by a ?search=... query parameter,
 | 
				
			||||||
        Search terms are set by a ?search=... query parameter,
 | 
					        and may be comma and/or whitespace delimited."""
 | 
				
			||||||
        and may be comma and/or whitespace delimited.
 | 
					        params = request.query_params.get("search", "")
 | 
				
			||||||
        """
 | 
					 | 
				
			||||||
        params = request.query_params.get(self.search_param, "")
 | 
					 | 
				
			||||||
        params = params.replace("\x00", "")  # strip null characters
 | 
					        params = params.replace("\x00", "")  # strip null characters
 | 
				
			||||||
        return params
 | 
					        return params
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -70,9 +72,9 @@ class QLSearch(SearchFilter):
 | 
				
			|||||||
        search_query = self.get_search_terms(request)
 | 
					        search_query = self.get_search_terms(request)
 | 
				
			||||||
        schema = self.get_schema(request, view)
 | 
					        schema = self.get_schema(request, view)
 | 
				
			||||||
        if len(search_query) == 0 or not self.enabled:
 | 
					        if len(search_query) == 0 or not self.enabled:
 | 
				
			||||||
            return super().filter_queryset(request, queryset, view)
 | 
					            return self._fallback.filter_queryset(request, queryset, view)
 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
            return apply_search(queryset, search_query, schema=schema)
 | 
					            return apply_search(queryset, search_query, schema=schema)
 | 
				
			||||||
        except DjangoQLError as exc:
 | 
					        except DjangoQLError as exc:
 | 
				
			||||||
            LOGGER.debug("Failed to parse search expression", exc=exc)
 | 
					            LOGGER.debug("Failed to parse search expression", exc=exc)
 | 
				
			||||||
            return super().filter_queryset(request, queryset, view)
 | 
					            return self._fallback.filter_queryset(request, queryset, view)
 | 
				
			||||||
 | 
				
			|||||||
@ -57,7 +57,7 @@ class QLTest(APITestCase):
 | 
				
			|||||||
        )
 | 
					        )
 | 
				
			||||||
        self.assertEqual(res.status_code, 200)
 | 
					        self.assertEqual(res.status_code, 200)
 | 
				
			||||||
        content = loads(res.content)
 | 
					        content = loads(res.content)
 | 
				
			||||||
        self.assertGreaterEqual(content["pagination"]["count"], 1)
 | 
					        self.assertEqual(content["pagination"]["count"], 1)
 | 
				
			||||||
        self.assertEqual(content["results"][0]["username"], self.user.username)
 | 
					        self.assertEqual(content["results"][0]["username"], self.user.username)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def test_search_json(self):
 | 
					    def test_search_json(self):
 | 
				
			||||||
 | 
				
			|||||||
@ -1,17 +1,5 @@
 | 
				
			|||||||
"""Enterprise additional settings"""
 | 
					"""Enterprise additional settings"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "enterprise_update_usage": {
 | 
					 | 
				
			||||||
        "task": "authentik.enterprise.tasks.enterprise_update_usage",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("enterprise_update_usage"), hour="*/2"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
TENANT_APPS = [
 | 
					TENANT_APPS = [
 | 
				
			||||||
    "authentik.enterprise.audit",
 | 
					    "authentik.enterprise.audit",
 | 
				
			||||||
    "authentik.enterprise.policies.unique_password",
 | 
					    "authentik.enterprise.policies.unique_password",
 | 
				
			||||||
 | 
				
			|||||||
@ -10,6 +10,7 @@ from django.utils.timezone import get_current_timezone
 | 
				
			|||||||
from authentik.enterprise.license import CACHE_KEY_ENTERPRISE_LICENSE
 | 
					from authentik.enterprise.license import CACHE_KEY_ENTERPRISE_LICENSE
 | 
				
			||||||
from authentik.enterprise.models import License
 | 
					from authentik.enterprise.models import License
 | 
				
			||||||
from authentik.enterprise.tasks import enterprise_update_usage
 | 
					from authentik.enterprise.tasks import enterprise_update_usage
 | 
				
			||||||
 | 
					from authentik.tasks.schedules.models import Schedule
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@receiver(pre_save, sender=License)
 | 
					@receiver(pre_save, sender=License)
 | 
				
			||||||
@ -26,7 +27,7 @@ def pre_save_license(sender: type[License], instance: License, **_):
 | 
				
			|||||||
def post_save_license(sender: type[License], instance: License, **_):
 | 
					def post_save_license(sender: type[License], instance: License, **_):
 | 
				
			||||||
    """Trigger license usage calculation when license is saved"""
 | 
					    """Trigger license usage calculation when license is saved"""
 | 
				
			||||||
    cache.delete(CACHE_KEY_ENTERPRISE_LICENSE)
 | 
					    cache.delete(CACHE_KEY_ENTERPRISE_LICENSE)
 | 
				
			||||||
    enterprise_update_usage.delay()
 | 
					    Schedule.dispatch_by_actor(enterprise_update_usage)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@receiver(post_delete, sender=License)
 | 
					@receiver(post_delete, sender=License)
 | 
				
			||||||
 | 
				
			|||||||
@ -97,6 +97,7 @@ class SourceStageFinal(StageView):
 | 
				
			|||||||
        token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
 | 
					        token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
 | 
				
			||||||
        self.logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
 | 
					        self.logger.info("Replacing source flow with overridden flow", flow=token.flow.slug)
 | 
				
			||||||
        plan = token.plan
 | 
					        plan = token.plan
 | 
				
			||||||
 | 
					        plan.context.update(self.executor.plan.context)
 | 
				
			||||||
        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
 | 
					        plan.context[PLAN_CONTEXT_IS_RESTORED] = token
 | 
				
			||||||
        response = plan.to_redirect(self.request, token.flow)
 | 
					        response = plan.to_redirect(self.request, token.flow)
 | 
				
			||||||
        token.delete()
 | 
					        token.delete()
 | 
				
			||||||
 | 
				
			|||||||
@ -90,14 +90,17 @@ class TestSourceStage(FlowTestCase):
 | 
				
			|||||||
        plan: FlowPlan = session[SESSION_KEY_PLAN]
 | 
					        plan: FlowPlan = session[SESSION_KEY_PLAN]
 | 
				
			||||||
        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
 | 
					        plan.insert_stage(in_memory_stage(SourceStageFinal), index=0)
 | 
				
			||||||
        plan.context[PLAN_CONTEXT_IS_RESTORED] = flow_token
 | 
					        plan.context[PLAN_CONTEXT_IS_RESTORED] = flow_token
 | 
				
			||||||
 | 
					        plan.context["foo"] = "bar"
 | 
				
			||||||
        session[SESSION_KEY_PLAN] = plan
 | 
					        session[SESSION_KEY_PLAN] = plan
 | 
				
			||||||
        session.save()
 | 
					        session.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        # Pretend we've just returned from the source
 | 
					        # Pretend we've just returned from the source
 | 
				
			||||||
        response = self.client.get(
 | 
					        with self.assertFlowFinishes() as ff:
 | 
				
			||||||
            reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), follow=True
 | 
					            response = self.client.get(
 | 
				
			||||||
        )
 | 
					                reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug}), follow=True
 | 
				
			||||||
        self.assertEqual(response.status_code, 200)
 | 
					            )
 | 
				
			||||||
        self.assertStageRedirects(
 | 
					            self.assertEqual(response.status_code, 200)
 | 
				
			||||||
            response, reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
 | 
					            self.assertStageRedirects(
 | 
				
			||||||
        )
 | 
					                response, reverse("authentik_core:if-flow", kwargs={"flow_slug": flow.slug})
 | 
				
			||||||
 | 
					            )
 | 
				
			||||||
 | 
					        self.assertEqual(ff().context["foo"], "bar")
 | 
				
			||||||
 | 
				
			|||||||
@ -1,14 +1,11 @@
 | 
				
			|||||||
"""Enterprise tasks"""
 | 
					"""Enterprise tasks"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.enterprise.license import LicenseKey
 | 
					from authentik.enterprise.license import LicenseKey
 | 
				
			||||||
from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, prefill_task
 | 
					 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Update enterprise license status."))
 | 
				
			||||||
@prefill_task
 | 
					def enterprise_update_usage():
 | 
				
			||||||
def enterprise_update_usage(self: SystemTask):
 | 
					 | 
				
			||||||
    """Update enterprise license status"""
 | 
					 | 
				
			||||||
    LicenseKey.get_total().record_usage()
 | 
					    LicenseKey.get_total().record_usage()
 | 
				
			||||||
    self.set_status(TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -1,104 +0,0 @@
 | 
				
			|||||||
"""Tasks API"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from importlib import import_module
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.contrib import messages
 | 
					 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					 | 
				
			||||||
from drf_spectacular.types import OpenApiTypes
 | 
					 | 
				
			||||||
from drf_spectacular.utils import OpenApiResponse, extend_schema
 | 
					 | 
				
			||||||
from rest_framework.decorators import action
 | 
					 | 
				
			||||||
from rest_framework.fields import (
 | 
					 | 
				
			||||||
    CharField,
 | 
					 | 
				
			||||||
    ChoiceField,
 | 
					 | 
				
			||||||
    DateTimeField,
 | 
					 | 
				
			||||||
    FloatField,
 | 
					 | 
				
			||||||
    SerializerMethodField,
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
from rest_framework.request import Request
 | 
					 | 
				
			||||||
from rest_framework.response import Response
 | 
					 | 
				
			||||||
from rest_framework.viewsets import ReadOnlyModelViewSet
 | 
					 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.core.api.utils import ModelSerializer
 | 
					 | 
				
			||||||
from authentik.events.logs import LogEventSerializer
 | 
					 | 
				
			||||||
from authentik.events.models import SystemTask, TaskStatus
 | 
					 | 
				
			||||||
from authentik.rbac.decorators import permission_required
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
LOGGER = get_logger()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class SystemTaskSerializer(ModelSerializer):
 | 
					 | 
				
			||||||
    """Serialize TaskInfo and TaskResult"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    name = CharField()
 | 
					 | 
				
			||||||
    full_name = SerializerMethodField()
 | 
					 | 
				
			||||||
    uid = CharField(required=False)
 | 
					 | 
				
			||||||
    description = CharField()
 | 
					 | 
				
			||||||
    start_timestamp = DateTimeField(read_only=True)
 | 
					 | 
				
			||||||
    finish_timestamp = DateTimeField(read_only=True)
 | 
					 | 
				
			||||||
    duration = FloatField(read_only=True)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    status = ChoiceField(choices=[(x.value, x.name) for x in TaskStatus])
 | 
					 | 
				
			||||||
    messages = LogEventSerializer(many=True)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def get_full_name(self, instance: SystemTask) -> str:
 | 
					 | 
				
			||||||
        """Get full name with UID"""
 | 
					 | 
				
			||||||
        if instance.uid:
 | 
					 | 
				
			||||||
            return f"{instance.name}:{instance.uid}"
 | 
					 | 
				
			||||||
        return instance.name
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    class Meta:
 | 
					 | 
				
			||||||
        model = SystemTask
 | 
					 | 
				
			||||||
        fields = [
 | 
					 | 
				
			||||||
            "uuid",
 | 
					 | 
				
			||||||
            "name",
 | 
					 | 
				
			||||||
            "full_name",
 | 
					 | 
				
			||||||
            "uid",
 | 
					 | 
				
			||||||
            "description",
 | 
					 | 
				
			||||||
            "start_timestamp",
 | 
					 | 
				
			||||||
            "finish_timestamp",
 | 
					 | 
				
			||||||
            "duration",
 | 
					 | 
				
			||||||
            "status",
 | 
					 | 
				
			||||||
            "messages",
 | 
					 | 
				
			||||||
            "expires",
 | 
					 | 
				
			||||||
            "expiring",
 | 
					 | 
				
			||||||
        ]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class SystemTaskViewSet(ReadOnlyModelViewSet):
 | 
					 | 
				
			||||||
    """Read-only view set that returns all background tasks"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    queryset = SystemTask.objects.all()
 | 
					 | 
				
			||||||
    serializer_class = SystemTaskSerializer
 | 
					 | 
				
			||||||
    filterset_fields = ["name", "uid", "status"]
 | 
					 | 
				
			||||||
    ordering = ["name", "uid", "status"]
 | 
					 | 
				
			||||||
    search_fields = ["name", "description", "uid", "status"]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    @permission_required(None, ["authentik_events.run_task"])
 | 
					 | 
				
			||||||
    @extend_schema(
 | 
					 | 
				
			||||||
        request=OpenApiTypes.NONE,
 | 
					 | 
				
			||||||
        responses={
 | 
					 | 
				
			||||||
            204: OpenApiResponse(description="Task retried successfully"),
 | 
					 | 
				
			||||||
            404: OpenApiResponse(description="Task not found"),
 | 
					 | 
				
			||||||
            500: OpenApiResponse(description="Failed to retry task"),
 | 
					 | 
				
			||||||
        },
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
    @action(detail=True, methods=["POST"], permission_classes=[])
 | 
					 | 
				
			||||||
    def run(self, request: Request, pk=None) -> Response:
 | 
					 | 
				
			||||||
        """Run task"""
 | 
					 | 
				
			||||||
        task: SystemTask = self.get_object()
 | 
					 | 
				
			||||||
        try:
 | 
					 | 
				
			||||||
            task_module = import_module(task.task_call_module)
 | 
					 | 
				
			||||||
            task_func = getattr(task_module, task.task_call_func)
 | 
					 | 
				
			||||||
            LOGGER.info("Running task", task=task_func)
 | 
					 | 
				
			||||||
            task_func.delay(*task.task_call_args, **task.task_call_kwargs)
 | 
					 | 
				
			||||||
            messages.success(
 | 
					 | 
				
			||||||
                self.request,
 | 
					 | 
				
			||||||
                _("Successfully started task {name}.".format_map({"name": task.name})),
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
            return Response(status=204)
 | 
					 | 
				
			||||||
        except (ImportError, AttributeError) as exc:  # pragma: no cover
 | 
					 | 
				
			||||||
            LOGGER.warning("Failed to run task, remove state", task=task.name, exc=exc)
 | 
					 | 
				
			||||||
            # if we get an import error, the module path has probably changed
 | 
					 | 
				
			||||||
            task.delete()
 | 
					 | 
				
			||||||
            return Response(status=500)
 | 
					 | 
				
			||||||
@ -1,12 +1,11 @@
 | 
				
			|||||||
"""authentik events app"""
 | 
					"""authentik events app"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
from prometheus_client import Gauge, Histogram
 | 
					from prometheus_client import Gauge, Histogram
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.blueprints.apps import ManagedAppConfig
 | 
					from authentik.blueprints.apps import ManagedAppConfig
 | 
				
			||||||
from authentik.lib.config import CONFIG, ENV_PREFIX
 | 
					from authentik.lib.config import CONFIG, ENV_PREFIX
 | 
				
			||||||
from authentik.lib.utils.reflection import path_to_class
 | 
					from authentik.lib.utils.time import fqdn_rand
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.schedules.lib import ScheduleSpec
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# TODO: Deprecated metric - remove in 2024.2 or later
 | 
					# TODO: Deprecated metric - remove in 2024.2 or later
 | 
				
			||||||
GAUGE_TASKS = Gauge(
 | 
					GAUGE_TASKS = Gauge(
 | 
				
			||||||
@ -35,6 +34,17 @@ class AuthentikEventsConfig(ManagedAppConfig):
 | 
				
			|||||||
    verbose_name = "authentik Events"
 | 
					    verbose_name = "authentik Events"
 | 
				
			||||||
    default = True
 | 
					    default = True
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @property
 | 
				
			||||||
 | 
					    def tenant_schedule_specs(self) -> list[ScheduleSpec]:
 | 
				
			||||||
 | 
					        from authentik.events.tasks import notification_cleanup
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        return [
 | 
				
			||||||
 | 
					            ScheduleSpec(
 | 
				
			||||||
 | 
					                actor=notification_cleanup,
 | 
				
			||||||
 | 
					                crontab=f"{fqdn_rand('notification_cleanup')} */8 * * *",
 | 
				
			||||||
 | 
					            ),
 | 
				
			||||||
 | 
					        ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @ManagedAppConfig.reconcile_global
 | 
					    @ManagedAppConfig.reconcile_global
 | 
				
			||||||
    def check_deprecations(self):
 | 
					    def check_deprecations(self):
 | 
				
			||||||
        """Check for config deprecations"""
 | 
					        """Check for config deprecations"""
 | 
				
			||||||
@ -56,41 +66,3 @@ class AuthentikEventsConfig(ManagedAppConfig):
 | 
				
			|||||||
                replacement_env=replace_env,
 | 
					                replacement_env=replace_env,
 | 
				
			||||||
                message=msg,
 | 
					                message=msg,
 | 
				
			||||||
            ).save()
 | 
					            ).save()
 | 
				
			||||||
 | 
					 | 
				
			||||||
    @ManagedAppConfig.reconcile_tenant
 | 
					 | 
				
			||||||
    def prefill_tasks(self):
 | 
					 | 
				
			||||||
        """Prefill tasks"""
 | 
					 | 
				
			||||||
        from authentik.events.models import SystemTask
 | 
					 | 
				
			||||||
        from authentik.events.system_tasks import _prefill_tasks
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        for task in _prefill_tasks:
 | 
					 | 
				
			||||||
            if SystemTask.objects.filter(name=task.name).exists():
 | 
					 | 
				
			||||||
                continue
 | 
					 | 
				
			||||||
            task.save()
 | 
					 | 
				
			||||||
            self.logger.debug("prefilled task", task_name=task.name)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    @ManagedAppConfig.reconcile_tenant
 | 
					 | 
				
			||||||
    def run_scheduled_tasks(self):
 | 
					 | 
				
			||||||
        """Run schedule tasks which are behind schedule (only applies
 | 
					 | 
				
			||||||
        to tasks of which we keep metrics)"""
 | 
					 | 
				
			||||||
        from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
        from authentik.events.system_tasks import SystemTask as CelerySystemTask
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        for task in CELERY_APP.conf["beat_schedule"].values():
 | 
					 | 
				
			||||||
            schedule = task["schedule"]
 | 
					 | 
				
			||||||
            if not isinstance(schedule, crontab):
 | 
					 | 
				
			||||||
                continue
 | 
					 | 
				
			||||||
            task_class: CelerySystemTask = path_to_class(task["task"])
 | 
					 | 
				
			||||||
            if not isinstance(task_class, CelerySystemTask):
 | 
					 | 
				
			||||||
                continue
 | 
					 | 
				
			||||||
            db_task = task_class.db()
 | 
					 | 
				
			||||||
            if not db_task:
 | 
					 | 
				
			||||||
                continue
 | 
					 | 
				
			||||||
            due, _ = schedule.is_due(db_task.finish_timestamp)
 | 
					 | 
				
			||||||
            if due or db_task.status == TaskStatus.UNKNOWN:
 | 
					 | 
				
			||||||
                self.logger.debug("Running past-due scheduled task", task=task["task"])
 | 
					 | 
				
			||||||
                task_class.apply_async(
 | 
					 | 
				
			||||||
                    args=task.get("args", None),
 | 
					 | 
				
			||||||
                    kwargs=task.get("kwargs", None),
 | 
					 | 
				
			||||||
                    **task.get("options", {}),
 | 
					 | 
				
			||||||
                )
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -15,13 +15,13 @@ class MMDBContextProcessor(EventContextProcessor):
 | 
				
			|||||||
        self.reader: Reader | None = None
 | 
					        self.reader: Reader | None = None
 | 
				
			||||||
        self._last_mtime: float = 0.0
 | 
					        self._last_mtime: float = 0.0
 | 
				
			||||||
        self.logger = get_logger()
 | 
					        self.logger = get_logger()
 | 
				
			||||||
        self.open()
 | 
					        self.load()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def path(self) -> str | None:
 | 
					    def path(self) -> str | None:
 | 
				
			||||||
        """Get the path to the MMDB file to load"""
 | 
					        """Get the path to the MMDB file to load"""
 | 
				
			||||||
        raise NotImplementedError
 | 
					        raise NotImplementedError
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def open(self):
 | 
					    def load(self):
 | 
				
			||||||
        """Get GeoIP Reader, if configured, otherwise none"""
 | 
					        """Get GeoIP Reader, if configured, otherwise none"""
 | 
				
			||||||
        path = self.path()
 | 
					        path = self.path()
 | 
				
			||||||
        if path == "" or not path:
 | 
					        if path == "" or not path:
 | 
				
			||||||
@ -44,7 +44,7 @@ class MMDBContextProcessor(EventContextProcessor):
 | 
				
			|||||||
            diff = self._last_mtime < mtime
 | 
					            diff = self._last_mtime < mtime
 | 
				
			||||||
            if diff > 0:
 | 
					            if diff > 0:
 | 
				
			||||||
                self.logger.info("Found new MMDB Database, reopening", diff=diff, path=path)
 | 
					                self.logger.info("Found new MMDB Database, reopening", diff=diff, path=path)
 | 
				
			||||||
                self.open()
 | 
					                self.load()
 | 
				
			||||||
        except OSError as exc:
 | 
					        except OSError as exc:
 | 
				
			||||||
            self.logger.warning("Failed to check MMDB age", exc=exc)
 | 
					            self.logger.warning("Failed to check MMDB age", exc=exc)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -19,7 +19,7 @@ from authentik.blueprints.v1.importer import excluded_models
 | 
				
			|||||||
from authentik.core.models import Group, User
 | 
					from authentik.core.models import Group, User
 | 
				
			||||||
from authentik.events.models import Event, EventAction, Notification
 | 
					from authentik.events.models import Event, EventAction, Notification
 | 
				
			||||||
from authentik.events.utils import model_to_dict
 | 
					from authentik.events.utils import model_to_dict
 | 
				
			||||||
from authentik.lib.sentry import before_send
 | 
					from authentik.lib.sentry import should_ignore_exception
 | 
				
			||||||
from authentik.lib.utils.errors import exception_to_string
 | 
					from authentik.lib.utils.errors import exception_to_string
 | 
				
			||||||
from authentik.stages.authenticator_static.models import StaticToken
 | 
					from authentik.stages.authenticator_static.models import StaticToken
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -173,7 +173,7 @@ class AuditMiddleware:
 | 
				
			|||||||
                message=exception_to_string(exception),
 | 
					                message=exception_to_string(exception),
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
            thread.run()
 | 
					            thread.run()
 | 
				
			||||||
        elif before_send({}, {"exc_info": (None, exception, None)}) is not None:
 | 
					        elif not should_ignore_exception(exception):
 | 
				
			||||||
            thread = EventNewThread(
 | 
					            thread = EventNewThread(
 | 
				
			||||||
                EventAction.SYSTEM_EXCEPTION,
 | 
					                EventAction.SYSTEM_EXCEPTION,
 | 
				
			||||||
                request,
 | 
					                request,
 | 
				
			||||||
 | 
				
			|||||||
							
								
								
									
										22
									
								
								authentik/events/migrations/0011_alter_systemtask_options.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								authentik/events/migrations/0011_alter_systemtask_options.py
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,22 @@
 | 
				
			|||||||
 | 
					# Generated by Django 5.1.11 on 2025-06-24 15:36
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from django.db import migrations
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					class Migration(migrations.Migration):
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    dependencies = [
 | 
				
			||||||
 | 
					        ("authentik_events", "0010_rename_group_notificationrule_destination_group_and_more"),
 | 
				
			||||||
 | 
					    ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    operations = [
 | 
				
			||||||
 | 
					        migrations.AlterModelOptions(
 | 
				
			||||||
 | 
					            name="systemtask",
 | 
				
			||||||
 | 
					            options={
 | 
				
			||||||
 | 
					                "default_permissions": (),
 | 
				
			||||||
 | 
					                "permissions": (),
 | 
				
			||||||
 | 
					                "verbose_name": "System Task",
 | 
				
			||||||
 | 
					                "verbose_name_plural": "System Tasks",
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
 | 
					        ),
 | 
				
			||||||
 | 
					    ]
 | 
				
			||||||
@ -5,12 +5,11 @@ from datetime import timedelta
 | 
				
			|||||||
from difflib import get_close_matches
 | 
					from difflib import get_close_matches
 | 
				
			||||||
from functools import lru_cache
 | 
					from functools import lru_cache
 | 
				
			||||||
from inspect import currentframe
 | 
					from inspect import currentframe
 | 
				
			||||||
from smtplib import SMTPException
 | 
					 | 
				
			||||||
from typing import Any
 | 
					from typing import Any
 | 
				
			||||||
from uuid import uuid4
 | 
					from uuid import uuid4
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.apps import apps
 | 
					from django.apps import apps
 | 
				
			||||||
from django.db import connection, models
 | 
					from django.db import models
 | 
				
			||||||
from django.http import HttpRequest
 | 
					from django.http import HttpRequest
 | 
				
			||||||
from django.http.request import QueryDict
 | 
					from django.http.request import QueryDict
 | 
				
			||||||
from django.utils.timezone import now
 | 
					from django.utils.timezone import now
 | 
				
			||||||
@ -27,7 +26,6 @@ from authentik.core.middleware import (
 | 
				
			|||||||
    SESSION_KEY_IMPERSONATE_USER,
 | 
					    SESSION_KEY_IMPERSONATE_USER,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.core.models import ExpiringModel, Group, PropertyMapping, User
 | 
					from authentik.core.models import ExpiringModel, Group, PropertyMapping, User
 | 
				
			||||||
from authentik.events.apps import GAUGE_TASKS, SYSTEM_TASK_STATUS, SYSTEM_TASK_TIME
 | 
					 | 
				
			||||||
from authentik.events.context_processors.base import get_context_processors
 | 
					from authentik.events.context_processors.base import get_context_processors
 | 
				
			||||||
from authentik.events.utils import (
 | 
					from authentik.events.utils import (
 | 
				
			||||||
    cleanse_dict,
 | 
					    cleanse_dict,
 | 
				
			||||||
@ -43,6 +41,7 @@ from authentik.lib.utils.time import timedelta_from_string
 | 
				
			|||||||
from authentik.policies.models import PolicyBindingModel
 | 
					from authentik.policies.models import PolicyBindingModel
 | 
				
			||||||
from authentik.root.middleware import ClientIPMiddleware
 | 
					from authentik.root.middleware import ClientIPMiddleware
 | 
				
			||||||
from authentik.stages.email.utils import TemplateEmailMessage
 | 
					from authentik.stages.email.utils import TemplateEmailMessage
 | 
				
			||||||
 | 
					from authentik.tasks.models import TasksModel
 | 
				
			||||||
from authentik.tenants.models import Tenant
 | 
					from authentik.tenants.models import Tenant
 | 
				
			||||||
from authentik.tenants.utils import get_current_tenant
 | 
					from authentik.tenants.utils import get_current_tenant
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -193,17 +192,32 @@ class Event(SerializerModel, ExpiringModel):
 | 
				
			|||||||
            brand: Brand = request.brand
 | 
					            brand: Brand = request.brand
 | 
				
			||||||
            self.brand = sanitize_dict(model_to_dict(brand))
 | 
					            self.brand = sanitize_dict(model_to_dict(brand))
 | 
				
			||||||
        if hasattr(request, "user"):
 | 
					        if hasattr(request, "user"):
 | 
				
			||||||
            original_user = None
 | 
					            self.user = get_user(request.user)
 | 
				
			||||||
            if hasattr(request, "session"):
 | 
					 | 
				
			||||||
                original_user = request.session.get(SESSION_KEY_IMPERSONATE_ORIGINAL_USER, None)
 | 
					 | 
				
			||||||
            self.user = get_user(request.user, original_user)
 | 
					 | 
				
			||||||
        if user:
 | 
					        if user:
 | 
				
			||||||
            self.user = get_user(user)
 | 
					            self.user = get_user(user)
 | 
				
			||||||
        # Check if we're currently impersonating, and add that user
 | 
					 | 
				
			||||||
        if hasattr(request, "session"):
 | 
					        if hasattr(request, "session"):
 | 
				
			||||||
 | 
					            from authentik.flows.views.executor import SESSION_KEY_PLAN
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            # Check if we're currently impersonating, and add that user
 | 
				
			||||||
            if SESSION_KEY_IMPERSONATE_ORIGINAL_USER in request.session:
 | 
					            if SESSION_KEY_IMPERSONATE_ORIGINAL_USER in request.session:
 | 
				
			||||||
                self.user = get_user(request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER])
 | 
					                self.user = get_user(request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER])
 | 
				
			||||||
                self.user["on_behalf_of"] = get_user(request.session[SESSION_KEY_IMPERSONATE_USER])
 | 
					                self.user["on_behalf_of"] = get_user(request.session[SESSION_KEY_IMPERSONATE_USER])
 | 
				
			||||||
 | 
					            # Special case for events that happen during a flow, the user might not be authenticated
 | 
				
			||||||
 | 
					            # yet but is a pending user instead
 | 
				
			||||||
 | 
					            if SESSION_KEY_PLAN in request.session:
 | 
				
			||||||
 | 
					                from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                plan: FlowPlan = request.session[SESSION_KEY_PLAN]
 | 
				
			||||||
 | 
					                pending_user = plan.context.get(PLAN_CONTEXT_PENDING_USER, None)
 | 
				
			||||||
 | 
					                # Only save `authenticated_as` if there's a different pending user in the flow
 | 
				
			||||||
 | 
					                # than the user that is authenticated
 | 
				
			||||||
 | 
					                if pending_user and (
 | 
				
			||||||
 | 
					                    (pending_user.pk and pending_user.pk != self.user.get("pk"))
 | 
				
			||||||
 | 
					                    or (not pending_user.pk)
 | 
				
			||||||
 | 
					                ):
 | 
				
			||||||
 | 
					                    orig_user = self.user.copy()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                    self.user = {"authenticated_as": orig_user, **get_user(pending_user)}
 | 
				
			||||||
        # User 255.255.255.255 as fallback if IP cannot be determined
 | 
					        # User 255.255.255.255 as fallback if IP cannot be determined
 | 
				
			||||||
        self.client_ip = ClientIPMiddleware.get_client_ip(request)
 | 
					        self.client_ip = ClientIPMiddleware.get_client_ip(request)
 | 
				
			||||||
        # Enrich event data
 | 
					        # Enrich event data
 | 
				
			||||||
@ -252,7 +266,8 @@ class Event(SerializerModel, ExpiringModel):
 | 
				
			|||||||
            models.Index(fields=["created"]),
 | 
					            models.Index(fields=["created"]),
 | 
				
			||||||
            models.Index(fields=["client_ip"]),
 | 
					            models.Index(fields=["client_ip"]),
 | 
				
			||||||
            models.Index(
 | 
					            models.Index(
 | 
				
			||||||
                models.F("context__authorized_application"), name="authentik_e_ctx_app__idx"
 | 
					                models.F("context__authorized_application"),
 | 
				
			||||||
 | 
					                name="authentik_e_ctx_app__idx",
 | 
				
			||||||
            ),
 | 
					            ),
 | 
				
			||||||
        ]
 | 
					        ]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -266,7 +281,7 @@ class TransportMode(models.TextChoices):
 | 
				
			|||||||
    EMAIL = "email", _("Email")
 | 
					    EMAIL = "email", _("Email")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class NotificationTransport(SerializerModel):
 | 
					class NotificationTransport(TasksModel, SerializerModel):
 | 
				
			||||||
    """Action which is executed when a Rule matches"""
 | 
					    """Action which is executed when a Rule matches"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 | 
					    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 | 
				
			||||||
@ -431,6 +446,8 @@ 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"""
 | 
				
			||||||
 | 
					        from authentik.stages.email.tasks import send_mail
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        if notification.user.email.strip() == "":
 | 
					        if notification.user.email.strip() == "":
 | 
				
			||||||
            LOGGER.info(
 | 
					            LOGGER.info(
 | 
				
			||||||
                "Discarding notification as user has no email address",
 | 
					                "Discarding notification as user has no email address",
 | 
				
			||||||
@ -472,17 +489,14 @@ class NotificationTransport(SerializerModel):
 | 
				
			|||||||
            template_name="email/event_notification.html",
 | 
					            template_name="email/event_notification.html",
 | 
				
			||||||
            template_context=context,
 | 
					            template_context=context,
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
        # Email is sent directly here, as the call to send() should have been from a task.
 | 
					        send_mail.send_with_options(args=(mail.__dict__,), rel_obj=self)
 | 
				
			||||||
        try:
 | 
					        return []
 | 
				
			||||||
            from authentik.stages.email.tasks import send_mail
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
            return send_mail(mail.__dict__)
 | 
					 | 
				
			||||||
        except (SMTPException, ConnectionError, OSError) as exc:
 | 
					 | 
				
			||||||
            raise NotificationTransportError(exc) from exc
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @property
 | 
					    @property
 | 
				
			||||||
    def serializer(self) -> type[Serializer]:
 | 
					    def serializer(self) -> type[Serializer]:
 | 
				
			||||||
        from authentik.events.api.notification_transports import NotificationTransportSerializer
 | 
					        from authentik.events.api.notification_transports import (
 | 
				
			||||||
 | 
					            NotificationTransportSerializer,
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return NotificationTransportSerializer
 | 
					        return NotificationTransportSerializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -532,7 +546,7 @@ class Notification(SerializerModel):
 | 
				
			|||||||
        verbose_name_plural = _("Notifications")
 | 
					        verbose_name_plural = _("Notifications")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class NotificationRule(SerializerModel, PolicyBindingModel):
 | 
					class NotificationRule(TasksModel, SerializerModel, PolicyBindingModel):
 | 
				
			||||||
    """Decide when to create a Notification based on policies attached to this object."""
 | 
					    """Decide when to create a Notification based on policies attached to this object."""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    name = models.TextField(unique=True)
 | 
					    name = models.TextField(unique=True)
 | 
				
			||||||
@ -596,7 +610,9 @@ class NotificationWebhookMapping(PropertyMapping):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    @property
 | 
					    @property
 | 
				
			||||||
    def serializer(self) -> type[type[Serializer]]:
 | 
					    def serializer(self) -> type[type[Serializer]]:
 | 
				
			||||||
        from authentik.events.api.notification_mappings import NotificationWebhookMappingSerializer
 | 
					        from authentik.events.api.notification_mappings import (
 | 
				
			||||||
 | 
					            NotificationWebhookMappingSerializer,
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        return NotificationWebhookMappingSerializer
 | 
					        return NotificationWebhookMappingSerializer
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -609,7 +625,7 @@ class NotificationWebhookMapping(PropertyMapping):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class TaskStatus(models.TextChoices):
 | 
					class TaskStatus(models.TextChoices):
 | 
				
			||||||
    """Possible states of tasks"""
 | 
					    """DEPRECATED do not use"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    UNKNOWN = "unknown"
 | 
					    UNKNOWN = "unknown"
 | 
				
			||||||
    SUCCESSFUL = "successful"
 | 
					    SUCCESSFUL = "successful"
 | 
				
			||||||
@ -617,8 +633,8 @@ class TaskStatus(models.TextChoices):
 | 
				
			|||||||
    ERROR = "error"
 | 
					    ERROR = "error"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class SystemTask(SerializerModel, ExpiringModel):
 | 
					class SystemTask(ExpiringModel):
 | 
				
			||||||
    """Info about a system task running in the background along with details to restart the task"""
 | 
					    """DEPRECATED do not use"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 | 
					    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 | 
				
			||||||
    name = models.TextField()
 | 
					    name = models.TextField()
 | 
				
			||||||
@ -638,41 +654,13 @@ class SystemTask(SerializerModel, ExpiringModel):
 | 
				
			|||||||
    task_call_args = models.JSONField(default=list)
 | 
					    task_call_args = models.JSONField(default=list)
 | 
				
			||||||
    task_call_kwargs = models.JSONField(default=dict)
 | 
					    task_call_kwargs = models.JSONField(default=dict)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @property
 | 
					 | 
				
			||||||
    def serializer(self) -> type[Serializer]:
 | 
					 | 
				
			||||||
        from authentik.events.api.tasks import SystemTaskSerializer
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        return SystemTaskSerializer
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def update_metrics(self):
 | 
					 | 
				
			||||||
        """Update prometheus metrics"""
 | 
					 | 
				
			||||||
        # TODO: Deprecated metric - remove in 2024.2 or later
 | 
					 | 
				
			||||||
        GAUGE_TASKS.labels(
 | 
					 | 
				
			||||||
            tenant=connection.schema_name,
 | 
					 | 
				
			||||||
            task_name=self.name,
 | 
					 | 
				
			||||||
            task_uid=self.uid or "",
 | 
					 | 
				
			||||||
            status=self.status.lower(),
 | 
					 | 
				
			||||||
        ).set(self.duration)
 | 
					 | 
				
			||||||
        SYSTEM_TASK_TIME.labels(
 | 
					 | 
				
			||||||
            tenant=connection.schema_name,
 | 
					 | 
				
			||||||
            task_name=self.name,
 | 
					 | 
				
			||||||
            task_uid=self.uid or "",
 | 
					 | 
				
			||||||
        ).observe(self.duration)
 | 
					 | 
				
			||||||
        SYSTEM_TASK_STATUS.labels(
 | 
					 | 
				
			||||||
            tenant=connection.schema_name,
 | 
					 | 
				
			||||||
            task_name=self.name,
 | 
					 | 
				
			||||||
            task_uid=self.uid or "",
 | 
					 | 
				
			||||||
            status=self.status.lower(),
 | 
					 | 
				
			||||||
        ).inc()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def __str__(self) -> str:
 | 
					    def __str__(self) -> str:
 | 
				
			||||||
        return f"System Task {self.name}"
 | 
					        return f"System Task {self.name}"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    class Meta:
 | 
					    class Meta:
 | 
				
			||||||
        unique_together = (("name", "uid"),)
 | 
					        unique_together = (("name", "uid"),)
 | 
				
			||||||
        # Remove "add", "change" and "delete" permissions as those are not used
 | 
					        default_permissions = ()
 | 
				
			||||||
        default_permissions = ["view"]
 | 
					        permissions = ()
 | 
				
			||||||
        permissions = [("run_task", _("Run task"))]
 | 
					 | 
				
			||||||
        verbose_name = _("System Task")
 | 
					        verbose_name = _("System Task")
 | 
				
			||||||
        verbose_name_plural = _("System Tasks")
 | 
					        verbose_name_plural = _("System Tasks")
 | 
				
			||||||
        indexes = ExpiringModel.Meta.indexes
 | 
					        indexes = ExpiringModel.Meta.indexes
 | 
				
			||||||
 | 
				
			|||||||
@ -1,13 +0,0 @@
 | 
				
			|||||||
"""Event Settings"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from celery.schedules import crontab
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.lib.utils.time import fqdn_rand
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
CELERY_BEAT_SCHEDULE = {
 | 
					 | 
				
			||||||
    "events_notification_cleanup": {
 | 
					 | 
				
			||||||
        "task": "authentik.events.tasks.notification_cleanup",
 | 
					 | 
				
			||||||
        "schedule": crontab(minute=fqdn_rand("notification_cleanup"), hour="*/8"),
 | 
					 | 
				
			||||||
        "options": {"queue": "authentik_scheduled"},
 | 
					 | 
				
			||||||
    },
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@ -12,13 +12,10 @@ from rest_framework.request import Request
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from authentik.core.models import AuthenticatedSession, User
 | 
					from authentik.core.models import AuthenticatedSession, User
 | 
				
			||||||
from authentik.core.signals import login_failed, password_changed
 | 
					from authentik.core.signals import login_failed, password_changed
 | 
				
			||||||
from authentik.events.apps import SYSTEM_TASK_STATUS
 | 
					from authentik.events.models import Event, EventAction
 | 
				
			||||||
from authentik.events.models import Event, EventAction, SystemTask
 | 
					 | 
				
			||||||
from authentik.events.tasks import event_notification_handler, gdpr_cleanup
 | 
					 | 
				
			||||||
from authentik.flows.models import Stage
 | 
					from authentik.flows.models import Stage
 | 
				
			||||||
from authentik.flows.planner import PLAN_CONTEXT_OUTPOST, PLAN_CONTEXT_SOURCE, FlowPlan
 | 
					from authentik.flows.planner import PLAN_CONTEXT_OUTPOST, PLAN_CONTEXT_SOURCE, FlowPlan
 | 
				
			||||||
from authentik.flows.views.executor import SESSION_KEY_PLAN
 | 
					from authentik.flows.views.executor import SESSION_KEY_PLAN
 | 
				
			||||||
from authentik.root.monitoring import monitoring_set
 | 
					 | 
				
			||||||
from authentik.stages.invitation.models import Invitation
 | 
					from authentik.stages.invitation.models import Invitation
 | 
				
			||||||
from authentik.stages.invitation.signals import invitation_used
 | 
					from authentik.stages.invitation.signals import invitation_used
 | 
				
			||||||
from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS
 | 
					from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS
 | 
				
			||||||
@ -114,19 +111,15 @@ def on_password_changed(sender, user: User, password: str, request: HttpRequest
 | 
				
			|||||||
@receiver(post_save, sender=Event)
 | 
					@receiver(post_save, sender=Event)
 | 
				
			||||||
def event_post_save_notification(sender, instance: Event, **_):
 | 
					def event_post_save_notification(sender, instance: Event, **_):
 | 
				
			||||||
    """Start task to check if any policies trigger an notification on this event"""
 | 
					    """Start task to check if any policies trigger an notification on this event"""
 | 
				
			||||||
    event_notification_handler.delay(instance.event_uuid.hex)
 | 
					    from authentik.events.tasks import event_trigger_dispatch
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    event_trigger_dispatch.send(instance.event_uuid)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@receiver(pre_delete, sender=User)
 | 
					@receiver(pre_delete, sender=User)
 | 
				
			||||||
def event_user_pre_delete_cleanup(sender, instance: User, **_):
 | 
					def event_user_pre_delete_cleanup(sender, instance: User, **_):
 | 
				
			||||||
    """If gdpr_compliance is enabled, remove all the user's events"""
 | 
					    """If gdpr_compliance is enabled, remove all the user's events"""
 | 
				
			||||||
 | 
					    from authentik.events.tasks import gdpr_cleanup
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    if get_current_tenant().gdpr_compliance:
 | 
					    if get_current_tenant().gdpr_compliance:
 | 
				
			||||||
        gdpr_cleanup.delay(instance.pk)
 | 
					        gdpr_cleanup.send(instance.pk)
 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
@receiver(monitoring_set)
 | 
					 | 
				
			||||||
def monitoring_system_task(sender, **_):
 | 
					 | 
				
			||||||
    """Update metrics when task is saved"""
 | 
					 | 
				
			||||||
    SYSTEM_TASK_STATUS.clear()
 | 
					 | 
				
			||||||
    for task in SystemTask.objects.all():
 | 
					 | 
				
			||||||
        task.update_metrics()
 | 
					 | 
				
			||||||
 | 
				
			|||||||
@ -1,156 +0,0 @@
 | 
				
			|||||||
"""Monitored tasks"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from datetime import datetime, timedelta
 | 
					 | 
				
			||||||
from time import perf_counter
 | 
					 | 
				
			||||||
from typing import Any
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.utils.timezone import now
 | 
					 | 
				
			||||||
from django.utils.translation import gettext_lazy as _
 | 
					 | 
				
			||||||
from structlog.stdlib import BoundLogger, get_logger
 | 
					 | 
				
			||||||
from tenant_schemas_celery.task import TenantTask
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.events.logs import LogEvent
 | 
					 | 
				
			||||||
from authentik.events.models import Event, EventAction, TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.models import SystemTask as DBSystemTask
 | 
					 | 
				
			||||||
from authentik.events.utils import sanitize_item
 | 
					 | 
				
			||||||
from authentik.lib.utils.errors import exception_to_string
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class SystemTask(TenantTask):
 | 
					 | 
				
			||||||
    """Task which can save its state to the cache"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    logger: BoundLogger
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    # For tasks that should only be listed if they failed, set this to False
 | 
					 | 
				
			||||||
    save_on_success: bool
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    _status: TaskStatus
 | 
					 | 
				
			||||||
    _messages: list[LogEvent]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    _uid: str | None
 | 
					 | 
				
			||||||
    # Precise start time from perf_counter
 | 
					 | 
				
			||||||
    _start_precise: float | None = None
 | 
					 | 
				
			||||||
    _start: datetime | None = None
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def __init__(self, *args, **kwargs) -> None:
 | 
					 | 
				
			||||||
        super().__init__(*args, **kwargs)
 | 
					 | 
				
			||||||
        self._status = TaskStatus.SUCCESSFUL
 | 
					 | 
				
			||||||
        self.save_on_success = True
 | 
					 | 
				
			||||||
        self._uid = None
 | 
					 | 
				
			||||||
        self._status = None
 | 
					 | 
				
			||||||
        self._messages = []
 | 
					 | 
				
			||||||
        self.result_timeout_hours = 6
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def set_uid(self, uid: str):
 | 
					 | 
				
			||||||
        """Set UID, so in the case of an unexpected error its saved correctly"""
 | 
					 | 
				
			||||||
        self._uid = uid
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def set_status(self, status: TaskStatus, *messages: LogEvent):
 | 
					 | 
				
			||||||
        """Set result for current run, will overwrite previous result."""
 | 
					 | 
				
			||||||
        self._status = status
 | 
					 | 
				
			||||||
        self._messages = list(messages)
 | 
					 | 
				
			||||||
        for idx, msg in enumerate(self._messages):
 | 
					 | 
				
			||||||
            if not isinstance(msg, LogEvent):
 | 
					 | 
				
			||||||
                self._messages[idx] = LogEvent(msg, logger=self.__name__, log_level="info")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def set_error(self, exception: Exception, *messages: LogEvent):
 | 
					 | 
				
			||||||
        """Set result to error and save exception"""
 | 
					 | 
				
			||||||
        self._status = TaskStatus.ERROR
 | 
					 | 
				
			||||||
        self._messages = list(messages)
 | 
					 | 
				
			||||||
        self._messages.extend(
 | 
					 | 
				
			||||||
            [LogEvent(exception_to_string(exception), logger=self.__name__, log_level="error")]
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def before_start(self, task_id, args, kwargs):
 | 
					 | 
				
			||||||
        self._start_precise = perf_counter()
 | 
					 | 
				
			||||||
        self._start = now()
 | 
					 | 
				
			||||||
        self.logger = get_logger().bind(task_id=task_id)
 | 
					 | 
				
			||||||
        return super().before_start(task_id, args, kwargs)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def db(self) -> DBSystemTask | None:
 | 
					 | 
				
			||||||
        """Get DB object for latest task"""
 | 
					 | 
				
			||||||
        return DBSystemTask.objects.filter(
 | 
					 | 
				
			||||||
            name=self.__name__,
 | 
					 | 
				
			||||||
            uid=self._uid,
 | 
					 | 
				
			||||||
        ).first()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def after_return(self, status, retval, task_id, args: list[Any], kwargs: dict[str, Any], einfo):
 | 
					 | 
				
			||||||
        super().after_return(status, retval, task_id, args, kwargs, einfo=einfo)
 | 
					 | 
				
			||||||
        if not self._status:
 | 
					 | 
				
			||||||
            return
 | 
					 | 
				
			||||||
        if self._status == TaskStatus.SUCCESSFUL and not self.save_on_success:
 | 
					 | 
				
			||||||
            DBSystemTask.objects.filter(
 | 
					 | 
				
			||||||
                name=self.__name__,
 | 
					 | 
				
			||||||
                uid=self._uid,
 | 
					 | 
				
			||||||
            ).delete()
 | 
					 | 
				
			||||||
            return
 | 
					 | 
				
			||||||
        DBSystemTask.objects.update_or_create(
 | 
					 | 
				
			||||||
            name=self.__name__,
 | 
					 | 
				
			||||||
            uid=self._uid,
 | 
					 | 
				
			||||||
            defaults={
 | 
					 | 
				
			||||||
                "description": self.__doc__,
 | 
					 | 
				
			||||||
                "start_timestamp": self._start or now(),
 | 
					 | 
				
			||||||
                "finish_timestamp": now(),
 | 
					 | 
				
			||||||
                "duration": max(perf_counter() - self._start_precise, 0),
 | 
					 | 
				
			||||||
                "task_call_module": self.__module__,
 | 
					 | 
				
			||||||
                "task_call_func": self.__name__,
 | 
					 | 
				
			||||||
                "task_call_args": sanitize_item(args),
 | 
					 | 
				
			||||||
                "task_call_kwargs": sanitize_item(kwargs),
 | 
					 | 
				
			||||||
                "status": self._status,
 | 
					 | 
				
			||||||
                "messages": sanitize_item(self._messages),
 | 
					 | 
				
			||||||
                "expires": now() + timedelta(hours=self.result_timeout_hours),
 | 
					 | 
				
			||||||
                "expiring": True,
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def on_failure(self, exc, task_id, args, kwargs, einfo):
 | 
					 | 
				
			||||||
        super().on_failure(exc, task_id, args, kwargs, einfo=einfo)
 | 
					 | 
				
			||||||
        if not self._status:
 | 
					 | 
				
			||||||
            self.set_error(exc)
 | 
					 | 
				
			||||||
        DBSystemTask.objects.update_or_create(
 | 
					 | 
				
			||||||
            name=self.__name__,
 | 
					 | 
				
			||||||
            uid=self._uid,
 | 
					 | 
				
			||||||
            defaults={
 | 
					 | 
				
			||||||
                "description": self.__doc__,
 | 
					 | 
				
			||||||
                "start_timestamp": self._start or now(),
 | 
					 | 
				
			||||||
                "finish_timestamp": now(),
 | 
					 | 
				
			||||||
                "duration": max(perf_counter() - self._start_precise, 0),
 | 
					 | 
				
			||||||
                "task_call_module": self.__module__,
 | 
					 | 
				
			||||||
                "task_call_func": self.__name__,
 | 
					 | 
				
			||||||
                "task_call_args": sanitize_item(args),
 | 
					 | 
				
			||||||
                "task_call_kwargs": sanitize_item(kwargs),
 | 
					 | 
				
			||||||
                "status": self._status,
 | 
					 | 
				
			||||||
                "messages": sanitize_item(self._messages),
 | 
					 | 
				
			||||||
                "expires": now() + timedelta(hours=self.result_timeout_hours + 3),
 | 
					 | 
				
			||||||
                "expiring": True,
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        Event.new(
 | 
					 | 
				
			||||||
            EventAction.SYSTEM_TASK_EXCEPTION,
 | 
					 | 
				
			||||||
            message=f"Task {self.__name__} encountered an error: {exception_to_string(exc)}",
 | 
					 | 
				
			||||||
        ).save()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def run(self, *args, **kwargs):
 | 
					 | 
				
			||||||
        raise NotImplementedError
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
def prefill_task(func):
 | 
					 | 
				
			||||||
    """Ensure a task's details are always in cache, so it can always be triggered via API"""
 | 
					 | 
				
			||||||
    _prefill_tasks.append(
 | 
					 | 
				
			||||||
        DBSystemTask(
 | 
					 | 
				
			||||||
            name=func.__name__,
 | 
					 | 
				
			||||||
            description=func.__doc__,
 | 
					 | 
				
			||||||
            start_timestamp=now(),
 | 
					 | 
				
			||||||
            finish_timestamp=now(),
 | 
					 | 
				
			||||||
            status=TaskStatus.UNKNOWN,
 | 
					 | 
				
			||||||
            messages=sanitize_item([_("Task has not been run yet.")]),
 | 
					 | 
				
			||||||
            task_call_module=func.__module__,
 | 
					 | 
				
			||||||
            task_call_func=func.__name__,
 | 
					 | 
				
			||||||
            expiring=False,
 | 
					 | 
				
			||||||
            duration=0,
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
    )
 | 
					 | 
				
			||||||
    return func
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
_prefill_tasks = []
 | 
					 | 
				
			||||||
@ -1,41 +1,49 @@
 | 
				
			|||||||
"""Event notification tasks"""
 | 
					"""Event notification tasks"""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from uuid import UUID
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.db.models.query_utils import Q
 | 
					from django.db.models.query_utils import Q
 | 
				
			||||||
 | 
					from django.utils.translation import gettext_lazy as _
 | 
				
			||||||
 | 
					from django_dramatiq_postgres.middleware import CurrentTask
 | 
				
			||||||
 | 
					from dramatiq.actor import actor
 | 
				
			||||||
from guardian.shortcuts import get_anonymous_user
 | 
					from guardian.shortcuts import get_anonymous_user
 | 
				
			||||||
from structlog.stdlib import get_logger
 | 
					from structlog.stdlib import get_logger
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.core.expression.exceptions import PropertyMappingExpressionException
 | 
					 | 
				
			||||||
from authentik.core.models import User
 | 
					from authentik.core.models import User
 | 
				
			||||||
from authentik.events.models import (
 | 
					from authentik.events.models import (
 | 
				
			||||||
    Event,
 | 
					    Event,
 | 
				
			||||||
    Notification,
 | 
					    Notification,
 | 
				
			||||||
    NotificationRule,
 | 
					    NotificationRule,
 | 
				
			||||||
    NotificationTransport,
 | 
					    NotificationTransport,
 | 
				
			||||||
    NotificationTransportError,
 | 
					 | 
				
			||||||
    TaskStatus,
 | 
					 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.events.system_tasks import SystemTask, prefill_task
 | 
					 | 
				
			||||||
from authentik.policies.engine import PolicyEngine
 | 
					from authentik.policies.engine import PolicyEngine
 | 
				
			||||||
from authentik.policies.models import PolicyBinding, PolicyEngineMode
 | 
					from authentik.policies.models import PolicyBinding, PolicyEngineMode
 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					from authentik.tasks.models import Task
 | 
				
			||||||
 | 
					
 | 
				
			||||||
LOGGER = get_logger()
 | 
					LOGGER = get_logger()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Dispatch new event notifications."))
 | 
				
			||||||
def event_notification_handler(event_uuid: str):
 | 
					def event_trigger_dispatch(event_uuid: UUID):
 | 
				
			||||||
    """Start task for each trigger definition"""
 | 
					 | 
				
			||||||
    for trigger in NotificationRule.objects.all():
 | 
					    for trigger in NotificationRule.objects.all():
 | 
				
			||||||
        event_trigger_handler.apply_async(args=[event_uuid, trigger.name], queue="authentik_events")
 | 
					        event_trigger_handler.send_with_options(args=(event_uuid, trigger.name), rel_obj=trigger)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(
 | 
				
			||||||
def event_trigger_handler(event_uuid: str, trigger_name: str):
 | 
					    description=_(
 | 
				
			||||||
 | 
					        "Check if policies attached to NotificationRule match event "
 | 
				
			||||||
 | 
					        "and dispatch notification tasks."
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					def event_trigger_handler(event_uuid: UUID, trigger_name: str):
 | 
				
			||||||
    """Check if policies attached to NotificationRule match event"""
 | 
					    """Check if policies attached to NotificationRule match event"""
 | 
				
			||||||
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    event: Event = Event.objects.filter(event_uuid=event_uuid).first()
 | 
					    event: Event = Event.objects.filter(event_uuid=event_uuid).first()
 | 
				
			||||||
    if not event:
 | 
					    if not event:
 | 
				
			||||||
        LOGGER.warning("event doesn't exist yet or anymore", event_uuid=event_uuid)
 | 
					        self.warning("event doesn't exist yet or anymore", event_uuid=event_uuid)
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    trigger: NotificationRule | None = NotificationRule.objects.filter(name=trigger_name).first()
 | 
					    trigger: NotificationRule | None = NotificationRule.objects.filter(name=trigger_name).first()
 | 
				
			||||||
    if not trigger:
 | 
					    if not trigger:
 | 
				
			||||||
        return
 | 
					        return
 | 
				
			||||||
@ -70,57 +78,46 @@ def event_trigger_handler(event_uuid: str, trigger_name: str):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    LOGGER.debug("e(trigger): event trigger matched", trigger=trigger)
 | 
					    LOGGER.debug("e(trigger): event trigger matched", trigger=trigger)
 | 
				
			||||||
    # Create the notification objects
 | 
					    # Create the notification objects
 | 
				
			||||||
 | 
					    count = 0
 | 
				
			||||||
    for transport in trigger.transports.all():
 | 
					    for transport in trigger.transports.all():
 | 
				
			||||||
        for user in trigger.destination_users(event):
 | 
					        for user in trigger.destination_users(event):
 | 
				
			||||||
            LOGGER.debug("created notification")
 | 
					            notification_transport.send_with_options(
 | 
				
			||||||
            notification_transport.apply_async(
 | 
					                args=(
 | 
				
			||||||
                args=[
 | 
					 | 
				
			||||||
                    transport.pk,
 | 
					                    transport.pk,
 | 
				
			||||||
                    str(event.pk),
 | 
					                    event.pk,
 | 
				
			||||||
                    user.pk,
 | 
					                    user.pk,
 | 
				
			||||||
                    str(trigger.pk),
 | 
					                    trigger.pk,
 | 
				
			||||||
                ],
 | 
					                ),
 | 
				
			||||||
                queue="authentik_events",
 | 
					                rel_obj=transport,
 | 
				
			||||||
            )
 | 
					            )
 | 
				
			||||||
 | 
					            count += 1
 | 
				
			||||||
            if transport.send_once:
 | 
					            if transport.send_once:
 | 
				
			||||||
                break
 | 
					                break
 | 
				
			||||||
 | 
					    self.info(f"Created {count} notification tasks")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(
 | 
					@actor(description=_("Send notification."))
 | 
				
			||||||
    bind=True,
 | 
					def notification_transport(transport_pk: int, event_pk: str, user_pk: int, trigger_pk: str):
 | 
				
			||||||
    autoretry_for=(NotificationTransportError,),
 | 
					 | 
				
			||||||
    retry_backoff=True,
 | 
					 | 
				
			||||||
    base=SystemTask,
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
def notification_transport(
 | 
					 | 
				
			||||||
    self: SystemTask, transport_pk: int, event_pk: str, user_pk: int, trigger_pk: str
 | 
					 | 
				
			||||||
):
 | 
					 | 
				
			||||||
    """Send notification over specified transport"""
 | 
					    """Send notification over specified transport"""
 | 
				
			||||||
    self.save_on_success = False
 | 
					    event = Event.objects.filter(pk=event_pk).first()
 | 
				
			||||||
    try:
 | 
					    if not event:
 | 
				
			||||||
        event = Event.objects.filter(pk=event_pk).first()
 | 
					        return
 | 
				
			||||||
        if not event:
 | 
					    user = User.objects.filter(pk=user_pk).first()
 | 
				
			||||||
            return
 | 
					    if not user:
 | 
				
			||||||
        user = User.objects.filter(pk=user_pk).first()
 | 
					        return
 | 
				
			||||||
        if not user:
 | 
					    trigger = NotificationRule.objects.filter(pk=trigger_pk).first()
 | 
				
			||||||
            return
 | 
					    if not trigger:
 | 
				
			||||||
        trigger = NotificationRule.objects.filter(pk=trigger_pk).first()
 | 
					        return
 | 
				
			||||||
        if not trigger:
 | 
					    notification = Notification(
 | 
				
			||||||
            return
 | 
					        severity=trigger.severity, body=event.summary, event=event, user=user
 | 
				
			||||||
        notification = Notification(
 | 
					    )
 | 
				
			||||||
            severity=trigger.severity, body=event.summary, event=event, user=user
 | 
					    transport: NotificationTransport = NotificationTransport.objects.filter(pk=transport_pk).first()
 | 
				
			||||||
        )
 | 
					    if not transport:
 | 
				
			||||||
        transport = NotificationTransport.objects.filter(pk=transport_pk).first()
 | 
					        return
 | 
				
			||||||
        if not transport:
 | 
					    transport.send(notification)
 | 
				
			||||||
            return
 | 
					 | 
				
			||||||
        transport.send(notification)
 | 
					 | 
				
			||||||
        self.set_status(TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
    except (NotificationTransportError, PropertyMappingExpressionException) as exc:
 | 
					 | 
				
			||||||
        self.set_error(exc)
 | 
					 | 
				
			||||||
        raise exc
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task()
 | 
					@actor(description=_("Cleanup events for GDPR compliance."))
 | 
				
			||||||
def gdpr_cleanup(user_pk: int):
 | 
					def gdpr_cleanup(user_pk: int):
 | 
				
			||||||
    """cleanup events from gdpr_compliance"""
 | 
					    """cleanup events from gdpr_compliance"""
 | 
				
			||||||
    events = Event.objects.filter(user__pk=user_pk)
 | 
					    events = Event.objects.filter(user__pk=user_pk)
 | 
				
			||||||
@ -128,12 +125,12 @@ def gdpr_cleanup(user_pk: int):
 | 
				
			|||||||
    events.delete()
 | 
					    events.delete()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@CELERY_APP.task(bind=True, base=SystemTask)
 | 
					@actor(description=_("Cleanup seen notifications and notifications whose event expired."))
 | 
				
			||||||
@prefill_task
 | 
					def notification_cleanup():
 | 
				
			||||||
def notification_cleanup(self: SystemTask):
 | 
					 | 
				
			||||||
    """Cleanup seen notifications and notifications whose event expired."""
 | 
					    """Cleanup seen notifications and notifications whose event expired."""
 | 
				
			||||||
 | 
					    self: Task = CurrentTask.get_task()
 | 
				
			||||||
    notifications = Notification.objects.filter(Q(event=None) | Q(seen=True))
 | 
					    notifications = Notification.objects.filter(Q(event=None) | Q(seen=True))
 | 
				
			||||||
    amount = notifications.count()
 | 
					    amount = notifications.count()
 | 
				
			||||||
    notifications.delete()
 | 
					    notifications.delete()
 | 
				
			||||||
    LOGGER.debug("Expired notifications", amount=amount)
 | 
					    LOGGER.debug("Expired notifications", amount=amount)
 | 
				
			||||||
    self.set_status(TaskStatus.SUCCESSFUL, f"Expired {amount} Notifications")
 | 
					    self.info(f"Expired {amount} Notifications")
 | 
				
			||||||
 | 
				
			|||||||
@ -2,7 +2,9 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
from django.test import TestCase
 | 
					from django.test import TestCase
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					from authentik.events.context_processors.base import get_context_processors
 | 
				
			||||||
from authentik.events.context_processors.geoip import GeoIPContextProcessor
 | 
					from authentik.events.context_processors.geoip import GeoIPContextProcessor
 | 
				
			||||||
 | 
					from authentik.events.models import Event, EventAction
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
class TestGeoIP(TestCase):
 | 
					class TestGeoIP(TestCase):
 | 
				
			||||||
@ -13,8 +15,7 @@ class TestGeoIP(TestCase):
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    def test_simple(self):
 | 
					    def test_simple(self):
 | 
				
			||||||
        """Test simple city wrapper"""
 | 
					        """Test simple city wrapper"""
 | 
				
			||||||
        # IPs from
 | 
					        # IPs from https://github.com/maxmind/MaxMind-DB/blob/main/source-data/GeoLite2-City-Test.json
 | 
				
			||||||
        # https://github.com/maxmind/MaxMind-DB/blob/main/source-data/GeoLite2-City-Test.json
 | 
					 | 
				
			||||||
        self.assertEqual(
 | 
					        self.assertEqual(
 | 
				
			||||||
            self.reader.city_dict("2.125.160.216"),
 | 
					            self.reader.city_dict("2.125.160.216"),
 | 
				
			||||||
            {
 | 
					            {
 | 
				
			||||||
@ -25,3 +26,12 @@ class TestGeoIP(TestCase):
 | 
				
			|||||||
                "long": -1.25,
 | 
					                "long": -1.25,
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def test_special_chars(self):
 | 
				
			||||||
 | 
					        """Test city name with special characters"""
 | 
				
			||||||
 | 
					        # IPs from https://github.com/maxmind/MaxMind-DB/blob/main/source-data/GeoLite2-City-Test.json
 | 
				
			||||||
 | 
					        event = Event.new(EventAction.LOGIN)
 | 
				
			||||||
 | 
					        event.client_ip = "89.160.20.112"
 | 
				
			||||||
 | 
					        for processor in get_context_processors():
 | 
				
			||||||
 | 
					            processor.enrich_event(event)
 | 
				
			||||||
 | 
					        event.save()
 | 
				
			||||||
 | 
				
			|||||||
@ -8,9 +8,11 @@ from django.views.debug import SafeExceptionReporterFilter
 | 
				
			|||||||
from guardian.shortcuts import get_anonymous_user
 | 
					from guardian.shortcuts import get_anonymous_user
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.brands.models import Brand
 | 
					from authentik.brands.models import Brand
 | 
				
			||||||
from authentik.core.models import Group
 | 
					from authentik.core.models import Group, User
 | 
				
			||||||
 | 
					from authentik.core.tests.utils import create_test_user
 | 
				
			||||||
from authentik.events.models import Event
 | 
					from authentik.events.models import Event
 | 
				
			||||||
from authentik.flows.views.executor import QS_QUERY
 | 
					from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
 | 
				
			||||||
 | 
					from authentik.flows.views.executor import QS_QUERY, SESSION_KEY_PLAN
 | 
				
			||||||
from authentik.lib.generators import generate_id
 | 
					from authentik.lib.generators import generate_id
 | 
				
			||||||
from authentik.policies.dummy.models import DummyPolicy
 | 
					from authentik.policies.dummy.models import DummyPolicy
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@ -116,3 +118,92 @@ class TestEvents(TestCase):
 | 
				
			|||||||
                "pk": brand.pk.hex,
 | 
					                "pk": brand.pk.hex,
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
        )
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def test_from_http_flow_pending_user(self):
 | 
				
			||||||
 | 
					        """Test request from flow request with a pending user"""
 | 
				
			||||||
 | 
					        user = create_test_user()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        session = self.client.session
 | 
				
			||||||
 | 
					        plan = FlowPlan(generate_id())
 | 
				
			||||||
 | 
					        plan.context[PLAN_CONTEXT_PENDING_USER] = user
 | 
				
			||||||
 | 
					        session[SESSION_KEY_PLAN] = plan
 | 
				
			||||||
 | 
					        session.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        request = self.factory.get("/")
 | 
				
			||||||
 | 
					        request.session = session
 | 
				
			||||||
 | 
					        request.user = user
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        event = Event.new("unittest").from_http(request)
 | 
				
			||||||
 | 
					        self.assertEqual(
 | 
				
			||||||
 | 
					            event.user,
 | 
				
			||||||
 | 
					            {
 | 
				
			||||||
 | 
					                "email": user.email,
 | 
				
			||||||
 | 
					                "pk": user.pk,
 | 
				
			||||||
 | 
					                "username": user.username,
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def test_from_http_flow_pending_user_anon(self):
 | 
				
			||||||
 | 
					        """Test request from flow request with a pending user"""
 | 
				
			||||||
 | 
					        user = create_test_user()
 | 
				
			||||||
 | 
					        anon = get_anonymous_user()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        session = self.client.session
 | 
				
			||||||
 | 
					        plan = FlowPlan(generate_id())
 | 
				
			||||||
 | 
					        plan.context[PLAN_CONTEXT_PENDING_USER] = user
 | 
				
			||||||
 | 
					        session[SESSION_KEY_PLAN] = plan
 | 
				
			||||||
 | 
					        session.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        request = self.factory.get("/")
 | 
				
			||||||
 | 
					        request.session = session
 | 
				
			||||||
 | 
					        request.user = anon
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        event = Event.new("unittest").from_http(request)
 | 
				
			||||||
 | 
					        self.assertEqual(
 | 
				
			||||||
 | 
					            event.user,
 | 
				
			||||||
 | 
					            {
 | 
				
			||||||
 | 
					                "authenticated_as": {
 | 
				
			||||||
 | 
					                    "pk": anon.pk,
 | 
				
			||||||
 | 
					                    "is_anonymous": True,
 | 
				
			||||||
 | 
					                    "username": "AnonymousUser",
 | 
				
			||||||
 | 
					                    "email": "",
 | 
				
			||||||
 | 
					                },
 | 
				
			||||||
 | 
					                "email": user.email,
 | 
				
			||||||
 | 
					                "pk": user.pk,
 | 
				
			||||||
 | 
					                "username": user.username,
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def test_from_http_flow_pending_user_fake(self):
 | 
				
			||||||
 | 
					        """Test request from flow request with a pending user"""
 | 
				
			||||||
 | 
					        user = User(
 | 
				
			||||||
 | 
					            username=generate_id(),
 | 
				
			||||||
 | 
					            email=generate_id(),
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					        anon = get_anonymous_user()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        session = self.client.session
 | 
				
			||||||
 | 
					        plan = FlowPlan(generate_id())
 | 
				
			||||||
 | 
					        plan.context[PLAN_CONTEXT_PENDING_USER] = user
 | 
				
			||||||
 | 
					        session[SESSION_KEY_PLAN] = plan
 | 
				
			||||||
 | 
					        session.save()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        request = self.factory.get("/")
 | 
				
			||||||
 | 
					        request.session = session
 | 
				
			||||||
 | 
					        request.user = anon
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        event = Event.new("unittest").from_http(request)
 | 
				
			||||||
 | 
					        self.assertEqual(
 | 
				
			||||||
 | 
					            event.user,
 | 
				
			||||||
 | 
					            {
 | 
				
			||||||
 | 
					                "authenticated_as": {
 | 
				
			||||||
 | 
					                    "pk": anon.pk,
 | 
				
			||||||
 | 
					                    "is_anonymous": True,
 | 
				
			||||||
 | 
					                    "username": "AnonymousUser",
 | 
				
			||||||
 | 
					                    "email": "",
 | 
				
			||||||
 | 
					                },
 | 
				
			||||||
 | 
					                "email": user.email,
 | 
				
			||||||
 | 
					                "pk": user.pk,
 | 
				
			||||||
 | 
					                "username": user.username,
 | 
				
			||||||
 | 
					            },
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
				
			|||||||
@ -1,103 +0,0 @@
 | 
				
			|||||||
"""Test Monitored tasks"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from json import loads
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from django.urls import reverse
 | 
					 | 
				
			||||||
from rest_framework.test import APITestCase
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
from authentik.core.tasks import clean_expired_models
 | 
					 | 
				
			||||||
from authentik.core.tests.utils import create_test_admin_user
 | 
					 | 
				
			||||||
from authentik.events.models import SystemTask as DBSystemTask
 | 
					 | 
				
			||||||
from authentik.events.models import TaskStatus
 | 
					 | 
				
			||||||
from authentik.events.system_tasks import SystemTask
 | 
					 | 
				
			||||||
from authentik.lib.generators import generate_id
 | 
					 | 
				
			||||||
from authentik.root.celery import CELERY_APP
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
class TestSystemTasks(APITestCase):
 | 
					 | 
				
			||||||
    """Test Monitored tasks"""
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def setUp(self):
 | 
					 | 
				
			||||||
        super().setUp()
 | 
					 | 
				
			||||||
        self.user = create_test_admin_user()
 | 
					 | 
				
			||||||
        self.client.force_login(self.user)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_failed_successful_remove_state(self):
 | 
					 | 
				
			||||||
        """Test that a task with `save_on_success` set to `False` that failed saves
 | 
					 | 
				
			||||||
        a state, and upon successful completion will delete the state"""
 | 
					 | 
				
			||||||
        should_fail = True
 | 
					 | 
				
			||||||
        uid = generate_id()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        @CELERY_APP.task(
 | 
					 | 
				
			||||||
            bind=True,
 | 
					 | 
				
			||||||
            base=SystemTask,
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        def test_task(self: SystemTask):
 | 
					 | 
				
			||||||
            self.save_on_success = False
 | 
					 | 
				
			||||||
            self.set_uid(uid)
 | 
					 | 
				
			||||||
            self.set_status(TaskStatus.ERROR if should_fail else TaskStatus.SUCCESSFUL)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        # First test successful run
 | 
					 | 
				
			||||||
        should_fail = False
 | 
					 | 
				
			||||||
        test_task.delay().get()
 | 
					 | 
				
			||||||
        self.assertIsNone(DBSystemTask.objects.filter(name="test_task", uid=uid).first())
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        # Then test failed
 | 
					 | 
				
			||||||
        should_fail = True
 | 
					 | 
				
			||||||
        test_task.delay().get()
 | 
					 | 
				
			||||||
        task = DBSystemTask.objects.filter(name="test_task", uid=uid).first()
 | 
					 | 
				
			||||||
        self.assertEqual(task.status, TaskStatus.ERROR)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        # Then after that, the state should be removed
 | 
					 | 
				
			||||||
        should_fail = False
 | 
					 | 
				
			||||||
        test_task.delay().get()
 | 
					 | 
				
			||||||
        self.assertIsNone(DBSystemTask.objects.filter(name="test_task", uid=uid).first())
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_tasks(self):
 | 
					 | 
				
			||||||
        """Test Task API"""
 | 
					 | 
				
			||||||
        clean_expired_models.delay().get()
 | 
					 | 
				
			||||||
        response = self.client.get(reverse("authentik_api:systemtask-list"))
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 200)
 | 
					 | 
				
			||||||
        body = loads(response.content)
 | 
					 | 
				
			||||||
        self.assertTrue(any(task["name"] == "clean_expired_models" for task in body["results"]))
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_tasks_single(self):
 | 
					 | 
				
			||||||
        """Test Task API (read single)"""
 | 
					 | 
				
			||||||
        clean_expired_models.delay().get()
 | 
					 | 
				
			||||||
        task = DBSystemTask.objects.filter(name="clean_expired_models").first()
 | 
					 | 
				
			||||||
        response = self.client.get(
 | 
					 | 
				
			||||||
            reverse(
 | 
					 | 
				
			||||||
                "authentik_api:systemtask-detail",
 | 
					 | 
				
			||||||
                kwargs={"pk": str(task.pk)},
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 200)
 | 
					 | 
				
			||||||
        body = loads(response.content)
 | 
					 | 
				
			||||||
        self.assertEqual(body["status"], TaskStatus.SUCCESSFUL.value)
 | 
					 | 
				
			||||||
        self.assertEqual(body["name"], "clean_expired_models")
 | 
					 | 
				
			||||||
        response = self.client.get(
 | 
					 | 
				
			||||||
            reverse("authentik_api:systemtask-detail", kwargs={"pk": "qwerqwer"})
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 404)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_tasks_run(self):
 | 
					 | 
				
			||||||
        """Test Task API (run)"""
 | 
					 | 
				
			||||||
        clean_expired_models.delay().get()
 | 
					 | 
				
			||||||
        task = DBSystemTask.objects.filter(name="clean_expired_models").first()
 | 
					 | 
				
			||||||
        response = self.client.post(
 | 
					 | 
				
			||||||
            reverse(
 | 
					 | 
				
			||||||
                "authentik_api:systemtask-run",
 | 
					 | 
				
			||||||
                kwargs={"pk": str(task.pk)},
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 204)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    def test_tasks_run_404(self):
 | 
					 | 
				
			||||||
        """Test Task API (run, 404)"""
 | 
					 | 
				
			||||||
        response = self.client.post(
 | 
					 | 
				
			||||||
            reverse(
 | 
					 | 
				
			||||||
                "authentik_api:systemtask-run",
 | 
					 | 
				
			||||||
                kwargs={"pk": "qwerqewrqrqewrqewr"},
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
        )
 | 
					 | 
				
			||||||
        self.assertEqual(response.status_code, 404)
 | 
					 | 
				
			||||||
@ -5,13 +5,11 @@ from authentik.events.api.notification_mappings import NotificationWebhookMappin
 | 
				
			|||||||
from authentik.events.api.notification_rules import NotificationRuleViewSet
 | 
					from authentik.events.api.notification_rules import NotificationRuleViewSet
 | 
				
			||||||
from authentik.events.api.notification_transports import NotificationTransportViewSet
 | 
					from authentik.events.api.notification_transports import NotificationTransportViewSet
 | 
				
			||||||
from authentik.events.api.notifications import NotificationViewSet
 | 
					from authentik.events.api.notifications import NotificationViewSet
 | 
				
			||||||
from authentik.events.api.tasks import SystemTaskViewSet
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
api_urlpatterns = [
 | 
					api_urlpatterns = [
 | 
				
			||||||
    ("events/events", EventViewSet),
 | 
					    ("events/events", EventViewSet),
 | 
				
			||||||
    ("events/notifications", NotificationViewSet),
 | 
					    ("events/notifications", NotificationViewSet),
 | 
				
			||||||
    ("events/transports", NotificationTransportViewSet),
 | 
					    ("events/transports", NotificationTransportViewSet),
 | 
				
			||||||
    ("events/rules", NotificationRuleViewSet),
 | 
					    ("events/rules", NotificationRuleViewSet),
 | 
				
			||||||
    ("events/system_tasks", SystemTaskViewSet),
 | 
					 | 
				
			||||||
    ("propertymappings/notification", NotificationWebhookMappingViewSet),
 | 
					    ("propertymappings/notification", NotificationWebhookMappingViewSet),
 | 
				
			||||||
]
 | 
					]
 | 
				
			||||||
 | 
				
			|||||||
@ -74,8 +74,8 @@ def model_to_dict(model: Model) -> dict[str, Any]:
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def get_user(user: User | AnonymousUser, original_user: User | None = None) -> dict[str, Any]:
 | 
					def get_user(user: User | AnonymousUser) -> dict[str, Any]:
 | 
				
			||||||
    """Convert user object to dictionary, optionally including the original user"""
 | 
					    """Convert user object to dictionary"""
 | 
				
			||||||
    if isinstance(user, AnonymousUser):
 | 
					    if isinstance(user, AnonymousUser):
 | 
				
			||||||
        try:
 | 
					        try:
 | 
				
			||||||
            user = get_anonymous_user()
 | 
					            user = get_anonymous_user()
 | 
				
			||||||
@ -88,10 +88,6 @@ def get_user(user: User | AnonymousUser, original_user: User | None = None) -> d
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
    if user.username == settings.ANONYMOUS_USER_NAME:
 | 
					    if user.username == settings.ANONYMOUS_USER_NAME:
 | 
				
			||||||
        user_data["is_anonymous"] = True
 | 
					        user_data["is_anonymous"] = True
 | 
				
			||||||
    if original_user:
 | 
					 | 
				
			||||||
        original_data = get_user(original_user)
 | 
					 | 
				
			||||||
        original_data["on_behalf_of"] = user_data
 | 
					 | 
				
			||||||
        return original_data
 | 
					 | 
				
			||||||
    return user_data
 | 
					    return user_data
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
				
			|||||||
@ -4,8 +4,10 @@ from unittest.mock import MagicMock, PropertyMock, patch
 | 
				
			|||||||
from urllib.parse import urlencode
 | 
					from urllib.parse import urlencode
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from django.http import HttpRequest, HttpResponse
 | 
					from django.http import HttpRequest, HttpResponse
 | 
				
			||||||
 | 
					from django.test import override_settings
 | 
				
			||||||
from django.test.client import RequestFactory
 | 
					from django.test.client import RequestFactory
 | 
				
			||||||
from django.urls import reverse
 | 
					from django.urls import reverse
 | 
				
			||||||
 | 
					from rest_framework.exceptions import ParseError
 | 
				
			||||||
 | 
					
 | 
				
			||||||
from authentik.core.models import Group, User
 | 
					from authentik.core.models import Group, User
 | 
				
			||||||
from authentik.core.tests.utils import create_test_flow, create_test_user
 | 
					from authentik.core.tests.utils import create_test_flow, create_test_user
 | 
				
			||||||
@ -648,3 +650,25 @@ class TestFlowExecutor(FlowTestCase):
 | 
				
			|||||||
            self.assertStageResponse(response, flow, component="ak-stage-identification")
 | 
					            self.assertStageResponse(response, flow, component="ak-stage-identification")
 | 
				
			||||||
            response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True)
 | 
					            response = self.client.post(exec_url, {"uid_field": user_other.username}, follow=True)
 | 
				
			||||||
            self.assertStageResponse(response, flow, component="ak-stage-access-denied")
 | 
					            self.assertStageResponse(response, flow, component="ak-stage-access-denied")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @patch(
 | 
				
			||||||
 | 
					        "authentik.flows.views.executor.to_stage_response",
 | 
				
			||||||
 | 
					        TO_STAGE_RESPONSE_MOCK,
 | 
				
			||||||
 | 
					    )
 | 
				
			||||||
 | 
					    def test_invalid_json(self):
 | 
				
			||||||
 | 
					        """Test invalid JSON body"""
 | 
				
			||||||
 | 
					        flow = create_test_flow()
 | 
				
			||||||
 | 
					        FlowStageBinding.objects.create(
 | 
				
			||||||
 | 
					            target=flow, stage=DummyStage.objects.create(name=generate_id()), order=0
 | 
				
			||||||
 | 
					        )
 | 
				
			||||||
 | 
					        url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": flow.slug})
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        with override_settings(TEST=False, DEBUG=False):
 | 
				
			||||||
 | 
					            self.client.logout()
 | 
				
			||||||
 | 
					            response = self.client.post(url, data="{", content_type="application/json")
 | 
				
			||||||
 | 
					            self.assertEqual(response.status_code, 200)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        with self.assertRaises(ParseError):
 | 
				
			||||||
 | 
					            self.client.logout()
 | 
				
			||||||
 | 
					            response = self.client.post(url, data="{", content_type="application/json")
 | 
				
			||||||
 | 
					            self.assertEqual(response.status_code, 200)
 | 
				
			||||||
 | 
				
			|||||||
@ -55,7 +55,7 @@ from authentik.flows.planner import (
 | 
				
			|||||||
    FlowPlanner,
 | 
					    FlowPlanner,
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
from authentik.flows.stage import AccessDeniedStage, StageView
 | 
					from authentik.flows.stage import AccessDeniedStage, StageView
 | 
				
			||||||
from authentik.lib.sentry import SentryIgnoredException
 | 
					from authentik.lib.sentry import SentryIgnoredException, should_ignore_exception
 | 
				
			||||||
from authentik.lib.utils.errors import exception_to_string
 | 
					from authentik.lib.utils.errors import exception_to_string
 | 
				
			||||||
from authentik.lib.utils.reflection import all_subclasses, class_to_path
 | 
					from authentik.lib.utils.reflection import all_subclasses, class_to_path
 | 
				
			||||||
from authentik.lib.utils.urls import is_url_absolute, redirect_with_qs
 | 
					from authentik.lib.utils.urls import is_url_absolute, redirect_with_qs
 | 
				
			||||||
@ -234,12 +234,13 @@ class FlowExecutorView(APIView):
 | 
				
			|||||||
        """Handle exception in stage execution"""
 | 
					        """Handle exception in stage execution"""
 | 
				
			||||||
        if settings.DEBUG or settings.TEST:
 | 
					        if settings.DEBUG or settings.TEST:
 | 
				
			||||||
            raise exc
 | 
					            raise exc
 | 
				
			||||||
        capture_exception(exc)
 | 
					 | 
				
			||||||
        self._logger.warning(exc)
 | 
					        self._logger.warning(exc)
 | 
				
			||||||
        Event.new(
 | 
					        if not should_ignore_exception(exc):
 | 
				
			||||||
            action=EventAction.SYSTEM_EXCEPTION,
 | 
					            capture_exception(exc)
 | 
				
			||||||
            message=exception_to_string(exc),
 | 
					            Event.new(
 | 
				
			||||||
        ).from_http(self.request)
 | 
					                action=EventAction.SYSTEM_EXCEPTION,
 | 
				
			||||||
 | 
					                message=exception_to_string(exc),
 | 
				
			||||||
 | 
					            ).from_http(self.request)
 | 
				
			||||||
        challenge = FlowErrorChallenge(self.request, exc)
 | 
					        challenge = FlowErrorChallenge(self.request, exc)
 | 
				
			||||||
        challenge.is_valid(raise_exception=True)
 | 
					        challenge.is_valid(raise_exception=True)
 | 
				
			||||||
        return to_stage_response(self.request, HttpChallengeResponse(challenge))
 | 
					        return to_stage_response(self.request, HttpChallengeResponse(challenge))
 | 
				
			||||||
 | 
				
			|||||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user