Compare commits
104
Commits
No files matched your search
+9
-1
@@ -1,5 +1,13 @@
|
||||
[alias]
|
||||
t = ["nextest", "run", "--workspace"]
|
||||
t = [
|
||||
"nextest",
|
||||
"run",
|
||||
"--workspace",
|
||||
"--filterset",
|
||||
"kind(lib) | kind(proc-macro) | kind(bin) | kind(example)",
|
||||
]
|
||||
tl = ["nextest", "list", "--workspace"]
|
||||
e2e = ["nextest", "run", "--workspace", "--filterset", "kind(test)"]
|
||||
|
||||
[build]
|
||||
rustflags = ["--cfg", "tokio_unstable"]
|
||||
@@ -1,2 +1 @@
|
||||
custom: https://goauthentik.io/pricing/
|
||||
github: goauthentik
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
name: Blank issue
|
||||
about: This issue type is only for internal use
|
||||
title:
|
||||
labels:
|
||||
assignees:
|
||||
---
|
||||
@@ -0,0 +1,57 @@
|
||||
name: "Comment usage instructions on PRs"
|
||||
description: "Comment usage instructions on PRs"
|
||||
|
||||
inputs:
|
||||
tag:
|
||||
description: "Image tag to pull"
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Find Comment
|
||||
uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v2
|
||||
id: fc
|
||||
with:
|
||||
issue-number: ${{ github.event.pull_request.number }}
|
||||
comment-author: "github-actions[bot]"
|
||||
body-includes: authentik PR Installation instructions
|
||||
- name: Create or update comment
|
||||
uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v2
|
||||
with:
|
||||
comment-id: ${{ steps.fc.outputs.comment-id }}
|
||||
issue-number: ${{ github.event.pull_request.number }}
|
||||
body: |
|
||||
authentik PR Installation instructions
|
||||
|
||||
<details>
|
||||
<summary>Instructions for docker-compose</summary>
|
||||
|
||||
Add the following block to your `.env` file:
|
||||
|
||||
```shell
|
||||
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
|
||||
AUTHENTIK_TAG=${{ inputs.tag }}
|
||||
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||
```
|
||||
|
||||
Afterwards, run the upgrade commands from the latest release notes.
|
||||
</details>
|
||||
<details>
|
||||
<summary>Instructions for Kubernetes</summary>
|
||||
|
||||
Add the following block to your `values.yml` file:
|
||||
|
||||
```yaml
|
||||
authentik:
|
||||
outposts:
|
||||
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||
global:
|
||||
image:
|
||||
repository: ghcr.io/goauthentik/dev-server
|
||||
tag: ${{ inputs.tag }}
|
||||
```
|
||||
|
||||
Afterwards, run the upgrade commands from the latest release notes.
|
||||
</details>
|
||||
edit-mode: replace
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
name: "Comment on PR"
|
||||
description: "Upserts one section of the shared CI comment on a pull request"
|
||||
|
||||
inputs:
|
||||
section:
|
||||
description: "Slug of the section to replace. Every other section is left alone."
|
||||
required: true
|
||||
body:
|
||||
description: "Markdown for the section"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
env:
|
||||
SECTION: "${{ inputs.section }}"
|
||||
BODY: "${{ inputs.body }}"
|
||||
with:
|
||||
script: |
|
||||
const marker = "<!-- ci-comment -->";
|
||||
const { SECTION, BODY } = process.env;
|
||||
const issue = { ...context.repo, issue_number: context.issue.number };
|
||||
|
||||
// Every CI job writes into the same comment, so find it by its marker and splice in
|
||||
// only this job's section, leaving the sections other jobs own untouched.
|
||||
// ponytail: read-modify-write, so two jobs finishing at the same instant can drop one
|
||||
// section update; the next push rewrites it. Retry on a changed body if that bites.
|
||||
const comments = await github.paginate(github.rest.issues.listComments, issue);
|
||||
const existing = comments.find(({ body }) => body?.startsWith(marker));
|
||||
|
||||
const section = new RegExp(`<!-- section:${SECTION} -->[\\s\\S]*?<!-- /section:${SECTION} -->`);
|
||||
const block = `<!-- section:${SECTION} -->\n${BODY.trim()}\n<!-- /section:${SECTION} -->`;
|
||||
const previous = existing?.body?.trim() || marker;
|
||||
const body = section.test(previous)
|
||||
? previous.replace(section, () => block)
|
||||
: `${previous}\n\n${block}`;
|
||||
|
||||
await (existing
|
||||
? github.rest.issues.updateComment({ ...issue, comment_id: existing.id, body })
|
||||
: github.rest.issues.createComment({ ...issue, body }));
|
||||
@@ -14,7 +14,7 @@ outputs:
|
||||
description: "Tag in the form gh-<safe-branch-name>"
|
||||
value: "${{ steps.compute-tags.outputs.tag-branch }}"
|
||||
tag-flux:
|
||||
description: "Tag in the form gh-<safe-branch-name>-<timestamp>-<short sha>"
|
||||
description: "Tag in the form gh-<timestamp>-<short sha>"
|
||||
value: "${{ steps.compute-tags.outputs.tag-flux }}"
|
||||
|
||||
runs:
|
||||
@@ -35,11 +35,11 @@ runs:
|
||||
branch_name = os.environ["GITHUB_REF"]
|
||||
if os.environ.get("GITHUB_HEAD_REF", "") != "":
|
||||
branch_name = os.environ["GITHUB_HEAD_REF"]
|
||||
safe_branch_name = re.sub(r"[^a-zA-Z0-9-.]", "-", branch_name.replace("refs/heads/", ""))
|
||||
safe_branch_name = re.sub(r"[^a-zA-Z0-9-]", "-", branch_name.replace("refs/heads/", ""))
|
||||
|
||||
tag_full = f"gh-{sha}"
|
||||
tag_branch = f"gh-{safe_branch_name}"
|
||||
tag_flux = f"gh-{safe_branch_name}-{int(time())}-{short_sha}"
|
||||
tag_flux = f"gh-{int(time())}-{short_sha}"
|
||||
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a+", encoding="utf-8") as _output:
|
||||
print(f"safe-branch-name={safe_branch_name}", file=_output)
|
||||
|
||||
@@ -20,12 +20,7 @@ runs:
|
||||
- name: Cleanup apt
|
||||
if: ${{ contains(inputs.dependencies, 'system') || contains(inputs.dependencies, 'python') }}
|
||||
shell: bash
|
||||
run: |
|
||||
# The runner image installs Chrome and leaves its apt source behind.
|
||||
# Nothing here installs from it, and a broken index there breaks the
|
||||
# apt-get update below. https://github.com/goauthentik/authentik/pull/25990
|
||||
sudo rm -f /etc/apt/sources.list.d/google-chrome.*
|
||||
sudo apt-get remove --purge man-db
|
||||
run: sudo apt-get remove --purge man-db
|
||||
- name: Install apt deps
|
||||
if: ${{ contains(inputs.dependencies, 'system') || contains(inputs.dependencies, 'python') }}
|
||||
uses: gerlero/apt-install@c0fa73fe5c4a22deecf6d629565be92a15dd2026
|
||||
@@ -42,7 +37,7 @@ runs:
|
||||
sudo rsync -a --delete /tmp/empty/ /usr/local/lib/android/
|
||||
- name: Install uv
|
||||
if: ${{ contains(inputs.dependencies, 'python') }}
|
||||
uses: astral-sh/setup-uv@1c37ad07a6a961277cf70c0d37d6f313000f5884 # v5
|
||||
uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v5
|
||||
with:
|
||||
enable-cache: true
|
||||
- name: Setup python
|
||||
@@ -57,26 +52,24 @@ runs:
|
||||
run: uv sync --all-extras --dev --locked
|
||||
- name: Setup rust (stable)
|
||||
if: ${{ contains(inputs.dependencies, 'rust') && !contains(inputs.dependencies, 'rust-nightly') }}
|
||||
uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
with:
|
||||
rustflags: ""
|
||||
- name: Setup rust (nightly)
|
||||
if: ${{ contains(inputs.dependencies, 'rust-nightly') }}
|
||||
uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
components: rustfmt
|
||||
rustflags: ""
|
||||
- name: Setup rust dependencies
|
||||
if: ${{ contains(inputs.dependencies, 'rust') }}
|
||||
uses: taiki-e/install-action@1168f6810a3cb30a3514bf5756a3b7f0422c6df8 # v2
|
||||
uses: taiki-e/install-action@07b4745e0c39a41822af610387492e3e53aa222b # v2
|
||||
with:
|
||||
tool: cargo-deny cargo-machete cargo-llvm-cov nextest
|
||||
- name: Setup pnpm
|
||||
if: ${{ contains(inputs.dependencies, 'node') }}
|
||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
with:
|
||||
package_json_file: ${{ inputs.working-directory }}package.json
|
||||
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
if: ${{ contains(inputs.dependencies, 'node') }}
|
||||
shell: bash
|
||||
@@ -85,17 +78,16 @@ runs:
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- name: Setup node (root, web)
|
||||
if: ${{ contains(inputs.dependencies, 'node') }}
|
||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: ${{ inputs.working-directory }}package.json
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
cache-dependency-path: |
|
||||
${{ inputs.working-directory }}pnpm-lock.yaml
|
||||
${{ inputs.working-directory }}web/pnpm-lock.yaml
|
||||
pnpm-lock.yaml
|
||||
web/pnpm-lock.yaml
|
||||
- name: Install node dependencies (root, web)
|
||||
if: ${{ contains(inputs.dependencies, 'node') }}
|
||||
shell: bash
|
||||
working-directory: ${{ inputs.working-directory }}
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
@@ -104,12 +96,8 @@ runs:
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v5
|
||||
with:
|
||||
go-version-file: "${{ inputs.working-directory }}go.mod"
|
||||
cache-dependency-path: "${{ inputs.working-directory }}go.mod"
|
||||
- name: Setup docker cache
|
||||
if: ${{ contains(inputs.dependencies, 'runtime') }}
|
||||
# The post step `docker save`s every new image, but digest-pinned images (e2e,
|
||||
# kind) list without a tag and fail. Jobs share the key, so another job saves it.
|
||||
continue-on-error: true
|
||||
uses: AndreKurait/docker-cache@7a3887908bdb97935395833df69b060cfcca0f7f
|
||||
with:
|
||||
key: docker-images-${{ runner.os }}-${{ hashFiles('.github/actions/setup/compose.yml', 'Makefile') }}-${{ inputs.postgresql_version }}
|
||||
|
||||
@@ -10,12 +10,12 @@ inputs:
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
|
||||
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v5
|
||||
with:
|
||||
files: ${{ inputs.files }}
|
||||
flags: ${{ inputs.flags }}
|
||||
use_oidc: true
|
||||
- uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
|
||||
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v5
|
||||
with:
|
||||
files: ${{ inputs.files }}
|
||||
flags: ${{ inputs.flags }}
|
||||
|
||||
+65
-68
@@ -8,7 +8,7 @@ updates:
|
||||
# Required to update composite actions
|
||||
# https://github.com/dependabot/dependabot-core/issues/6704
|
||||
- /.github/actions/setup
|
||||
- /.github/actions/comment-pr
|
||||
- /.github/actions/comment-pr-instructions
|
||||
- /.github/actions/test-results
|
||||
schedule:
|
||||
interval: daily
|
||||
@@ -20,13 +20,6 @@ updates:
|
||||
- dependencies
|
||||
cooldown:
|
||||
default-days: 3
|
||||
groups:
|
||||
codeql:
|
||||
patterns:
|
||||
- "github/codeql-action/*"
|
||||
regclient:
|
||||
patterns:
|
||||
- "regclient/actions/*"
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -95,17 +88,13 @@ updates:
|
||||
|
||||
#endregion
|
||||
|
||||
#region Web & Documentation
|
||||
#region Web
|
||||
|
||||
# One entry for every workspace root that shares the pnpm catalog pins, so a
|
||||
# group bump lands in all of them in a single PR. Groups don't span entries,
|
||||
# and `scripts/node/lint-catalogs.ts` fails when the roots drift apart.
|
||||
- package-ecosystem: npm
|
||||
directories:
|
||||
- "/"
|
||||
- "/web"
|
||||
- "/web/packages/*"
|
||||
- "/website"
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "04:00"
|
||||
@@ -126,20 +115,13 @@ updates:
|
||||
patterns:
|
||||
- "@babel/*"
|
||||
- "babel-*"
|
||||
oxc:
|
||||
eslint:
|
||||
patterns:
|
||||
- "@oxc-project/*"
|
||||
- "oxc-*"
|
||||
- "oxfmt"
|
||||
- "oxlint"
|
||||
lint:
|
||||
patterns:
|
||||
# Rule sources for @goauthentik/oxlint-config; oxlint reads their rule
|
||||
# definitions, so they move in lockstep with it.
|
||||
- "eslint-plugin-lit"
|
||||
- "eslint-plugin-wc"
|
||||
- "stylelint"
|
||||
- "stylelint-*"
|
||||
- "@eslint/*"
|
||||
- "@typescript-eslint/*"
|
||||
- "eslint-*"
|
||||
- "eslint"
|
||||
- "typescript-eslint"
|
||||
storybook:
|
||||
patterns:
|
||||
- "@storybook/*"
|
||||
@@ -159,17 +141,6 @@ updates:
|
||||
patterns:
|
||||
- "@swc/*"
|
||||
- "swc-*"
|
||||
# Listed before `goauthentik` so the config package moves with Docusaurus.
|
||||
docusaurus:
|
||||
patterns:
|
||||
- "@docusaurus/*"
|
||||
- "@goauthentik/docusaurus-config"
|
||||
- "docusaurus-plugin-openapi-docs"
|
||||
- "docusaurus-theme-openapi-docs"
|
||||
website-build:
|
||||
patterns:
|
||||
- "lightningcss*"
|
||||
- "@rspack/binding*"
|
||||
goauthentik:
|
||||
patterns:
|
||||
- "@goauthentik/*"
|
||||
@@ -186,15 +157,12 @@ updates:
|
||||
|
||||
- package-ecosystem: npm
|
||||
directories:
|
||||
- "/packages/docusaurus-config"
|
||||
- "/packages/esbuild-plugin-live-reload"
|
||||
- "/packages/fonts"
|
||||
- "/packages/geo"
|
||||
- "/packages/logger-js"
|
||||
- "/packages/oxfmt-config"
|
||||
- "/packages/oxlint-config"
|
||||
- "/packages/theme"
|
||||
- "/packages/prettier-config"
|
||||
- "/packages/tsconfig"
|
||||
- "/packages/docusaurus-config"
|
||||
- "/packages/eslint-config"
|
||||
- "/packages/logger-js"
|
||||
- "/packages/esbuild-plugin-live-reload"
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "04:00"
|
||||
@@ -215,20 +183,13 @@ updates:
|
||||
patterns:
|
||||
- "@babel/*"
|
||||
- "babel-*"
|
||||
oxc:
|
||||
eslint:
|
||||
patterns:
|
||||
- "@oxc-project/*"
|
||||
- "oxc-*"
|
||||
- "oxfmt"
|
||||
- "oxlint"
|
||||
lint:
|
||||
patterns:
|
||||
# Rule sources for @goauthentik/oxlint-config; oxlint reads their rule
|
||||
# definitions, so they move in lockstep with it.
|
||||
- "eslint-plugin-lit"
|
||||
- "eslint-plugin-wc"
|
||||
- "stylelint"
|
||||
- "stylelint-*"
|
||||
- "@eslint/*"
|
||||
- "@typescript-eslint/*"
|
||||
- "eslint-*"
|
||||
- "eslint"
|
||||
- "typescript-eslint"
|
||||
storybook:
|
||||
patterns:
|
||||
- "@storybook/*"
|
||||
@@ -260,7 +221,51 @@ updates:
|
||||
|
||||
#endregion
|
||||
|
||||
#region AWS Lifecycle
|
||||
# #region Documentation
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: "/website"
|
||||
schedule:
|
||||
interval: daily
|
||||
time: "04:00"
|
||||
open-pull-requests-limit: 10
|
||||
commit-message:
|
||||
prefix: "website:"
|
||||
labels:
|
||||
- dependencies
|
||||
cooldown:
|
||||
default-days: 7
|
||||
semver-major-days: 14
|
||||
semver-patch-days: 3
|
||||
groups:
|
||||
docusaurus:
|
||||
patterns:
|
||||
- "@docusaurus/*"
|
||||
- "@goauthentik/docusaurus-config"
|
||||
- "docusaurus-plugin-openapi-docs"
|
||||
- "docusaurus-theme-openapi-docs"
|
||||
build:
|
||||
patterns:
|
||||
- "@swc/*"
|
||||
- "swc-*"
|
||||
- "lightningcss*"
|
||||
- "@rspack/binding*"
|
||||
goauthentik:
|
||||
patterns:
|
||||
- "@goauthentik/eslint-config"
|
||||
- "@goauthentik/prettier-config"
|
||||
- "@goauthentik/tsconfig"
|
||||
eslint:
|
||||
patterns:
|
||||
- "@eslint/*"
|
||||
- "@typescript-eslint/*"
|
||||
- "eslint-*"
|
||||
- "eslint"
|
||||
- "typescript-eslint"
|
||||
|
||||
#endregion
|
||||
|
||||
# AWS Lifecycle
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: "/lifecycle/aws"
|
||||
@@ -307,9 +312,6 @@ updates:
|
||||
types:
|
||||
patterns:
|
||||
- types-*
|
||||
opentelemetry:
|
||||
patterns:
|
||||
- opentelemetry-*
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -329,19 +331,14 @@ updates:
|
||||
- dependencies
|
||||
cooldown:
|
||||
default-days: 3
|
||||
groups:
|
||||
pnpm:
|
||||
patterns:
|
||||
- "*pnpm/pnpm"
|
||||
- package-ecosystem: docker-compose
|
||||
directories:
|
||||
- /packages/client-go
|
||||
- /packages/client-rust
|
||||
- /packages/client-ts
|
||||
- /scripts
|
||||
- /tests
|
||||
- /tests/compose
|
||||
- /tests/e2e
|
||||
- /tests/integration
|
||||
- /tests/openid_conformance
|
||||
schedule:
|
||||
interval: daily
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
version: "2"
|
||||
linters:
|
||||
exclusions:
|
||||
paths:
|
||||
- '(^|/)node_modules/'
|
||||
@@ -24,4 +24,3 @@ Use `closes #N` to auto-close an issue on merge. Use `refs #N` for related issue
|
||||
|
||||
- [ ] The project has been linted, built, and tested (`make all`)
|
||||
- [ ] The documentation has been updated and formatted (`make docs`)
|
||||
- [ ] I have read the [AI usage policy](https://github.com/goauthentik/authentik/blob/main/AI_POLICY.md).
|
||||
@@ -15,45 +15,3 @@ git:
|
||||
source_file: locale/en/LC_MESSAGES/django.po
|
||||
# path expression to translation files, must contain <lang> placeholder
|
||||
translation_files_expression: "locale/<lang>/LC_MESSAGES/django.po"
|
||||
|
||||
settings:
|
||||
# Generated from locales.yaml by `make gen-locales`. Do not edit by hand.
|
||||
language_mapping:
|
||||
ar_AA: ar
|
||||
bg_BG: bg-BG
|
||||
bn_BD: bn-BD
|
||||
ca_ES: ca-ES
|
||||
cs_CZ: cs-CZ
|
||||
sk_SK: sk-SK
|
||||
cy_GB: cy-GB
|
||||
da_DK: da-DK
|
||||
de_DE: de-DE
|
||||
el_GR: el-GR
|
||||
es_ES: es-ES
|
||||
eu_ES: eu-ES
|
||||
fa_IR: fa-IR
|
||||
fi_FI: fi-FI
|
||||
fr_FR: fr-FR
|
||||
gl_ES: gl-ES
|
||||
hr_HR: hr-HR
|
||||
hu_HU: hu-HU
|
||||
it_IT: it-IT
|
||||
ja_JP: ja-JP
|
||||
ka_GE: ka-GE
|
||||
ko_KR: ko-KR
|
||||
lt_LT: lt-LT
|
||||
lv_LV: lv-LV
|
||||
ms_MY: ms-MY
|
||||
no_NO: nb-NO
|
||||
nl_NL: nl-NL
|
||||
pl_PL: pl-PL
|
||||
pt_BR: pt-BR
|
||||
pt_PT: pt-PT
|
||||
ro_RO: ro-RO
|
||||
ru_RU: ru-RU
|
||||
sl_SI: sl-SI
|
||||
sv_SE: sv-SE
|
||||
th_TH: th-TH
|
||||
tr_TR: tr-TR
|
||||
uk_UA: uk-UA
|
||||
vi_VN: vi-VN
|
||||
@@ -60,16 +60,16 @@ jobs:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
ref: "${{ inputs.ref }}"
|
||||
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||
- uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
|
||||
- uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
|
||||
- uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
- if: "${{ inputs.should-cache }}"
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- id: build
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
|
||||
with:
|
||||
# inputs
|
||||
context: .
|
||||
@@ -91,7 +91,7 @@ jobs:
|
||||
# params
|
||||
platforms: "linux/${{ inputs.image-arch }}"
|
||||
- id: upload
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
|
||||
with:
|
||||
name: "container-build-${{ inputs.image-name }}-${{ inputs.image-arch }}"
|
||||
path: build/
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
uses: ./.github/workflows/_reusable-container-build-single.yml
|
||||
secrets: inherit
|
||||
with:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
ref: "${{ inputs.ref }}"
|
||||
image-name: "${{ inputs.image-name }}"
|
||||
image-arch: amd64
|
||||
@@ -42,12 +42,11 @@ jobs:
|
||||
image-build-args: "${{ inputs.image-build-args }}"
|
||||
should-cache: "${{ inputs.should-cache }}"
|
||||
cache-suffix: "${{ inputs.cache-suffix }}"
|
||||
|
||||
build-arm64:
|
||||
uses: ./.github/workflows/_reusable-container-build-single.yml
|
||||
secrets: inherit
|
||||
with:
|
||||
runs-on: ubuntu-26.04-arm
|
||||
runs-on: ubuntu-24.04-arm
|
||||
ref: "${{ inputs.ref }}"
|
||||
image-name: "${{ inputs.image-name }}"
|
||||
image-arch: arm64
|
||||
@@ -55,181 +54,30 @@ jobs:
|
||||
image-build-args: "${{ inputs.image-build-args }}"
|
||||
should-cache: "${{ inputs.should-cache }}"
|
||||
cache-suffix: "${{ inputs.cache-suffix }}"
|
||||
|
||||
merge:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build-amd64
|
||||
- build-arm64
|
||||
steps:
|
||||
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
- uses: regclient/actions/regctl-installer@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
artifact-ids: "${{ needs.build-amd64.outputs.artifact-id }},${{ needs.build-arm64.outputs.artifact-id }}"
|
||||
merge-multiple: true
|
||||
|
||||
- name: Merge and flatten architecture indexes
|
||||
shell: bash
|
||||
- name: merge
|
||||
run: |
|
||||
set -euo pipefail
|
||||
regctl image import ocidir://${{ inputs.image-name }}-amd64:build container/${{ inputs.image-name }}-amd64.oci.tar
|
||||
regctl image import ocidir://${{ inputs.image-name }}-arm64:build container/${{ inputs.image-name }}-arm64.oci.tar
|
||||
|
||||
image_name="${{ inputs.image-name }}"
|
||||
target="ocidir://${image_name}:build"
|
||||
regctl index create ocidir://${{ inputs.image-name }}:build
|
||||
|
||||
regctl image import \
|
||||
"ocidir://${image_name}-amd64:build" \
|
||||
"container/${image_name}-amd64.oci.tar"
|
||||
|
||||
regctl image import \
|
||||
"ocidir://${image_name}-arm64:build" \
|
||||
"container/${image_name}-arm64.oci.tar"
|
||||
|
||||
regctl index create "${target}"
|
||||
|
||||
add_platform() {
|
||||
local arch="$1"
|
||||
local source="ocidir://${image_name}-${arch}:build"
|
||||
local source_index
|
||||
local image_digest
|
||||
local attestation_digest
|
||||
|
||||
source_index="$(
|
||||
regctl manifest get "${source}" --format raw-body
|
||||
)"
|
||||
|
||||
# Select the runnable image manifest from the architecture index.
|
||||
image_digest="$(
|
||||
jq -er --arg arch "${arch}" '
|
||||
[
|
||||
.manifests[]
|
||||
| select(
|
||||
.mediaType
|
||||
== "application/vnd.oci.image.manifest.v1+json"
|
||||
and .platform.os == "linux"
|
||||
and .platform.architecture == $arch
|
||||
)
|
||||
| .digest
|
||||
]
|
||||
| if length == 1 then .[0]
|
||||
else error(
|
||||
"expected exactly one linux/" + $arch
|
||||
+ " image manifest"
|
||||
)
|
||||
end
|
||||
' <<<"${source_index}"
|
||||
)"
|
||||
|
||||
# Select the BuildKit attestation associated with that image.
|
||||
attestation_digest="$(
|
||||
jq -er --arg image_digest "${image_digest}" '
|
||||
[
|
||||
.manifests[]
|
||||
| select(
|
||||
.mediaType
|
||||
== "application/vnd.oci.image.manifest.v1+json"
|
||||
and .platform.os == "unknown"
|
||||
and .platform.architecture == "unknown"
|
||||
and .annotations["vnd.docker.reference.type"]
|
||||
== "attestation-manifest"
|
||||
and .annotations["vnd.docker.reference.digest"]
|
||||
== $image_digest
|
||||
)
|
||||
| .digest
|
||||
]
|
||||
| if length == 1 then .[0]
|
||||
else error(
|
||||
"expected exactly one attestation for "
|
||||
+ $image_digest
|
||||
)
|
||||
end
|
||||
' <<<"${source_index}"
|
||||
)"
|
||||
|
||||
# Add the runnable image manifest directly to the final index.
|
||||
regctl index add "${target}" \
|
||||
--ref "${source}@${image_digest}" \
|
||||
--desc-platform "linux/${arch}"
|
||||
|
||||
# Add the associated attestation directly beside the image.
|
||||
regctl index add "${target}" \
|
||||
--ref "${source}@${attestation_digest}" \
|
||||
--desc-platform "unknown/unknown" \
|
||||
--desc-annotation \
|
||||
"vnd.docker.reference.type=attestation-manifest" \
|
||||
--desc-annotation \
|
||||
"vnd.docker.reference.digest=${image_digest}"
|
||||
}
|
||||
|
||||
add_platform amd64
|
||||
add_platform arm64
|
||||
|
||||
final_index="$(
|
||||
regctl manifest get "${target}" --format raw-body
|
||||
)"
|
||||
|
||||
# Ensure the result is a flat index containing two runnable image
|
||||
# manifests and their two attestations, with no nested OCI indexes.
|
||||
jq -e '
|
||||
.mediaType == "application/vnd.oci.image.index.v1+json"
|
||||
and (.manifests | length == 4)
|
||||
and (
|
||||
[.manifests[].mediaType]
|
||||
| all(
|
||||
. == "application/vnd.oci.image.manifest.v1+json"
|
||||
)
|
||||
)
|
||||
and (
|
||||
[
|
||||
.manifests[]
|
||||
| select(.platform.os == "linux")
|
||||
| .platform.architecture
|
||||
]
|
||||
| sort
|
||||
== ["amd64", "arm64"]
|
||||
)
|
||||
and (
|
||||
[
|
||||
.manifests[]
|
||||
| select(
|
||||
.platform.os == "unknown"
|
||||
and .platform.architecture == "unknown"
|
||||
and .annotations["vnd.docker.reference.type"]
|
||||
== "attestation-manifest"
|
||||
)
|
||||
]
|
||||
| length == 2
|
||||
)
|
||||
and (
|
||||
(
|
||||
[
|
||||
.manifests[]
|
||||
| select(.platform.os == "linux")
|
||||
| .digest
|
||||
]
|
||||
| sort
|
||||
)
|
||||
==
|
||||
(
|
||||
[
|
||||
.manifests[]
|
||||
| select(
|
||||
.platform.os == "unknown"
|
||||
and .platform.architecture == "unknown"
|
||||
)
|
||||
| .annotations["vnd.docker.reference.digest"]
|
||||
]
|
||||
| sort
|
||||
)
|
||||
)
|
||||
' <<<"${final_index}"
|
||||
regctl index add ocidir://${{ inputs.image-name }}:build --ref ocidir://${{ inputs.image-name }}-amd64:build --desc-platform linux/amd64
|
||||
regctl index add ocidir://${{ inputs.image-name }}:build --ref ocidir://${{ inputs.image-name }}-arm64:build --desc-platform linux/arm64
|
||||
|
||||
mkdir -p build/container/
|
||||
|
||||
regctl image export \
|
||||
"${target}" \
|
||||
"build/container/${image_name}.oci.tar"
|
||||
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
|
||||
regctl image export ocidir://${{ inputs.image-name }}:build build/container/${{ inputs.image-name }}.oci.tar
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
|
||||
with:
|
||||
name: "container-build-${{ inputs.image-name }}"
|
||||
path: build/
|
||||
|
||||
@@ -12,26 +12,22 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
command:
|
||||
- check
|
||||
- prettier-check
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -45,16 +41,16 @@ jobs:
|
||||
- name: Lint
|
||||
run: pnpm --dir website run ${{ matrix.command }}
|
||||
build:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -79,28 +75,28 @@ jobs:
|
||||
env:
|
||||
NODE_ENV: production
|
||||
run: pnpm run build:api
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
|
||||
with:
|
||||
name: api-docs
|
||||
path: website/api/build
|
||||
retention-days: 7
|
||||
deploy:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- lint
|
||||
- build
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
name: api-docs
|
||||
path: website/api/build
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
|
||||
@@ -12,10 +12,6 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
env:
|
||||
POSTGRES_DB: authentik
|
||||
POSTGRES_USER: authentik
|
||||
@@ -23,17 +19,17 @@ env:
|
||||
|
||||
jobs:
|
||||
check-changes-applied:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -48,8 +44,8 @@ jobs:
|
||||
if: always()
|
||||
needs:
|
||||
- check-changes-applied
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
|
||||
- uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
@@ -13,7 +13,7 @@ env:
|
||||
|
||||
jobs:
|
||||
publish-source-docs:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
@@ -22,16 +22,9 @@ jobs:
|
||||
- name: generate docs
|
||||
run: |
|
||||
uv run make migrate
|
||||
uv run python -m manage build_source_docs
|
||||
- uses: nwtgck/actions-netlify@d22a32a27c918fe470bbc562e984f80ec48c2668 # v4.0.0
|
||||
id: netlify
|
||||
with:
|
||||
publish-dir: "./source_docs"
|
||||
production-deploy: true
|
||||
enable-commit-comment: false
|
||||
enable-pull-request-comment: false
|
||||
enable-commit-status: false
|
||||
enable-github-deployment: false
|
||||
uv run ak build_source_docs
|
||||
- name: Publish
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: eb246b7b-1d83-4f69-89f7-01a936b4ca59
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
run: pnpm dlx netlify-cli deploy --dir=source_docs --prod
|
||||
@@ -12,28 +12,24 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NODE_ENV: production
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
command:
|
||||
- check
|
||||
- prettier-check
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -47,17 +43,17 @@ jobs:
|
||||
- name: Lint
|
||||
run: pnpm --dir website run ${{ matrix.command }}
|
||||
build-docs:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NODE_ENV: production
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
name: Setup Node.js
|
||||
with:
|
||||
node-version-file: package.json
|
||||
@@ -72,17 +68,17 @@ jobs:
|
||||
- name: Build Documentation via Docusaurus
|
||||
run: pnpm --dir website run build
|
||||
build-integrations:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NODE_ENV: production
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -96,7 +92,7 @@ jobs:
|
||||
- name: Build Integrations via Docusaurus
|
||||
run: pnpm --dir website run build:integrations
|
||||
build-container:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed to upload container images to ghcr.io
|
||||
packages: write
|
||||
@@ -111,18 +107,18 @@ jobs:
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
- name: Login to Container Registry
|
||||
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build Docker Image
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
|
||||
with:
|
||||
file: website/Dockerfile
|
||||
context: .
|
||||
@@ -141,8 +137,8 @@ jobs:
|
||||
- build-docs
|
||||
- build-integrations
|
||||
- build-container
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
|
||||
- uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
@@ -13,14 +13,14 @@ on:
|
||||
|
||||
jobs:
|
||||
test-container:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
version:
|
||||
- docs
|
||||
- version-2026-2
|
||||
- version-2026-5
|
||||
- version-2026-8
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- run: |
|
||||
|
||||
+118
-233
@@ -12,10 +12,6 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
env:
|
||||
POSTGRES_DB: authentik
|
||||
POSTGRES_USER: authentik
|
||||
@@ -29,7 +25,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
build-compute-tags:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
safe-branch-name: "${{ steps.compute-tags.outputs.safe-branch-name }}"
|
||||
tag-full: "${{ steps.compute-tags.outputs.tag-full }}"
|
||||
@@ -69,7 +65,9 @@ jobs:
|
||||
image-dockerfile: "lifecycle/container/${{ matrix.dockerfile }}"
|
||||
image-build-args: |
|
||||
GIT_BUILD_HASH=${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
should-cache: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
should-cache: "${{ github.event_name == 'push' || (github.event_name ==
|
||||
'pull_request' && github.event.pull_request.head.repo.full_name ==
|
||||
github.repository) }}"
|
||||
cache-suffix: "-${{ needs.build-compute-tags.outputs.safe-branch-name }}"
|
||||
lint:
|
||||
strategy:
|
||||
@@ -84,10 +82,6 @@ jobs:
|
||||
deps: node
|
||||
- job: catalogs
|
||||
deps: node
|
||||
- job: locales
|
||||
deps: python
|
||||
- job: oxlint-fixtures
|
||||
deps: node
|
||||
- job: pending-migrations
|
||||
deps: python,runtime
|
||||
- job: ruff
|
||||
@@ -102,23 +96,17 @@ jobs:
|
||||
deps: rust
|
||||
- job: rustfmt
|
||||
deps: rust-nightly
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
dependencies: ${{ matrix.deps }}
|
||||
- name: Create required files
|
||||
run: |
|
||||
mkdir -p web/dist/standalone/loading
|
||||
for f in web/robots.txt web/security.txt web/dist/standalone/loading/startup.html; do
|
||||
echo empty > "$f"
|
||||
done
|
||||
- name: run job
|
||||
run: make ci-lint-${{ matrix.job }}
|
||||
test-gen:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
@@ -132,9 +120,10 @@ jobs:
|
||||
- name: generate API clients
|
||||
run: make gen-clients
|
||||
- name: ensure schema is up-to-date
|
||||
run: git diff --exit-code -- schema.yml blueprints/schema.json packages/client-go packages/client-rust packages/client-ts
|
||||
run: git diff --exit-code -- schema.yml blueprints/schema.json
|
||||
packages/client-go packages/client-rust packages/client-ts
|
||||
test-migrations:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
@@ -142,7 +131,7 @@ jobs:
|
||||
- name: run migrations
|
||||
run: uv run python -m lifecycle.migrate
|
||||
test-make-seed:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: seed
|
||||
run: |
|
||||
@@ -150,8 +139,9 @@ jobs:
|
||||
outputs:
|
||||
seed: ${{ steps.seed.outputs.seed }}
|
||||
test-migrations-from-stable:
|
||||
name: test-migrations-from-stable - PostgreSQL ${{ matrix.psql }} - Run ${{ matrix.run_id }}/10
|
||||
runs-on: ubuntu-26.04
|
||||
name: test-migrations-from-stable - PostgreSQL ${{ matrix.psql }} - Run ${{
|
||||
matrix.run_id }}/5
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: test-make-seed
|
||||
strategy:
|
||||
@@ -160,9 +150,7 @@ jobs:
|
||||
psql:
|
||||
- 14-alpine
|
||||
- 18-alpine
|
||||
run_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
env:
|
||||
AUTHENTIK_MIGRATIONS__DANGEROUSLY_ALLOW_MULTIPLE_MAJOR_VERSION_UPGRADES: "true"
|
||||
run_id: [1, 2, 3, 4, 5]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
@@ -225,7 +213,7 @@ jobs:
|
||||
AUTHENTIK_POSTGRESQL__TEST__NAME: authentik
|
||||
CI_TEST_SEED: ${{ needs.test-make-seed.outputs.seed }}
|
||||
CI_RUN_ID: ${{ matrix.run_id }}
|
||||
CI_TOTAL_RUNS: "10"
|
||||
CI_TOTAL_RUNS: "5"
|
||||
run: |
|
||||
uv run make ci-test
|
||||
- uses: ./.github/actions/test-results
|
||||
@@ -233,8 +221,8 @@ jobs:
|
||||
with:
|
||||
flags: unit-migrate
|
||||
test-unittest:
|
||||
name: test-unittest - PostgreSQL ${{ matrix.psql }} - Run ${{ matrix.run_id }}/10
|
||||
runs-on: ubuntu-26.04
|
||||
name: test-unittest - PostgreSQL ${{ matrix.psql }} - Run ${{ matrix.run_id }}/5
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: test-make-seed
|
||||
strategy:
|
||||
@@ -243,7 +231,7 @@ jobs:
|
||||
psql:
|
||||
- 14-alpine
|
||||
- 18-alpine
|
||||
run_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
run_id: [1, 2, 3, 4, 5]
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
@@ -254,7 +242,7 @@ jobs:
|
||||
env:
|
||||
CI_TEST_SEED: ${{ needs.test-make-seed.outputs.seed }}
|
||||
CI_RUN_ID: ${{ matrix.run_id }}
|
||||
CI_TOTAL_RUNS: "10"
|
||||
CI_TOTAL_RUNS: "5"
|
||||
run: |
|
||||
uv run make ci-test
|
||||
- uses: ./.github/actions/test-results
|
||||
@@ -262,14 +250,14 @@ jobs:
|
||||
with:
|
||||
flags: unit
|
||||
test-integration:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
- name: Create k8s Kind Cluster
|
||||
uses: helm/kind-action@1544676c07bb3570fcb70166beaa07c4528fd4aa # v1.15.1
|
||||
uses: helm/kind-action@ef37e7f390d99f746eb8b610417061a60e82a6cc # v1.14.0
|
||||
- name: run integration
|
||||
run: |
|
||||
uv run coverage run manage.py test tests/integration
|
||||
@@ -281,7 +269,7 @@ jobs:
|
||||
flags: integration
|
||||
test-e2e:
|
||||
name: test-e2e (${{ matrix.job.name }})
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs:
|
||||
- build-compute-tags
|
||||
@@ -290,9 +278,6 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
job:
|
||||
- name: proxy
|
||||
glob: tests/e2e/test_provider_proxy*
|
||||
profiles: selenium
|
||||
- name: oauth
|
||||
glob: tests/e2e/test_provider_oauth2* tests/e2e/test_source_oauth*
|
||||
profiles: selenium
|
||||
@@ -321,7 +306,7 @@ jobs:
|
||||
glob: tests/e2e/test_endpoints_*
|
||||
profiles: selenium
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
pattern: container-build-*-amd64
|
||||
merge-multiple: true
|
||||
@@ -340,12 +325,12 @@ jobs:
|
||||
COMPOSE_PROFILES: ${{ matrix.job.profiles }}
|
||||
run: |
|
||||
docker compose -f tests/e2e/compose.yml up -d --quiet-pull
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -357,9 +342,11 @@ jobs:
|
||||
if: contains(matrix.job.profiles, 'selenium')
|
||||
with:
|
||||
path: web/dist
|
||||
key: ${{ runner.os }}-web-${{ hashFiles('web/package.json', 'web/pnpm-lock.yaml', 'pnpm-lock.yaml', 'web/src/**', 'web/packages/sfe/src/**') }}-b
|
||||
key: ${{ runner.os }}-web-${{ hashFiles('web/pnpm-lock.yaml', 'pnpm-lock.yaml',
|
||||
'web/src/**', 'web/packages/sfe/src/**') }}-b
|
||||
- name: prepare web ui
|
||||
if: steps.cache-web.outputs.cache-hit != 'true' && contains(matrix.job.profiles, 'selenium')
|
||||
if: steps.cache-web.outputs.cache-hit != 'true' && contains(matrix.job.profiles,
|
||||
'selenium')
|
||||
working-directory: web
|
||||
env:
|
||||
NODE_ENV: "production"
|
||||
@@ -376,9 +363,73 @@ jobs:
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
flags: e2e
|
||||
test-e2e-container:
|
||||
name: test-e2e-container (${{ matrix.name }})
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs:
|
||||
- build-compute-tags
|
||||
- build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
name:
|
||||
- provider_proxy
|
||||
- flows
|
||||
steps:
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
pattern: container-build-*-amd64
|
||||
merge-multiple: true
|
||||
- name: Load Docker images
|
||||
run: |
|
||||
for image in server proxy ldap radius rac; do
|
||||
skopeo copy "oci-archive:container/${image}-amd64.oci.tar" "docker-daemon:authentik.invalid/goauthentik/dev-${image}:${{ needs.build-compute-tags.outputs.tag-full }}"
|
||||
skopeo copy "oci-archive:container/${image}-amd64.oci.tar" "docker-daemon:authentik.invalid/goauthentik/dev-${image}:${{ needs.build-compute-tags.outputs.tag-branch }}"
|
||||
done
|
||||
rm -rf container/
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
dependencies: python,rust
|
||||
- name: Pull dependencies
|
||||
run: |
|
||||
COMPOSE_PROFILES="$(docker compose -f tests/compose/compose.utils.yml -f tests/compose/compose.proxies.yml config --profiles | paste -sd, -)" \
|
||||
docker compose \
|
||||
-f tests/compose/compose.utils.yml \
|
||||
-f tests/compose/compose.proxies.yml \
|
||||
pull
|
||||
- name: Run tests
|
||||
run: |
|
||||
# Currently runs only two jobs concurrently since our runners are a bit small for more
|
||||
cargo llvm-cov --no-report nextest \
|
||||
--package authentik-tests \
|
||||
--success-output final \
|
||||
--failure-output final \
|
||||
--no-output-indent \
|
||||
--retries 3 \
|
||||
--jobs 2 \
|
||||
--no-fail-fast \
|
||||
--filterset 'kind(test) & binary_id(#authentik-tests::e2e_${{ matrix.name }}*)'
|
||||
cargo llvm-cov report --codecov --output-path target/llvm-cov-target/rust.json
|
||||
- name: Merge coverage files
|
||||
run: |
|
||||
uv run coverage combine ./coverage/*
|
||||
uv run coverage report
|
||||
uv run coverage xml
|
||||
- uses: ./.github/actions/test-results
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
flags: e2e-container
|
||||
- uses: ./.github/actions/test-results
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
files: target/llvm-cov-target/rust.json
|
||||
flags: e2e-container-rust
|
||||
test-openid-conformance:
|
||||
name: test-openid-conformance (${{ matrix.job.name }})
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -414,7 +465,8 @@ jobs:
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v4
|
||||
with:
|
||||
path: web/dist
|
||||
key: ${{ runner.os }}-web-${{ hashFiles('web/pnpm-lock.yaml', 'web/src/**', 'web/packages/sfe/src/**') }}-b
|
||||
key: ${{ runner.os }}-web-${{ hashFiles('web/pnpm-lock.yaml', 'web/src/**',
|
||||
'web/packages/sfe/src/**') }}-b
|
||||
- name: prepare web ui
|
||||
if: steps.cache-web.outputs.cache-hit != 'true'
|
||||
env:
|
||||
@@ -433,166 +485,28 @@ jobs:
|
||||
with:
|
||||
flags: conformance
|
||||
- if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: conformance-certification-${{ matrix.job.name }}
|
||||
path: tests/openid_conformance/exports/
|
||||
test-rust:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
dependencies: system,python,rust,runtime
|
||||
- name: Prepare database
|
||||
run: |
|
||||
uv run make migrate
|
||||
- name: Create required files
|
||||
run: |
|
||||
mkdir -p web/dist/standalone/loading
|
||||
for f in web/robots.txt web/security.txt web/dist/standalone/loading/startup.html; do
|
||||
echo empty > "$f"
|
||||
done
|
||||
dependencies: rust,runtime
|
||||
- name: run tests
|
||||
run: |
|
||||
cargo llvm-cov --no-report nextest --workspace
|
||||
cargo llvm-cov --no-report nextest --workspace --no-fail-fast --filterset 'kind(lib) | kind(proc-macro) | kind(bin) | kind(example)'
|
||||
cargo llvm-cov report --codecov --output-path target/llvm-cov-target/rust.json
|
||||
- uses: ./.github/actions/test-results
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
files: target/llvm-cov-target/rust.json
|
||||
flags: rust
|
||||
- if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: test-rust
|
||||
path: target/llvm-cov-target/rust.json
|
||||
test-e2e-web:
|
||||
name: test-e2e (web)
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 60
|
||||
needs:
|
||||
- build
|
||||
permissions:
|
||||
contents: read
|
||||
# Required so the "Comment on PR" step can create and update the run's
|
||||
# shared comment through the issues API.
|
||||
pull-requests: write
|
||||
# Required so the codecov upload below can mint an OIDC token.
|
||||
id-token: write
|
||||
services:
|
||||
# setup-authentik brings authentik up through the published compose file,
|
||||
# which pulls its image — a locally loaded tag is not pullable. Pushing the
|
||||
# image built by `build` here first gives compose something to pull.
|
||||
registry:
|
||||
image: registry:2
|
||||
ports:
|
||||
- 5000:5000
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
dependencies: node
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
with:
|
||||
name: container-build-server-amd64
|
||||
- name: Push the built server image to the local registry
|
||||
run: | # shell
|
||||
skopeo copy --dest-tls-verify=false \
|
||||
"oci-archive:container/server-amd64.oci.tar" \
|
||||
"docker://127.0.0.1:5000/server:e2e"
|
||||
- name: Resolve Playwright version
|
||||
id: playwright-version
|
||||
working-directory: web
|
||||
run: | # shell
|
||||
version=$(node -p "require('@playwright/test/package.json').version")
|
||||
if [ -z "$version" ]; then
|
||||
echo "Failed to resolve @playwright/test version" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||
- name: Cache Playwright browsers
|
||||
id: playwright-cache
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ steps.playwright-version.outputs.version }}
|
||||
- name: Install Playwright browsers
|
||||
working-directory: web
|
||||
run: | # shell
|
||||
if [ "${{ steps.playwright-cache.outputs.cache-hit }}" = "true" ]; then
|
||||
pnpm exec playwright install-deps chromium
|
||||
else
|
||||
pnpm exec playwright install --with-deps chromium
|
||||
fi
|
||||
- name: Start authentik
|
||||
id: authentik
|
||||
uses: goauthentik/action-setup-authentik@d6c4c8f677abc2a9839b855100ab6c56eddacab5 # v3.4.0
|
||||
with:
|
||||
version: 127.0.0.1:5000/server:e2e
|
||||
blueprints_path: web/test/blueprints
|
||||
# The image tag is per-commit, so the cache key never hits and every run
|
||||
# would `docker save` a gigabyte for nothing.
|
||||
cache: false
|
||||
wait: true
|
||||
enterprise_license: true
|
||||
- name: Run Playwright tests
|
||||
working-directory: web
|
||||
env:
|
||||
AK_TEST_RUNNER_PAGE_URL: ${{ steps.authentik.outputs.http_url }}
|
||||
run: pnpm run test:e2e
|
||||
# Reporting / upload steps below intentionally use `!cancelled()` rather
|
||||
# than `failure()`: a cancelled run (e.g. superseded by a newer push) is
|
||||
# not a real result and shouldn't produce reviewer-facing artifacts or
|
||||
# comments. `if-no-files-found: ignore` keeps the "passed" case quiet.
|
||||
# Server logs need no step of their own: the action's post step dumps the
|
||||
# logs of every compose service into the job log.
|
||||
- name: Upload Playwright HTML report
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-report
|
||||
path: web/playwright-report/
|
||||
retention-days: 14
|
||||
if-no-files-found: ignore
|
||||
- name: Upload Playwright traces and videos
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: playwright-traces
|
||||
path: web/test-results/
|
||||
retention-days: 14
|
||||
if-no-files-found: ignore
|
||||
# Test analytics only — no coverage is collected for the browser suite.
|
||||
- name: Upload Playwright results to codecov
|
||||
if: ${{ !cancelled() }}
|
||||
uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v5
|
||||
with:
|
||||
files: web/playwright-report/results.xml
|
||||
flags: e2e-web
|
||||
use_oidc: true
|
||||
report_type: test_results
|
||||
# Pass or fail, the artifacts are only useful if a reviewer knows how to get
|
||||
# them; the results themselves live in codecov. Skipped for pushes, and for
|
||||
# fork pull requests: those run with a read-only GITHUB_TOKEN even after
|
||||
# maintainer approval, so commenting would 403.
|
||||
- name: Comment on PR
|
||||
if: "${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}"
|
||||
uses: ./.github/actions/comment-pr
|
||||
with:
|
||||
section: playwright
|
||||
body: |
|
||||
## Playwright e2e
|
||||
|
||||
Download this run's HTML report and traces, then open the report:
|
||||
|
||||
```shell
|
||||
gh run download ${{ github.run_id }} -D playwright-artifacts
|
||||
npx playwright show-report playwright-artifacts/playwright-report
|
||||
```
|
||||
ci-core-mark:
|
||||
if: always()
|
||||
needs:
|
||||
@@ -603,18 +517,21 @@ jobs:
|
||||
- test-migrations-from-stable
|
||||
- test-unittest
|
||||
- test-integration
|
||||
- test-e2e
|
||||
- test-rust
|
||||
runs-on: ubuntu-26.04
|
||||
- test-e2e
|
||||
- test-e2e-container
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
|
||||
- uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
publish:
|
||||
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
needs:
|
||||
- build-compute-tags
|
||||
- build
|
||||
- ci-core-mark
|
||||
permissions:
|
||||
# Needed to upload container images to ghcr.io
|
||||
packages: write
|
||||
@@ -624,7 +541,7 @@ jobs:
|
||||
artifact-metadata: write
|
||||
# Needed for checkout
|
||||
contents: read
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -635,16 +552,16 @@ jobs:
|
||||
- radius
|
||||
- rac
|
||||
steps:
|
||||
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: regclient/actions/regctl-installer@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
# logs in to ghcr.io by default
|
||||
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: regclient/actions/regctl-login@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
# Docker login is required for attestations
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f
|
||||
- uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: "${{ github.actor }}"
|
||||
password: "${{ secrets.GITHUB_TOKEN }}"
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
name: "container-build-${{ matrix.name }}"
|
||||
- id: publish
|
||||
@@ -655,17 +572,18 @@ jobs:
|
||||
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-full }}" "container/${{ matrix.name }}.oci.tar"
|
||||
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-branch }}" "container/${{ matrix.name }}.oci.tar"
|
||||
regctl image import "ghcr.io/goauthentik/dev-${{ matrix.name }}:${{ needs.build-compute-tags.outputs.tag-flux }}" "container/${{ matrix.name }}.oci.tar"
|
||||
- uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6
|
||||
- uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6
|
||||
with:
|
||||
subject-name: "ghcr.io/goauthentik/dev-${{ matrix.name }}"
|
||||
subject-digest: "${{ steps.publish.outputs.digest }}"
|
||||
push-to-registry: true
|
||||
pr-comment:
|
||||
if: "${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}"
|
||||
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
needs:
|
||||
- build-compute-tags
|
||||
- publish
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed to write comments on PRs
|
||||
pull-requests: write
|
||||
@@ -673,39 +591,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- name: Comment on PR
|
||||
uses: ./.github/actions/comment-pr
|
||||
uses: ./.github/actions/comment-pr-instructions
|
||||
with:
|
||||
section: install
|
||||
body: |
|
||||
## Installation instructions
|
||||
|
||||
<details>
|
||||
<summary>Instructions for docker-compose</summary>
|
||||
|
||||
Add the following block to your `.env` file:
|
||||
|
||||
```shell
|
||||
AUTHENTIK_IMAGE=ghcr.io/goauthentik/dev-server
|
||||
AUTHENTIK_TAG=${{ needs.build-compute-tags.outputs.tag-full }}
|
||||
AUTHENTIK_OUTPOSTS__CONTAINER_IMAGE_BASE=ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||
```
|
||||
|
||||
Afterwards, run the upgrade commands from the latest release notes.
|
||||
</details>
|
||||
<details>
|
||||
<summary>Instructions for Kubernetes</summary>
|
||||
|
||||
Add the following block to your `values.yml` file:
|
||||
|
||||
```yaml
|
||||
authentik:
|
||||
outposts:
|
||||
container_image_base: ghcr.io/goauthentik/dev-%(type)s:gh-%(build_hash)s
|
||||
global:
|
||||
image:
|
||||
repository: ghcr.io/goauthentik/dev-server
|
||||
tag: ${{ needs.build-compute-tags.outputs.tag-full }}
|
||||
```
|
||||
|
||||
Afterwards, run the upgrade commands from the latest release notes.
|
||||
</details>
|
||||
tag: "${{ needs.build-compute-tags.outputs.tag-full }}"
|
||||
@@ -1,221 +0,0 @@
|
||||
---
|
||||
name: CI - Cross-branch migrations
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "41 4 * * *"
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/ci-migrations-cross-branch.yml
|
||||
|
||||
jobs:
|
||||
discover-release-branches:
|
||||
name: Find the adjacent release branches
|
||||
runs-on: ubuntu-26.04
|
||||
outputs:
|
||||
pairs: "${{ steps.pairs.outputs.pairs }}"
|
||||
steps:
|
||||
- id: pairs
|
||||
# Release branches are named version-<family> and sort with `sort -V`,
|
||||
# so the supported upgrade steps are derived here instead of being
|
||||
# listed
|
||||
env:
|
||||
REPO_URL: "${{ github.server_url }}/${{ github.repository }}"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mapfile -t branches < <(
|
||||
git ls-remote --heads "${REPO_URL}" 'refs/heads/version-*' \
|
||||
| sed 's#.*refs/heads/##' \
|
||||
| sort -V
|
||||
)
|
||||
if [ "${#branches[@]}" -lt 2 ]; then
|
||||
echo "::error::Found ${#branches[@]} release branches, need at least two"
|
||||
exit 1
|
||||
fi
|
||||
newest="${branches[-1]}"
|
||||
previous="${branches[-2]}"
|
||||
echo "::notice::Checking ${previous} -> ${newest} and ${newest} -> main"
|
||||
pairs="$(jq -nc --arg p "${previous}" --arg n "${newest}" \
|
||||
'{include: [{old: $p, new: $n}, {old: $n, new: "main"}]}')"
|
||||
echo "pairs=${pairs}" >> "$GITHUB_OUTPUT"
|
||||
test-migrations-cross-branch:
|
||||
name: Migrate ${{ matrix.old }} to ${{ matrix.new }}
|
||||
needs: discover-release-branches
|
||||
runs-on: ubuntu-26.04
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJson(needs.discover-release-branches.outputs.pairs) }}
|
||||
env:
|
||||
IMAGE_REPO: ghcr.io/goauthentik/dev-server
|
||||
PG_IMAGE: postgres:16-alpine
|
||||
PG_NAME: ak-migrate-postgres
|
||||
PG_NETWORK: ak-migrate
|
||||
steps:
|
||||
- id: images
|
||||
name: Resolve the branch images
|
||||
env:
|
||||
OLD_BRANCH: "${{ matrix.old }}"
|
||||
NEW_BRANCH: "${{ matrix.new }}"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
resolve() {
|
||||
local branch="$1" dashed dotted tag
|
||||
# version-2026.8 and newer replace the dot with a dash in the tag.
|
||||
# Remove once every branch uses compute-container-tags.
|
||||
dashed="gh-$(printf '%s' "${branch}" | sed 's/[^a-zA-Z0-9-]/-/g')"
|
||||
dotted="gh-${branch}"
|
||||
for tag in "${dashed}" "${dotted}"; do
|
||||
if docker manifest inspect "${IMAGE_REPO}:${tag}" >/dev/null 2>&1; then
|
||||
printf '%s' "${IMAGE_REPO}:${tag}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
missing=""
|
||||
old_image="$(resolve "${OLD_BRANCH}")" || missing="${OLD_BRANCH}"
|
||||
new_image="$(resolve "${NEW_BRANCH}")" || missing="${missing:+${missing} and }${NEW_BRANCH}"
|
||||
|
||||
if [ -n "${missing}" ]; then
|
||||
# A branch has no image until its own ci-main publish job runs, so
|
||||
# this is normal right after a branch-off and while that branch is
|
||||
# red. It is not a migration problem, so the step exits zero and
|
||||
# nothing is posted to Slack.
|
||||
note="No published image for ${missing}, skipped ${OLD_BRANCH} -> ${NEW_BRANCH}."
|
||||
echo "::warning::${note}"
|
||||
echo "${note}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "ready=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "::notice::${old_image} -> ${new_image}"
|
||||
{
|
||||
echo "old-image=${old_image}"
|
||||
echo "new-image=${new_image}"
|
||||
echo "ready=true"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- name: Start PostgreSQL
|
||||
if: ${{ steps.images.outputs.ready == 'true' }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker network create "${PG_NETWORK}"
|
||||
docker run --detach --name "${PG_NAME}" --network "${PG_NETWORK}" \
|
||||
-e POSTGRES_USER=authentik \
|
||||
-e POSTGRES_PASSWORD=authentik \
|
||||
-e POSTGRES_DB=authentik \
|
||||
"${PG_IMAGE}"
|
||||
|
||||
ready=false
|
||||
for _ in $(seq 1 60); do
|
||||
if docker exec "${PG_NAME}" pg_isready -U authentik -d authentik >/dev/null 2>&1; then
|
||||
ready=true
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "${ready}" != "true" ]; then
|
||||
docker logs "${PG_NAME}"
|
||||
echo "::error::PostgreSQL did not become ready"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "AUTHENTIK_SECRET_KEY=$(openssl rand -hex 32)" >> "$GITHUB_ENV"
|
||||
- name: Migrate to ${{ matrix.old }}
|
||||
if: ${{ steps.images.outputs.ready == 'true' }}
|
||||
env:
|
||||
IMAGE: "${{ steps.images.outputs.old-image }}"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# lifecycle/ sits at /lifecycle and the working directory is /, so
|
||||
# the entrypoint is overridden rather than using `ak migrate`, which
|
||||
# would skip the lifecycle system migrations.
|
||||
docker run --rm --network "${PG_NETWORK}" \
|
||||
-e AUTHENTIK_POSTGRESQL__HOST="${PG_NAME}" \
|
||||
-e AUTHENTIK_POSTGRESQL__USER=authentik \
|
||||
-e AUTHENTIK_POSTGRESQL__NAME=authentik \
|
||||
-e AUTHENTIK_POSTGRESQL__PASSWORD=authentik \
|
||||
-e AUTHENTIK_SECRET_KEY="${AUTHENTIK_SECRET_KEY}" \
|
||||
-e AUTHENTIK_AVATARS=none \
|
||||
--entrypoint bash "${IMAGE}" \
|
||||
-c 'cd / && python -m lifecycle.migrate'
|
||||
- name: Migrate to ${{ matrix.new }}
|
||||
if: ${{ steps.images.outputs.ready == 'true' }}
|
||||
env:
|
||||
IMAGE: "${{ steps.images.outputs.new-image }}"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm --network "${PG_NETWORK}" \
|
||||
-e AUTHENTIK_POSTGRESQL__HOST="${PG_NAME}" \
|
||||
-e AUTHENTIK_POSTGRESQL__USER=authentik \
|
||||
-e AUTHENTIK_POSTGRESQL__NAME=authentik \
|
||||
-e AUTHENTIK_POSTGRESQL__PASSWORD=authentik \
|
||||
-e AUTHENTIK_SECRET_KEY="${AUTHENTIK_SECRET_KEY}" \
|
||||
-e AUTHENTIK_AVATARS=none \
|
||||
--entrypoint bash "${IMAGE}" \
|
||||
-c 'cd / && python -m lifecycle.migrate'
|
||||
notify-migration-divergence:
|
||||
name: Notify migration divergence
|
||||
# Only the nightly run posts to Slack when something failed.
|
||||
# A manual run/PR show up in the Actions tab.
|
||||
if: >-
|
||||
${{ always() && github.event_name == 'schedule'
|
||||
&& (needs.discover-release-branches.result != 'success'
|
||||
|| needs.test-migrations-cross-branch.result != 'success') }}
|
||||
needs:
|
||||
- discover-release-branches
|
||||
- test-migrations-cross-branch
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Build the Slack message
|
||||
env:
|
||||
DISCOVERY_RESULT: "${{ needs.discover-release-branches.result }}"
|
||||
PAIRS: "${{ needs.discover-release-branches.outputs.pairs }}"
|
||||
REPO: "${{ github.repository }}"
|
||||
RUN_URL: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ "${DISCOVERY_RESULT}" = "success" ]; then
|
||||
headline="Nightly cross-branch migration check failed"
|
||||
intro="An upgrade between two release branches is broken. Django rejects the migration history, so the server crash-loops on start."
|
||||
pairs_list="$(printf '%s' "${PAIRS:-}" \
|
||||
| jq -r '.include[] | "• `\(.old)` -> `\(.new)`"' 2>/dev/null || true)"
|
||||
[ -n "${pairs_list}" ] || pairs_list="• the checked pairs are unknown"
|
||||
body="$(printf '%s\n\n%s' "${intro}" "${pairs_list}")"
|
||||
link_text="Open the failing run to see which pair failed"
|
||||
else
|
||||
headline="Nightly cross-branch migration check could not run"
|
||||
body="Branch discovery finished with \`${DISCOVERY_RESULT}\`, so no upgrade path was checked."
|
||||
link_text="Open the failing run"
|
||||
fi
|
||||
|
||||
jq -n \
|
||||
--arg headline "${headline}" \
|
||||
--arg body "${body}" \
|
||||
--arg link_text "${link_text}" \
|
||||
--arg repo "${REPO}" \
|
||||
--arg run_url "${RUN_URL}" \
|
||||
'{
|
||||
text: $headline,
|
||||
blocks: [
|
||||
{type: "section", text: {type: "mrkdwn",
|
||||
text: ("*" + $headline + "*\n" + $body)}},
|
||||
{type: "context", elements: [
|
||||
{type: "mrkdwn",
|
||||
text: ("`" + $repo + "` · <" + $run_url + "|" + $link_text + ">")}
|
||||
]}
|
||||
]
|
||||
}' > "${RUNNER_TEMP}/slack-payload.json"
|
||||
- name: Post to Slack
|
||||
uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0
|
||||
with:
|
||||
webhook: "${{ secrets.RELEASE_SLACK_WEBHOOK_URL }}"
|
||||
webhook-type: incoming-webhook
|
||||
payload-file-path: "${{ runner.temp }}/slack-payload.json"
|
||||
errors: "true"
|
||||
@@ -12,10 +12,6 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
env:
|
||||
POSTGRES_DB: authentik
|
||||
POSTGRES_USER: authentik
|
||||
@@ -23,7 +19,7 @@ env:
|
||||
|
||||
jobs:
|
||||
lint-golint:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
@@ -38,10 +34,11 @@ jobs:
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@ba0d7d2ec06a0ea1cb5fa41b2e4a3ab91d21278a # v8
|
||||
with:
|
||||
args: --timeout 5000s --verbose --config .github/golangci.yml
|
||||
version: latest
|
||||
args: --timeout 5000s --verbose
|
||||
skip-cache: true
|
||||
test-unittest:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
@@ -60,20 +57,21 @@ jobs:
|
||||
needs:
|
||||
- lint-golint
|
||||
- test-unittest
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
|
||||
- uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
build-binary:
|
||||
timeout-minutes: 120
|
||||
needs:
|
||||
- ci-outpost-mark
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
type:
|
||||
- proxy
|
||||
- ldap
|
||||
- radius
|
||||
- rac
|
||||
@@ -86,6 +84,24 @@ jobs:
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
cache-dependency-path: |
|
||||
pnpm-lock.yaml
|
||||
web/pnpm-lock.yaml
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
- name: Build web
|
||||
run: pnpm --dir web run build-proxy
|
||||
- name: Build outpost
|
||||
run: |
|
||||
set -x
|
||||
|
||||
@@ -12,27 +12,18 @@ on:
|
||||
- main
|
||||
- version-*
|
||||
|
||||
concurrency:
|
||||
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||
cancel-in-progress: "${{ !startsWith(github.ref, 'refs/heads/version-') && github.ref != 'refs/heads/main' && github.ref != 'refs/heads/next' }}"
|
||||
|
||||
env:
|
||||
POSTGRES_DB: authentik
|
||||
POSTGRES_USER: authentik
|
||||
POSTGRES_PASSWORD: "EK-5jnKfjrGRm<77"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -44,25 +35,25 @@ jobs:
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
- name: Lint
|
||||
run: pnpm --dir web run lint:check
|
||||
run: pnpm --dir web run lint-check
|
||||
- name: Check types
|
||||
run: pnpm --dir web run tsc
|
||||
- name: Check formatting
|
||||
run: pnpm --dir web run format:check
|
||||
run: pnpm --dir web run prettier-check
|
||||
- name: Lit analyse
|
||||
run: pnpm --dir web run lit-analyse
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -83,24 +74,24 @@ jobs:
|
||||
needs:
|
||||
- build
|
||||
- lint
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: re-actors/alls-green@b5b5b37504aa4183270bd3d855c52a67f212be35 # release/v1
|
||||
- uses: re-actors/alls-green@05ac9388f0aebcb5727afa17fcccfecd6f8ec5fe # release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
test:
|
||||
needs:
|
||||
- ci-web-mark
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
cache: pnpm
|
||||
@@ -113,4 +104,4 @@ jobs:
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
- name: test
|
||||
working-directory: web/
|
||||
run: pnpm exec vitest run --project "Unit Tests"
|
||||
run: pnpm run test || exit 0
|
||||
@@ -20,12 +20,12 @@ on:
|
||||
jobs:
|
||||
compress:
|
||||
name: compress
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
# Don't run on forks. Token will not be available. Will run on main and open a PR anyway
|
||||
if: "${{ github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) }}"
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
|
||||
@@ -13,10 +13,10 @@ env:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
@@ -25,7 +25,7 @@ jobs:
|
||||
token: ${{ steps.generate_token.outputs.token }}
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
- run: uv run python -m manage update_webauthn_mds
|
||||
- run: uv run ak update_webauthn_mds
|
||||
- uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
|
||||
id: cpr
|
||||
with:
|
||||
|
||||
@@ -13,7 +13,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
|
||||
@@ -13,10 +13,10 @@ on:
|
||||
jobs:
|
||||
clean-ghcr:
|
||||
name: Delete old unused container images
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
app-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
|
||||
@@ -6,10 +6,8 @@ on:
|
||||
branches: [main]
|
||||
paths:
|
||||
- packages/tsconfig/**
|
||||
- packages/oxlint-config/**
|
||||
- packages/oxfmt-config/**
|
||||
- packages/fonts/**
|
||||
- packages/theme/**
|
||||
- packages/eslint-config/**
|
||||
- packages/prettier-config/**
|
||||
- packages/docusaurus-config/**
|
||||
- packages/logger-js/**
|
||||
- packages/esbuild-plugin-live-reload/**
|
||||
@@ -22,30 +20,28 @@ permissions:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
package:
|
||||
# The order of the `*config` packages should not be changed, as they depend on each other.
|
||||
- packages/tsconfig
|
||||
- packages/oxlint-config
|
||||
- packages/oxfmt-config
|
||||
- packages/fonts
|
||||
- packages/logger-js
|
||||
- packages/theme
|
||||
- packages/eslint-config
|
||||
- packages/prettier-config
|
||||
- packages/docusaurus-config
|
||||
- packages/logger-js
|
||||
- packages/esbuild-plugin-live-reload
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
- uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
- name: Pin pnpm store directory
|
||||
run: |
|
||||
echo "PNPM_HOME=${RUNNER_TEMP}/pnpm-home" >> "$GITHUB_ENV"
|
||||
echo "npm_config_store_dir=${RUNNER_TEMP}/pnpm-home/store" >> "$GITHUB_ENV"
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v4
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
@@ -12,7 +12,7 @@ on:
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
@@ -28,10 +28,10 @@ jobs:
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/init@7188fc363630916deb702c7fdcf4e481b751f97a # v4.37.1
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/autobuild@7188fc363630916deb702c7fdcf4e481b751f97a # v4.37.1
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3
|
||||
uses: github/codeql-action/analyze@7188fc363630916deb702c7fdcf4e481b751f97a # v4.37.1
|
||||
@@ -17,7 +17,7 @@ permissions:
|
||||
jobs:
|
||||
dependency-review:
|
||||
name: dependency-review
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
|
||||
@@ -17,7 +17,7 @@ on:
|
||||
jobs:
|
||||
semgrep:
|
||||
name: semgrep/ci
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
|
||||
@@ -17,7 +17,7 @@ env:
|
||||
jobs:
|
||||
check-inputs:
|
||||
name: Check inputs validity
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: |
|
||||
echo "${{ inputs.next_version }}" | grep -E "^[0-9]{4}\.[0-9]{1,2}$"
|
||||
@@ -25,11 +25,11 @@ jobs:
|
||||
name: Branch-off
|
||||
needs:
|
||||
- check-inputs
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: app-token
|
||||
name: Generate app token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
@@ -46,18 +46,18 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: "${{ steps.app-token.outputs.token }}"
|
||||
run: |
|
||||
current_version_family="$(uv version --short | grep -oE "^[0-9]{4}\.[0-9]{1,2}")"
|
||||
git checkout -b "version-${current_version_family}"
|
||||
git push origin "version-${current_version_family}"
|
||||
gh label create "backport/version-${current_version_family}" --description "Add this label to PRs to backport changes to version-${current_version_family}" --color "fbca04"
|
||||
current_major_version="$(uv version --short | grep -oE "^[0-9]{4}\.[0-9]{1,2}")"
|
||||
git checkout -b "version-${current_major_version}"
|
||||
git push origin "version-${current_major_version}"
|
||||
gh label create "backport/version-${current_major_version}" --description "Add this label to PRs to backport changes to version-${current_major_version}" --color "fbca04"
|
||||
bump-version-pr:
|
||||
name: Open version bump PR
|
||||
needs:
|
||||
- branch-off
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
|
||||
@@ -12,7 +12,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
update-next:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
environment: internal-production
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
|
||||
@@ -7,17 +7,13 @@ on:
|
||||
|
||||
jobs:
|
||||
metadata:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag-name: "${{ steps.metadata.outputs.tag-name }}"
|
||||
version: "${{ steps.metadata.outputs.version }}"
|
||||
version-family: "${{ steps.metadata.outputs.version-family }}"
|
||||
major-version: "${{ steps.metadata.outputs.major-version }}"
|
||||
release-reason: "${{ steps.metadata.outputs.release-reason }}"
|
||||
changelog-url: "${{ steps.metadata.outputs.changelog-url }}"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- id: metadata
|
||||
name: Compute variables
|
||||
run: |
|
||||
@@ -25,12 +21,12 @@ jobs:
|
||||
echo "tag-name=$tag_name" >> "$GITHUB_OUTPUT"
|
||||
gh release download "$tag_name" --pattern metadata.json
|
||||
gh attestation verify metadata.json --owner goauthentik
|
||||
echo "version=$(jq -r '.version' < metadata.json)" >> "$GITHUB_OUTPUT"
|
||||
echo "version-family=$(jq -r '.version_family' < metadata.json)" >> "$GITHUB_OUTPUT"
|
||||
echo "release-reason=$(jq -r '.release_reason' < metadata.json)" >> "$GITHUB_OUTPUT"
|
||||
echo "changelog-url=$(jq -r '.changelog_url' < metadata.json)" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$(jq -r '.version')" >> "$GITHUB_OUTPUT"
|
||||
echo "major-version=$(jq -r '.major_version')" >> "$GITHUB_OUTPUT"
|
||||
echo "release-reason=$(jq -r '.release_reason')" >> "$GITHUB_OUTPUT"
|
||||
echo "changelog-url=$(jq -r '.changelog_url')" >> "$GITHUB_OUTPUT"
|
||||
publish-containers:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
# Needed to upload container images to ghcr.io
|
||||
@@ -39,7 +35,6 @@ jobs:
|
||||
id-token: write
|
||||
attestations: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
name:
|
||||
- server
|
||||
@@ -49,14 +44,11 @@ jobs:
|
||||
- rac
|
||||
needs:
|
||||
- metadata
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: regclient/actions/regctl-installer@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: regclient/actions/regctl-installer@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
# logs in to ghcr.io by default
|
||||
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: regclient/actions/regctl-login@dd58ad94f76adb73d8ac1bf75ed25f01545d5b32
|
||||
- uses: regclient/actions/regctl-login@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
- uses: regclient/actions/regctl-login@c48159175b58fb90cccd0f98410927a81e04a166
|
||||
with:
|
||||
registry: docker.io
|
||||
username: "${{ secrets.DOCKER_CORP_USERNAME }}"
|
||||
@@ -71,18 +63,10 @@ jobs:
|
||||
regctl image import "ocidir://${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
|
||||
echo "digest=$(regctl image digest "ocidir://${{ matrix.name }}:${{ needs.metadata.outputs.version }}")" >> "$GITHUB_OUTPUT"
|
||||
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
|
||||
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.major-version }}" "${{ matrix.name }}.oci.tar"
|
||||
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version }}" "${{ matrix.name }}.oci.tar"
|
||||
if [ "${{ needs.metadata.outputs.release-reason }}" != "prerelease" ]; then
|
||||
regctl image import "ghcr.io/goauthentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}" "${{ matrix.name }}.oci.tar"
|
||||
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.version-family }}" "${{ matrix.name }}.oci.tar"
|
||||
fi
|
||||
# we need to re-login for the attestation to go through
|
||||
- uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6
|
||||
regctl image import "docker.io/authentik/${{ matrix.name }}:${{ needs.metadata.outputs.major-version }}" "${{ matrix.name }}.oci.tar"
|
||||
- uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6
|
||||
with:
|
||||
subject-name: "ghcr.io/goauthentik/${{ matrix.name }}"
|
||||
subject-digest: "${{ steps.publish.outputs.digest }}"
|
||||
@@ -90,7 +74,7 @@ jobs:
|
||||
publish-docs-container:
|
||||
needs:
|
||||
- metadata
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed to upload container images to ghcr.io
|
||||
packages: write
|
||||
@@ -101,28 +85,30 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
ref: "${{ needs.metadata.outputs.tag-name }}"
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@594f3bf4285d9ea8dc53c9a0c9c4092420091003 # v4.4.0
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- id: build
|
||||
name: Build Docker Image
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
|
||||
with:
|
||||
tags: |
|
||||
ghcr.io/goauthentik/docs:${{ needs.metadata.outputs.version }}
|
||||
ghcr.io/goauthentik/docs:${{ needs.metadata.outputs.version-family }}
|
||||
ghcr.io/goauthentik/docs:${{ needs.metadata.outputs.major-version }}
|
||||
file: website/Dockerfile
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
context: .
|
||||
- uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v3
|
||||
- uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v3
|
||||
with:
|
||||
subject-name: ghcr.io/goauthentik/docs
|
||||
subject-digest: "${{ steps.build.outputs.digest }}"
|
||||
@@ -137,11 +123,10 @@ jobs:
|
||||
- publish-containers
|
||||
env:
|
||||
AWS_REGION: eu-central-1
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
- uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
|
||||
- uses: aws-actions/configure-aws-credentials@517a711dbcd0e402f90c77e7e2f81e849156e31d # v6.2.2
|
||||
with:
|
||||
role-to-assume: "arn:aws:iam::016170277896:role/github_goauthentik_authentik"
|
||||
aws-region: ${{ env.AWS_REGION }}
|
||||
@@ -149,14 +134,13 @@ jobs:
|
||||
run: |
|
||||
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ github.ref }}.yaml
|
||||
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.${{ needs.metadata.outputs.tag-name }}.yaml
|
||||
if [ "$(gh release list --json tagName,isLatest --jq '.[] | select(.tagName=="${{ needs.metadata.outputs.tag-name }}") | .isLatest')" = "true" ]; then
|
||||
if [ "$(gh release list --json tagName,isLatest --jq '.[] | select(.tagName=="${{ needs.metadata.outputs.tag-name }} ") | .isLatest')" = "true" ]; then
|
||||
aws s3 cp --acl=public-read lifecycle/aws/template.yaml s3://authentik-cloudformation-templates/authentik.ecs.latest.yaml
|
||||
fi
|
||||
sentry-release:
|
||||
needs:
|
||||
- publish-containers
|
||||
- metadata
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Get static files from docker image
|
||||
run: |
|
||||
@@ -165,7 +149,7 @@ jobs:
|
||||
container=$(docker container create "$image")
|
||||
docker cp ${container}:web/ .
|
||||
- name: Create a Sentry.io release
|
||||
uses: getsentry/action-release@6fb9aeade7061441cf3864e34fbe11a1457ad7dc # v3
|
||||
uses: getsentry/action-release@ff07929a6537bac57790c3451cf4d364aca38528 # v3
|
||||
continue-on-error: true
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
@@ -181,35 +165,55 @@ jobs:
|
||||
- metadata
|
||||
- publish-containers
|
||||
if: ${{ needs.metadata.outputs.release-reason != 'prerelease' }}
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: app-token
|
||||
name: Generate app token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
repositories: version
|
||||
- name: Bump version
|
||||
uses: goauthentik/version@main
|
||||
- id: get-user-id
|
||||
name: Get GitHub app user ID
|
||||
run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT"
|
||||
env:
|
||||
GH_TOKEN: "${{ steps.app-token.outputs.token }}"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
product: authentik
|
||||
new-version: ${{ needs.metadata.outputs.version }}
|
||||
changelog-url: ${{ needs.metadata.outputs.changelog-url }}
|
||||
reason: ${{ needs.metadata.outputs.release-reason }}
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
github-app-slug: ${{ steps.app-token.outputs.app-slug }}
|
||||
repository: "${{ github.repository_owner }}/version"
|
||||
token: "${{ steps.app-token.outputs.token }}"
|
||||
- name: Bump version
|
||||
run: |
|
||||
jq \
|
||||
--arg version "${{ needs.metadata.outputs.version }}" \
|
||||
--arg changelog "See ${{ needs.metadata.outputs.changelog-url }}" \
|
||||
--arg changelog_url "${{ needs.metadata.outputs.changelog-url }}" \
|
||||
--arg reason "${{ needs.metadata.outputs.release-reason }}" \
|
||||
'.stable.version = $version | .stable.changelog = $changelog | .stable.changelog_url = $changelog_url | .stable.reason = $reason' version.json > version.new.json
|
||||
mv version.new.json version.json
|
||||
- name: Create pull request
|
||||
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v7
|
||||
with:
|
||||
token: "${{ steps.app-token.outputs.token }}"
|
||||
branch: bump-${{ needs.metadata.outputs.version }}
|
||||
commit-message: "version: bump to ${{ needs.metadata.outputs.version }}"
|
||||
title: "version: bump to ${{ needs.metadata.outputs.version }}"
|
||||
body: "See ${{ needs.metadata.outputs.changelog-url }}"
|
||||
delete-branch: true
|
||||
signoff: true
|
||||
author: "${{ steps.app-token.outputs.app-slug }}[bot] <${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com>"
|
||||
bump-helm:
|
||||
name: Bump Helm version
|
||||
needs:
|
||||
- metadata
|
||||
- publish-containers
|
||||
if: ${{ needs.metadata.outputs.release-reason != 'prerelease' }}
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: app-token
|
||||
name: Generate app token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
|
||||
@@ -27,7 +27,7 @@ env:
|
||||
jobs:
|
||||
check-inputs:
|
||||
name: Check inputs validity
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: check
|
||||
env:
|
||||
@@ -35,41 +35,32 @@ jobs:
|
||||
run: |
|
||||
echo "${VERSION}" | grep -E '^[0-9]{4}\.(0?[1-9]|1[0-2])\.[0-9]+(-rc[0-9]+)?$'
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
echo "version-family=${VERSION}" | grep -oE "^version-family=[0-9]{4}\.[0-9]{1,2}" >> "$GITHUB_OUTPUT"
|
||||
- id: check-branch
|
||||
env:
|
||||
BRANCH: "${{ github.ref_name }}"
|
||||
EXPECTED_BRANCH: "version-${{ steps.check.outputs.version-family }}"
|
||||
run: |
|
||||
if [ "${BRANCH}" != "${EXPECTED_BRANCH}" ]; then
|
||||
echo "::error::This workflow must be run on ${EXPECTED_BRANCH}, but was run on ${BRANCH}."
|
||||
exit 1
|
||||
fi
|
||||
echo "major-version=${VERSION}" | grep -oE "^major-version=[0-9]{4}\.[0-9]{1,2}" >> "$GITHUB_OUTPUT"
|
||||
- id: changelog-url
|
||||
run: |
|
||||
if [ "${{ inputs.release_reason }}" = "feature" ]; then
|
||||
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}"
|
||||
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.major-version }}"
|
||||
elif [ "${{ inputs.release_reason }}" = "prerelease" ]; then
|
||||
changelog_url="https://next.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}"
|
||||
changelog_url="https://next.goauthentik.io/docs/releases/${{ steps.check.outputs.major-version }}"
|
||||
else
|
||||
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.version-family }}#fixed-in-$(echo -n "${{ steps.check.outputs.version }}" | sed 's/\.//g')"
|
||||
changelog_url="https://docs.goauthentik.io/docs/releases/${{ steps.check.outputs.major-version }}#fixed-in-$(echo -n "${{ steps.check.outputs.version }}" | sed 's/\.//g')"}
|
||||
fi
|
||||
echo "changelog-url=${changelog_url}" >> "$GITHUB_OUTPUT"
|
||||
outputs:
|
||||
version: "${{ steps.check.outputs.version }}"
|
||||
version-family: "${{ steps.check.outputs.version-family }}"
|
||||
major-version: "${{ steps.check.outputs.major-version }}"
|
||||
changelog-url: "${{ steps.changelog-url.outputs.changelog-url }}"
|
||||
bump-version:
|
||||
name: Bump authentik version
|
||||
needs:
|
||||
- check-inputs
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release-commit: "${{ steps.commit.outputs.release-commit }}"
|
||||
steps:
|
||||
- id: app-token
|
||||
name: Generate app token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
@@ -80,7 +71,7 @@ jobs:
|
||||
GH_TOKEN: "${{ steps.app-token.outputs.token }}"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
ref: "version-${{ needs.check-inputs.outputs.version-family }}"
|
||||
ref: "version-${{ needs.check-inputs.outputs.major-version }}"
|
||||
token: "${{ steps.app-token.outputs.token }}"
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
@@ -134,11 +125,11 @@ jobs:
|
||||
image-dockerfile: "lifecycle/container/${{ matrix.dockerfile }}"
|
||||
image-build-args: |
|
||||
VERSION=${{ needs.check-inputs.outputs.version }}
|
||||
build-go-binaries:
|
||||
build-binaries:
|
||||
needs:
|
||||
- bump-version
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Needed for checkout
|
||||
contents: read
|
||||
@@ -146,6 +137,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
type:
|
||||
- proxy
|
||||
- ldap
|
||||
- radius
|
||||
goos: [linux, darwin]
|
||||
@@ -157,6 +149,13 @@ jobs:
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- uses: ./.github/actions/setup-node
|
||||
with:
|
||||
working-directory: web
|
||||
- name: Build web
|
||||
working-directory: web/
|
||||
run: |
|
||||
npm run build-proxy
|
||||
- name: Build outpost
|
||||
run: |
|
||||
set -x
|
||||
@@ -165,72 +164,22 @@ jobs:
|
||||
export GOARCH=${{ matrix.goarch }}
|
||||
export CGO_ENABLED=0
|
||||
go build -tags=outpost_static_embed -v -o ./build/binaries/authentik-outpost-${{ matrix.type }}_${{ matrix.goos }}_${{ matrix.goarch }} ./cmd/${{ matrix.type }}
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v4
|
||||
with:
|
||||
name: "binaries-build-${{ matrix.type }}-${{ matrix.goos }}-${{ matrix.goarch }}"
|
||||
path: build/
|
||||
if-no-files-found: error
|
||||
retention-days: 2
|
||||
include-hidden-files: true
|
||||
build-rust-binaries:
|
||||
needs:
|
||||
- bump-version
|
||||
timeout-minutes: 120
|
||||
permissions:
|
||||
# Needed for checkout
|
||||
contents: read
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
type:
|
||||
- proxy
|
||||
target:
|
||||
- triple: x86_64-unknown-linux-gnu
|
||||
runs-on: ubuntu-26.04
|
||||
- triple: aarch64-unknown-linux-gnu
|
||||
runs-on: ubuntu-26.04-arm
|
||||
- triple: x86_64-apple-darwin
|
||||
runs-on: macos-15-intel
|
||||
- triple: aarch64-apple-darwin
|
||||
runs-on: macos-latest
|
||||
runs-on: "${{ matrix.target.runs-on }}"
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
ref: "${{ needs.bump-version.outputs.release-commit }}"
|
||||
- name: Setup rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@ecabd13d1c56bd1345c230e542e9144811ad706f # v2.0.0
|
||||
with:
|
||||
rustflags: ""
|
||||
target: "${{ matrix.target.triple }}"
|
||||
- name: Setup go
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
cache: false
|
||||
- name: Build outpost
|
||||
run: |
|
||||
set -x
|
||||
mkdir -p build/binaries/
|
||||
cargo build --package authentik --no-default-features --features "${{ matrix.type }}" --locked --release --target "${{ matrix.target.triple }}"
|
||||
cp "./target/${{ matrix.target.triple }}/release/authentik" "build/binaries/authentik-outpost-${{ matrix.type }}-${{ matrix.target.triple }}"
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v4
|
||||
with:
|
||||
name: "binaries-build-${{ matrix.type }}-${{ matrix.target.triple }}"
|
||||
path: build/
|
||||
if-no-files-found: error
|
||||
retention-days: 2
|
||||
include-hidden-files: true
|
||||
test:
|
||||
name: Pre-release test
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- check-inputs
|
||||
- bump-version
|
||||
- build-container
|
||||
steps:
|
||||
- name: Fetch container images
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
name: container-build-server-amd64
|
||||
- name: Load container images
|
||||
@@ -242,7 +191,6 @@ jobs:
|
||||
ref: "${{ needs.bump-version.outputs.release-commit }}"
|
||||
- name: Run test in Docker
|
||||
env:
|
||||
COMPOSE_PROJECT_NAME: authentik-release-test
|
||||
AUTHENTIK_IMAGE: authentik.invalid/goauthentik/server
|
||||
AUTHENTIK_TAG: "${{ needs.check-inputs.outputs.version }}"
|
||||
run: ./scripts/test_docker.sh
|
||||
@@ -252,18 +200,13 @@ jobs:
|
||||
- check-inputs
|
||||
- bump-version
|
||||
- build-container
|
||||
- build-go-binaries
|
||||
- build-rust-binaries
|
||||
- build-binaries
|
||||
- test
|
||||
runs-on: ubuntu-26.04
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: app-token
|
||||
name: Generate app token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
@@ -281,22 +224,23 @@ jobs:
|
||||
# ID from https://api.github.com/users/authentik-automation[bot]
|
||||
git config --global user.name '${{ steps.app-token.outputs.app-slug }}[bot]'
|
||||
git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com'
|
||||
git pull
|
||||
git tag "version/${{ needs.check-inputs.outputs.version }}" "${{ needs.bump-version.outputs.release-commit }}" -m "version/${{ needs.check-inputs.outputs.version }}"
|
||||
git push --tags
|
||||
- name: Create metadata file
|
||||
run: |
|
||||
echo '{"version": "${{ needs.check-inputs.outputs.version }}", "version_family": "${{ needs.check-inputs.outputs.version-family }}", "release_reason": "${{ inputs.release_reason }}", "changelog_url": "${{ needs.check-inputs.outputs.changelog-url }}"}' > metadata.json
|
||||
echo '{"version": "${{ needs.check-inputs.outputs.version }}", "major_version": "${{ needs.check-inputs.outputs.major-version }}", "release_reason": "${{ inputs.release_reason }}", "changelog_url": "${{ needs.check-inputs.outputs.changelog-url }}"}' > metadata.json
|
||||
- name: Fetch container images
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
pattern: container-build-*
|
||||
merge-multiple: true
|
||||
- name: Fetch binaries
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v5
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v5
|
||||
with:
|
||||
pattern: binaries-build-*
|
||||
merge-multiple: true
|
||||
- uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6
|
||||
- uses: actions/attest@f7c74d28b9d84cb8768d0b8ca14a4bac6ef463e6
|
||||
with:
|
||||
subject-path: |
|
||||
metadata.json
|
||||
@@ -306,15 +250,16 @@ jobs:
|
||||
container/radius.oci.tar
|
||||
container/rac.oci.tar
|
||||
binaries/authentik-outpost-*
|
||||
github-token: "${{ steps.app-token.outputs.token }}"
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
|
||||
with:
|
||||
token: "${{ steps.app-token.outputs.token }}"
|
||||
tag_name: "version/${{ needs.check-inputs.outputs.version }}"
|
||||
name: Release ${{ needs.check-inputs.outputs.version }}
|
||||
draft: true
|
||||
prerelease: ${{ inputs.release_reason == 'prerelease' }}
|
||||
generate_release_notes: false
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
See ${{ needs.check-inputs.outputs.changelog-url }}
|
||||
files: |
|
||||
|
||||
@@ -12,14 +12,14 @@ permissions:
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0
|
||||
- uses: actions/stale@1e223db275d687790206a7acac4d1a11bd6fe629 # v10
|
||||
with:
|
||||
repo-token: ${{ steps.generate_token.outputs.token }}
|
||||
days-before-stale: 60
|
||||
|
||||
@@ -17,7 +17,7 @@ permissions:
|
||||
|
||||
jobs:
|
||||
post-comment:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Find Comment
|
||||
uses: peter-evans/find-comment@b30e6a3c0ed37e7c023ccd3f1db5c6c0b0c23aad # v4
|
||||
|
||||
@@ -17,11 +17,11 @@ env:
|
||||
|
||||
jobs:
|
||||
compile:
|
||||
runs-on: ubuntu-26.04
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: generate_token
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
uv run make i18n-extract
|
||||
- name: run compile
|
||||
run: |
|
||||
uv run python -m manage compilemessages
|
||||
uv run ak compilemessages
|
||||
make web-check-compile
|
||||
- name: Create Pull Request
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
---
|
||||
name: Translation - Normalize locale paths
|
||||
|
||||
# Moves catalogs in Transifex pull requests to the paths listed in locales.yaml,
|
||||
# then pushes the result back to the pull request.
|
||||
# `make ci-lint-locales` in ci-main checks the outcome.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "locale/**"
|
||||
- "web/xliff/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
normalize:
|
||||
if: ${{ github.event.pull_request.user.login == 'transifex-integration[bot]' && github.event.pull_request.head.repo.full_name == github.repository }}
|
||||
runs-on: ubuntu-26.04
|
||||
steps:
|
||||
- id: generate_token
|
||||
uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v2
|
||||
with:
|
||||
client-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIV_KEY }}
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v5
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
token: ${{ steps.generate_token.outputs.token }}
|
||||
- name: Setup authentik env
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
dependencies: python
|
||||
- name: Normalize
|
||||
run: make locales-normalize gen-locales
|
||||
- name: Push corrections
|
||||
run: |
|
||||
if [ -z "$(git status --porcelain)" ]; then
|
||||
echo "Nothing to normalize."
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "authentik-automation[bot]"
|
||||
# ID from https://api.github.com/users/authentik-automation[bot]
|
||||
git config user.email "135050075+authentik-automation[bot]@users.noreply.github.com"
|
||||
git add -A locale web/xliff web/lit-localize.json web/src/common/ui/locale/definitions.ts .github/transifex.yml
|
||||
git commit --signoff -m "translate: normalize locale paths"
|
||||
git push
|
||||
@@ -14,7 +14,6 @@ media
|
||||
# Node
|
||||
|
||||
node_modules
|
||||
tsconfig.tsbuildinfo
|
||||
|
||||
.cspellcache
|
||||
cspell-report.*
|
||||
@@ -243,10 +242,3 @@ source_docs/
|
||||
### Docker ###
|
||||
tests/openid_conformance/exports/*.zip
|
||||
compose.override.yml
|
||||
|
||||
# Claude Local Instructions
|
||||
# https://code.claude.com/docs/en/memory#choose-where-to-put-claude-md-files
|
||||
CLAUDE.local.md
|
||||
|
||||
# Generated by `packages/oxlint-config/scripts/verify-fixtures.mjs`.
|
||||
.oxlintrc.generated.json
|
||||
@@ -0,0 +1,56 @@
|
||||
# Prettier Ignorefile
|
||||
|
||||
## Static Files
|
||||
CODEOWNERS
|
||||
**/LICENSE
|
||||
|
||||
authentik/stages/**/*
|
||||
|
||||
## Build asset directories
|
||||
coverage
|
||||
dist
|
||||
out
|
||||
.docusaurus
|
||||
# TODO Replace after moving website to docs
|
||||
website/api/reference
|
||||
|
||||
## Environment
|
||||
*.env
|
||||
|
||||
## Secrets
|
||||
*.secrets
|
||||
|
||||
## Yarn
|
||||
.yarn/**/*
|
||||
|
||||
# PNPM
|
||||
pnpm-workspace.yaml
|
||||
pnpm-lock.yaml
|
||||
|
||||
## Node
|
||||
node_modules
|
||||
coverage
|
||||
|
||||
## Vendored files
|
||||
vendored
|
||||
*.min.js
|
||||
|
||||
## Configs
|
||||
*.log
|
||||
*.yaml
|
||||
*.yml
|
||||
|
||||
# Templates
|
||||
# TODO: Rename affected files to *.template.* or similar.
|
||||
*.html
|
||||
*.mdx
|
||||
*.md
|
||||
|
||||
## Import order matters
|
||||
poly.ts
|
||||
src/locale-codes.ts
|
||||
src/locales/
|
||||
|
||||
# Storybook
|
||||
storybook-static/
|
||||
.storybook/css-import-maps*
|
||||
Vendored
+3
-2
@@ -3,18 +3,19 @@
|
||||
"bashmish.es6-string-css",
|
||||
"bpruitt-goddard.mermaid-markdown-syntax-highlighting",
|
||||
"charliermarsh.ruff",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"EditorConfig.EditorConfig",
|
||||
"esbenp.prettier-vscode",
|
||||
"github.vscode-github-actions",
|
||||
"golang.go",
|
||||
"Gruntfuggly.todo-tree",
|
||||
"mechatroner.rainbow-csv",
|
||||
"ms-python.black-formatter",
|
||||
"ms-python.black-formatter",
|
||||
"ms-python.debugpy",
|
||||
"ms-python.python",
|
||||
"ms-python.vscode-pylance",
|
||||
"oxc.oxc-vscode",
|
||||
"redhat.vscode-yaml",
|
||||
"rust-lang.rust-analyzer",
|
||||
"Tobermory.es6-string-html",
|
||||
"unifiedjs.vscode-mdx"
|
||||
]
|
||||
|
||||
Vendored
+4
-26
@@ -1,28 +1,7 @@
|
||||
{
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.oxc": "explicit"
|
||||
},
|
||||
"[css]": {
|
||||
"editor.minimap.markSectionHeaderRegex": "#\\bregion\\s*(?<separator>-?)\\s*(?<label>.*)\\*/$"
|
||||
},
|
||||
"[markdown]": {
|
||||
"editor.colorDecorators": false
|
||||
},
|
||||
"[yaml]": {
|
||||
"editor.autoIndent": "advanced",
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 2
|
||||
},
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
"[go]": {
|
||||
"editor.defaultFormatter": "golang.go"
|
||||
},
|
||||
"[rust]": {
|
||||
"editor.defaultFormatter": "rust-lang.rust-analyzer"
|
||||
},
|
||||
"[makefile]": {
|
||||
"editor.minimap.markSectionHeaderRegex": "^#{25}\n##\\s\\s*(?<separator>-?)\\s*(?<label>[^\n]*)\n#{25}$"
|
||||
},
|
||||
@@ -30,7 +9,6 @@
|
||||
"editor.minimap.markSectionHeaderRegex": "\\bStage\\s*\\d:(?<separator>-?)\\s*(?<label>.*)$"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "oxc.oxc-vscode",
|
||||
"editor.minimap.markSectionHeaderRegex": "#\\bregion\\s*(?<separator>-?)\\s*(?<label>.*)$"
|
||||
},
|
||||
"[xml]": {
|
||||
@@ -40,9 +18,11 @@
|
||||
// The built-in "ignore" language gives us enough syntax highlighting to make these files readable.
|
||||
"**/dictionaries/*.txt": "ignore"
|
||||
},
|
||||
"oxc.fixKind": "safe_fix_or_suggestion",
|
||||
"todo-tree.tree.showCountsInTree": true,
|
||||
"todo-tree.tree.showBadges": true,
|
||||
"yaml.format.printWidth": 200,
|
||||
"yaml.format.singleQuote": true,
|
||||
"yaml.format.bracketSpacing": false,
|
||||
"yaml.customTags": [
|
||||
"!Condition sequence",
|
||||
"!Context scalar",
|
||||
@@ -80,9 +60,7 @@
|
||||
"go.testEnvVars": {
|
||||
"WORKSPACE_DIR": "${workspaceFolder}"
|
||||
},
|
||||
"github-actions.workflows.pinned.workflows": [
|
||||
".github/workflows/ci-main.yml"
|
||||
],
|
||||
"github-actions.workflows.pinned.workflows": [".github/workflows/ci-main.yml"],
|
||||
"search.exclude": {
|
||||
"**/*.code-search": true,
|
||||
"**/bower_components": true,
|
||||
|
||||
@@ -7,8 +7,8 @@ It is a **polyglot monorepo**. Most work lands in one of the subtrees below; whe
|
||||
| Language | Where | What it is | Deeper guide |
|
||||
| -------------- | -------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------- |
|
||||
| **Python** | `authentik/`, `lifecycle/` | The core server — a Django + Django REST Framework app. The source of truth for the IdP. | — |
|
||||
| **Go** | `cmd/`, `internal/` | **Outposts** (LDAP, RAC, RADIUS). | — |
|
||||
| **Rust** | `src/`, `packages/ak-*` | Newer server/worker/proxy outpost components and shared crates (`ak-axum`, `ak-common`, `ak-guardian`). | — |
|
||||
| **Go** | `cmd/`, `internal/` | **Outposts** (LDAP, proxy, RAC, RADIUS) and the front reverse-proxy that fronts Django. | — |
|
||||
| **Rust** | `src/`, `packages/ak-*` | Newer server/worker components and shared crates (`ak-axum`, `ak-common`, `ak-guardian`). | — |
|
||||
| **TypeScript** | `web/` | The web UI — three Lit + PatternFly apps (Admin, User, Flow). | [`web/AGENTS.md`](web/AGENTS.md) |
|
||||
| **Docs** | `website/` | The documentation, integrations, and API sites (Docusaurus). | [`website/AGENTS.md`](website/AGENTS.md) |
|
||||
|
||||
@@ -18,19 +18,19 @@ The Python core and the web UI talk through a **generated OpenAPI client** — n
|
||||
|
||||
```
|
||||
authentik/ # Django core — the IdP itself (see "The authentik Django package" below)
|
||||
lifecycle/ # Boot/runtime: migrations, the prefork Python server, the `ak` CLI, container + AWS entrypoints
|
||||
cmd/ # Go entrypoints: ldap/ rac/ radius/ outposts
|
||||
internal/ # Shared Go: outpost implementations, config
|
||||
lifecycle/ # Boot/runtime: migrations, gunicorn config, the `ak` CLI, container + AWS entrypoints
|
||||
cmd/ # Go entrypoints: ldap/ proxy/ rac/ radius/ outposts + server/ (front reverse-proxy)
|
||||
internal/ # Shared Go: outpost implementations, config, web proxy, gounicorn process manager
|
||||
src/ # Rust server/worker (ak-axum based; gated behind cargo features)
|
||||
packages/ # Shared workspace packages, polyglot:
|
||||
# client-go / client-rust / client-ts — GENERATED API clients (do not hand-edit)
|
||||
# ak-axum / ak-common / ak-guardian — Rust crates
|
||||
# django-* — reusable Django apps (channels, dramatiq, cache)
|
||||
# oxlint-config / oxfmt-config / tsconfig / theme / docusaurus-config — shared JS config
|
||||
# eslint-config / prettier-config / tsconfig / theme / docusaurus-config — shared JS config
|
||||
web/ # TypeScript web UI (own AGENTS.md)
|
||||
website/ # Docs / integrations / API sites (own AGENTS.md)
|
||||
blueprints/ # YAML declarative config (default/ system/ example/) applied at startup
|
||||
locale/ # Backend translations (.po) + cspell overrides dictionary (en/dictionaries/)
|
||||
locale/ # Backend translations (.po) + shared cspell dictionaries (en/dictionaries/)
|
||||
tests/ # Cross-cutting test support: e2e/, integration/, geoip/, openid_conformance/
|
||||
schemas/ # Third-party XSD/JSON schemas (SAML, WS-*, SCIM) used at runtime
|
||||
scripts/ # Repo automation (schema build, compose generation, node setup, semver)
|
||||
@@ -52,7 +52,7 @@ go.mod # Go module (module path: goauthentik.io)
|
||||
- **`sources/`** — inbound identity (LDAP, OAuth, SAML, SCIM, Kerberos source).
|
||||
- **`providers/`** — outbound protocols authentik exposes (SAML, OAuth2/OIDC, Proxy, LDAP, RADIUS, SCIM, RAC).
|
||||
- **`outposts/`** — management/coordination of the Go outposts.
|
||||
- **`brands/`** — branding/theming per domain.
|
||||
- **`brands/`** + **`tenants/`** — branding/theming and multi-tenancy (`django-tenants`).
|
||||
- **`blueprints/`** — the engine that applies the YAML under the top-level `blueprints/` directory.
|
||||
- **`rbac/`**, **`crypto/`**, **`events/`** (audit log), **`enterprise/`** (EE-licensed features), **`api/`** - **`admin/`** (REST surfaces), **`root/`** (Django project: settings, URLs, ASGI/WSGI).
|
||||
|
||||
@@ -64,7 +64,7 @@ Most tasks land in one subtree and have one follow-up step. Find the row, then r
|
||||
| ------------------------------------------------------------------ | ------------------------------ | ------------------------------------------------------------------------------------ |
|
||||
| Add or change a REST endpoint, model field, or serializer | `authentik/` (Python) | `make gen` to refresh `schema.yml` + clients, and commit the generated migration |
|
||||
| Change UI behavior, a flow screen, or an admin page | `web/` | [`web/AGENTS.md`](web/AGENTS.md) — call the API only through `@goauthentik/api` |
|
||||
| Write or edit docs or an integration guide | `website/` | [`website/AGENTS.md`](website/AGENTS.md), then `make docs` / `make integrations` |
|
||||
| Write or edit docs, an integration guide, or a glossary term | `website/` | [`website/AGENTS.md`](website/AGENTS.md), then `make docs` / `make integrations` |
|
||||
| Change an outpost (LDAP, proxy, RAC, RADIUS) or the front proxy | `cmd/` + `internal/` (Go) | `make go-test` |
|
||||
| Change a native server/worker component or shared crate | `src/` + `packages/ak-*` (Rust)| `make rust-test` |
|
||||
| Seed or reconcile a managed object (flow, stage, policy, brand) | `blueprints/` (YAML) | prefer a blueprint over an ad-hoc data migration |
|
||||
@@ -106,9 +106,8 @@ make web-test # Web UI tests (delegates to web/)
|
||||
```bash
|
||||
make lint-fix # Auto-fix: black + ruff (Python) and rustfmt (Rust)
|
||||
make lint # Check: bandit, mypy --strict, golangci-lint, cargo deny/machete
|
||||
make lint-spellcheck # cspell across the repo (typo-only mode: reports known misspellings and forbidden British spellings, not unknown words)
|
||||
make lint-spellcheck # cspell across the repo (shared dictionaries in locale/en/dictionaries/)
|
||||
make lint-catalogs # pnpm catalog pins in sync across the root/web/website workspaces
|
||||
make lint-locales # translation files + generated locale lists match locales.yaml (`make gen-locales` regenerates)
|
||||
```
|
||||
|
||||
CI mirrors these as `ci-lint-*` / `ci-test` targets. Run the matching `make lint` / `make test` (plus `make web` / `make docs` for those subtrees) before pushing — CI runs the same checks.
|
||||
@@ -145,9 +144,9 @@ Authoritative contributor docs live under `website/docs/developer-docs/` and are
|
||||
|
||||
- `setup/full-dev-environment.mdx` — full backend + frontend dev environment.
|
||||
- `setup/frontend-dev-environment.mdx` — web-only setup.
|
||||
- `setup/debugging.mdx` — attaching a debugger (VS Code config included).
|
||||
- `setup/debugging.md` — attaching a debugger (VS Code config included).
|
||||
- `docs/style-guide.mdx` — the canonical prose style guide (also governs this repo's docs).
|
||||
- `contributing.mdx` / top-level `CONTRIBUTING.md` — contribution process. `SECURITY.md` — reporting vulnerabilities.
|
||||
- `contributing.md` / top-level `CONTRIBUTING.md` — contribution process. `SECURITY.md` — reporting vulnerabilities.
|
||||
|
||||
## Tech stack
|
||||
|
||||
@@ -155,7 +154,7 @@ Authoritative contributor docs live under `website/docs/developer-docs/` and are
|
||||
| --------------- | ------------------------------------------------------------------------ |
|
||||
| Core server | Python 3.14, Django 5.2 + Django REST Framework, Channels (ASGI) |
|
||||
| Background work | Dramatiq (Postgres broker) |
|
||||
| Datastore | PostgreSQL |
|
||||
| Datastore | PostgreSQL (multi-tenant via `django-tenants`) + Redis |
|
||||
| Outposts | Go 1.26 (`goauthentik.io` module) — LDAP, proxy, RAC, RADIUS |
|
||||
| Native services | Rust (2024 edition, `axum`) — server/worker components + shared crates |
|
||||
| Web UI | TypeScript, Lit 3, PatternFly 4 (see `web/`) |
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
# AI-Assisted Contributions Policy
|
||||
|
||||
authentik welcomes community contributions, including AI-assisted contributions, as long as contributors understand, review, and take responsibility for what they submit.
|
||||
|
||||
- **All AI usage in any form must be disclosed.** State what tool(s) you relied on and the extent that the work was AI-assisted.
|
||||
- **The human-in-the-loop must fully understand all code.** If you cannot explain what your changes do, why they are correct, and how they affect the relevant parts of authentik without AI assistance, do not submit them.
|
||||
- **Issues and discussions can use AI assistance but must have a human-in-the-loop.** This means that any content generated with AI must have been reviewed _and edited_ by a human before submission. AI is often overly verbose, with noise that distracts from the main point. Contributors are expected to verify claims, include relevant context, and remove generic or speculative content.
|
||||
- **No AI-generated media is allowed (art, images, videos, audio, etc.).** Text and code are the only acceptable AI-generated content.
|
||||
- If a code contribution or discussion appears to be entirely AI-driven and lacking human judgement, the maintainers will close the issue/PR/discussion. Common examples include unexplained large diffs, invented API endpoints, irrelevant changes, generic issue reports, repeated AI-generated replies, or contributors being unable to answer review questions.
|
||||
|
||||
These rules apply to all external contributions to authentik. Our [maintainers](https://github.com/orgs/goauthentik/people) use AI tools at the internal team's discretion; we are already constantly discussing our work with each other and checking in as humans.
|
||||
|
||||
## There are Humans Here
|
||||
|
||||
authentik is maintained by people with limited time and attention.
|
||||
|
||||
Every discussion, issue, and pull request is read and reviewed by humans (and sometimes machines, too). It is a boundary point at which people interact with each other and the work done. It is disrespectful and unscalable to approach this boundary with low-effort, unqualified work, since it puts the burden of validation on the maintainer.
|
||||
|
||||
**Our reason for the strict AI policy is not due to an anti-AI stance**, but instead due to the number of highly unqualified AI-driven contributions. A small minority misusing these tools creates an unscalable problem for maintainers.
|
||||
|
||||
In a perfect world, AI would produce high-quality, accurate work every time. But today, that reality depends on careful consideration and usage by the human driver of the AI. Since AI is instead best as _producing code quickly_, we have to have strict rules in place to protect the project and maintainers' limited time.
|
||||
+28
-30
@@ -1,15 +1,15 @@
|
||||
# Fallback
|
||||
* @goauthentik/backend @goauthentik/frontend
|
||||
# Backend
|
||||
/authentik/ @goauthentik/backend
|
||||
/blueprints/ @goauthentik/backend
|
||||
/src/ @goauthentik/backend
|
||||
/cmd/ @goauthentik/backend
|
||||
/internal/ @goauthentik/backend
|
||||
/lifecycle/ @goauthentik/backend
|
||||
/schemas/ @goauthentik/backend
|
||||
/scripts/ @goauthentik/backend
|
||||
/tests/ @goauthentik/backend
|
||||
authentik/ @goauthentik/backend
|
||||
blueprints/ @goauthentik/backend
|
||||
src/ @goauthentik/backend
|
||||
cmd/ @goauthentik/backend
|
||||
internal/ @goauthentik/backend
|
||||
lifecycle/ @goauthentik/backend
|
||||
schemas/ @goauthentik/backend
|
||||
scripts/ @goauthentik/backend
|
||||
tests/ @goauthentik/backend
|
||||
pyproject.toml @goauthentik/backend
|
||||
uv.lock @goauthentik/backend
|
||||
Cargo.toml @goauthentik/backend
|
||||
@@ -21,44 +21,42 @@ go.sum @goauthentik/backend
|
||||
rust-toolchain.toml @goauthentik/backend
|
||||
# Infrastructure
|
||||
.github/ @goauthentik/infrastructure
|
||||
/lifecycle/aws/ @goauthentik/infrastructure
|
||||
/lifecycle/container/ @goauthentik/infrastructure
|
||||
lifecycle/aws/ @goauthentik/infrastructure
|
||||
lifecycle/container/ @goauthentik/infrastructure
|
||||
.dockerignore @goauthentik/infrastructure
|
||||
Makefile @goauthentik/infrastructure
|
||||
.editorconfig @goauthentik/infrastructure
|
||||
CODEOWNERS @goauthentik/infrastructure
|
||||
# Backend packages
|
||||
/packages/ak-* @goauthentik/backend
|
||||
/packages/client-rust @goauthentik/backend
|
||||
/packages/django-channels-postgres @goauthentik/backend
|
||||
/packages/django-postgres-cache @goauthentik/backend
|
||||
/packages/django-dramatiq-postgres @goauthentik/backend
|
||||
packages/ak-* @goauthentik/backend
|
||||
packages/client-rust @goauthentik/backend
|
||||
packages/django-channels-postgres @goauthentik/backend
|
||||
packages/django-postgres-cache @goauthentik/backend
|
||||
packages/django-dramatiq-postgres @goauthentik/backend
|
||||
# Web packages
|
||||
.npmrc @goauthentik/frontend
|
||||
.nvmrc @goauthentik/frontend
|
||||
tsconfig.json @goauthentik/frontend
|
||||
package.json @goauthentik/frontend
|
||||
package-lock.json @goauthentik/frontend
|
||||
pnpm-lock.yaml @goauthentik/frontend
|
||||
pnpm-workspace.yaml @goauthentik/frontend
|
||||
/packages/client-ts @goauthentik/frontend
|
||||
/packages/docusaurus-config @goauthentik/frontend
|
||||
/packages/esbuild-plugin-live-reload @goauthentik/frontend
|
||||
/packages/oxlint-config @goauthentik/frontend
|
||||
/packages/oxfmt-config @goauthentik/frontend
|
||||
/packages/fonts @goauthentik/frontend
|
||||
/packages/logger-js @goauthentik/frontend
|
||||
/packages/theme @goauthentik/frontend
|
||||
/packages/tsconfig @goauthentik/frontend
|
||||
packages/client-ts @goauthentik/frontend
|
||||
packages/docusaurus-config @goauthentik/frontend
|
||||
packages/esbuild-plugin-live-reload @goauthentik/frontend
|
||||
packages/eslint-config @goauthentik/frontend
|
||||
packages/prettier-config @goauthentik/frontend
|
||||
packages/logger-js @goauthentik/frontend
|
||||
packages/theme @goauthentik/frontend
|
||||
packages/tsconfig @goauthentik/frontend
|
||||
# Web
|
||||
/web/ @goauthentik/frontend
|
||||
web/ @goauthentik/frontend
|
||||
# Locale
|
||||
/locale/ @goauthentik/backend @goauthentik/frontend
|
||||
/locale/*/dictionaries @goauthentik/frontend @goauthentik/docs
|
||||
/web/xliff/ @goauthentik/backend @goauthentik/frontend
|
||||
web/xliff/ @goauthentik/backend @goauthentik/frontend
|
||||
# Docs
|
||||
/website/ @goauthentik/docs
|
||||
website/ @goauthentik/docs
|
||||
CODE_OF_CONDUCT.md @goauthentik/docs
|
||||
# Security
|
||||
SECURITY.md @goauthentik/security @goauthentik/docs
|
||||
/website/security/ @goauthentik/security @goauthentik/docs
|
||||
website/security/ @goauthentik/security @goauthentik/docs
|
||||
Generated
+932
-724
File diff suppressed because it is too large.
Load diff
+50
-124
@@ -3,12 +3,13 @@ members = [
|
||||
"packages/ak-axum",
|
||||
"packages/ak-common",
|
||||
"packages/client-rust",
|
||||
"tests",
|
||||
"website/scripts/docsmg",
|
||||
]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "2026.11.0-rc1"
|
||||
version = "2026.8.0-rc1"
|
||||
authors = ["authentik Team <[email protected]>"]
|
||||
description = "Making authentication simple."
|
||||
edition = "2024"
|
||||
@@ -21,16 +22,12 @@ publish = false
|
||||
[workspace.dependencies]
|
||||
arc-swap = "= 1.9.2"
|
||||
argh = "= 0.1.19"
|
||||
askama = "= 0.16.1"
|
||||
axum-server = { version = "= 0.8.0", features = ["tls-rustls-no-provider"] }
|
||||
aws-lc-rs = { version = "= 1.18.2", features = ["fips"] }
|
||||
aws-lc-rs = { version = "= 1.17.3", features = ["fips"] }
|
||||
axum = { version = "= 0.8.9", features = ["http2", "macros", "ws"] }
|
||||
axum-extra = { version = "= 0.12.6", default-features = false, features = [
|
||||
"cookie-signed",
|
||||
"cookie-key-expansion",
|
||||
] }
|
||||
base64 = "= 0.23.1"
|
||||
clap = { version = "= 4.6.7", features = ["derive", "env"] }
|
||||
base64 = "= 0.22.1"
|
||||
clap = { version = "= 4.6.2", features = ["derive", "env"] }
|
||||
client-ip = { version = "0.2.1", features = ["forwarded-header"] }
|
||||
chrono = { version = "0.4.45", features = ["serde"] }
|
||||
color-eyre = "= 0.6.5"
|
||||
colored = "= 3.1.1"
|
||||
@@ -40,54 +37,27 @@ config-rs = { package = "config", version = "= 0.15.22", default-features = fals
|
||||
] }
|
||||
console-subscriber = "= 0.5.0"
|
||||
dotenvy = "= 0.15.7"
|
||||
durstr = "= 0.6.0"
|
||||
eyre = "= 0.6.14"
|
||||
futures = "= 0.3.34"
|
||||
glob = "= 0.3.4"
|
||||
http-body-util = "= 0.1.5"
|
||||
hyper = { version = "= 1.12.0", features = ["client", "http1", "http2"] }
|
||||
hyper-rustls = { version = "= 0.27.10", default-features = false, features = [
|
||||
"aws-lc-rs",
|
||||
"http1",
|
||||
"http2",
|
||||
"native-tokio",
|
||||
"tls12",
|
||||
] }
|
||||
hyper-unix-socket = "= 0.7.0"
|
||||
hyper-util = { version = "= 0.1.21", features = [
|
||||
"client-legacy",
|
||||
"http1",
|
||||
"http2",
|
||||
"tokio",
|
||||
] }
|
||||
ipnet = { version = "= 2.12.2", features = ["serde"] }
|
||||
json-subscriber = "= 0.3.1"
|
||||
jsonwebtoken = { version = "= 11.1.0", features = ["aws_lc_rs"] }
|
||||
durstr = "= 0.5.1"
|
||||
eyre = "= 0.6.12"
|
||||
forwarded-header-value = "= 0.1.1"
|
||||
futures = "= 0.3.33"
|
||||
futures-util = "= 0.3.33"
|
||||
glob = "= 0.3.3"
|
||||
hyper-unix-socket = "= 0.6.1"
|
||||
hyper-util = "= 0.1.20"
|
||||
ipnet = { version = "= 2.12.0", features = ["serde"] }
|
||||
json-subscriber = "= 0.3.0"
|
||||
jsonwebtoken = { version = "= 10.4.0", features = ["aws_lc_rs"] }
|
||||
metrics = "= 0.24.6"
|
||||
metrics-exporter-prometheus = { version = "= 0.18.3", default-features = false }
|
||||
moka = { version = "= 0.12.16", default-features = false, features = [
|
||||
"future",
|
||||
] }
|
||||
nix = { version = "= 0.31.3", features = [
|
||||
"fs",
|
||||
"hostname",
|
||||
"process",
|
||||
"signal",
|
||||
"user",
|
||||
] }
|
||||
nix = { version = "= 0.31.3", features = ["hostname", "signal"] }
|
||||
notify = "= 8.2.0"
|
||||
pem = "= 4.0.0"
|
||||
percent-encoding = "= 2.3.2"
|
||||
pin-project-lite = "= 0.2.17"
|
||||
pyo3 = "= 0.29.1"
|
||||
pyo3-build-config = "= 0.29.1"
|
||||
rand = "= 0.10.3"
|
||||
rcgen = { version = "= 0.14.10", default-features = false, features = [
|
||||
"aws_lc_rs",
|
||||
"fips",
|
||||
] }
|
||||
pyo3 = "= 0.29.0"
|
||||
pyo3-build-config = "= 0.29.0"
|
||||
rand = "= 0.10.2"
|
||||
regex = "= 1.13.1"
|
||||
reqwest = { version = "= 0.13.5", features = [
|
||||
reqwest = { version = "= 0.13.4", features = [
|
||||
"form",
|
||||
"json",
|
||||
"multipart",
|
||||
@@ -102,8 +72,8 @@ reqwest-middleware = { version = "= 0.5.2", features = [
|
||||
"query",
|
||||
"rustls",
|
||||
] }
|
||||
rustls = { version = "= 0.23.46", features = ["fips"] }
|
||||
sentry = { version = "= 0.49.3", default-features = false, features = [
|
||||
rustls = { version = "= 0.23.42", features = ["fips"] }
|
||||
sentry = { version = "= 0.48.5", default-features = false, features = [
|
||||
"backtrace",
|
||||
"contexts",
|
||||
"debug-images",
|
||||
@@ -114,9 +84,9 @@ sentry = { version = "= 0.49.3", default-features = false, features = [
|
||||
"tracing",
|
||||
] }
|
||||
serde = { version = "= 1.0.229", features = ["derive"] }
|
||||
serde_json = "= 1.0.154"
|
||||
serde_json = "= 1.0.150"
|
||||
serde_repr = "= 0.1.21"
|
||||
serde_with = { version = "= 3.24.0", default-features = false, features = [
|
||||
serde_with = { version = "= 3.21.0", default-features = false, features = [
|
||||
"base64",
|
||||
] }
|
||||
sqlx = { version = "= 0.9.0", default-features = false, features = [
|
||||
@@ -131,23 +101,20 @@ sqlx = { version = "= 0.9.0", default-features = false, features = [
|
||||
"json",
|
||||
] }
|
||||
tempfile = "= 3.27.0"
|
||||
thiserror = "= 2.0.21"
|
||||
time = { version = "= 0.3.55", features = ["macros"] }
|
||||
tokio = { version = "= 1.53.3", features = ["full", "tracing"] }
|
||||
testcontainers = { version = "0.27.3", default-features = false, features = [
|
||||
"aws-lc-rs",
|
||||
"docker-compose",
|
||||
"http_wait_plain",
|
||||
] }
|
||||
thirtyfour = "0.37.1"
|
||||
thiserror = "= 2.0.19"
|
||||
time = { version = "= 0.3.53", features = ["macros"] }
|
||||
tokio = { version = "= 1.52.4", features = ["full", "tracing"] }
|
||||
tokio-retry2 = "= 0.9.1"
|
||||
tokio-rustls = "= 0.26.6"
|
||||
tokio-tungstenite = { version = "= 0.30.0", features = [
|
||||
"rustls-tls-webpki-roots",
|
||||
"url",
|
||||
] }
|
||||
tokio-util = { version = "= 0.7.20", features = ["full"] }
|
||||
tokio-rustls = "= 0.26.4"
|
||||
tokio-util = { version = "= 0.7.18", features = ["full"] }
|
||||
tower = "= 0.5.3"
|
||||
tower-http = { version = "= 0.7.1", features = [
|
||||
"compression-full",
|
||||
"fs",
|
||||
"limit",
|
||||
"timeout",
|
||||
] }
|
||||
tower-http = { version = "= 0.7.0", features = ["timeout"] }
|
||||
tracing = "= 0.1.44"
|
||||
tracing-error = "= 0.2.1"
|
||||
tracing-subscriber = { version = "= 0.3.23", features = [
|
||||
@@ -157,11 +124,12 @@ tracing-subscriber = { version = "= 0.3.23", features = [
|
||||
"tracing-log",
|
||||
] }
|
||||
url = "= 2.5.8"
|
||||
uuid = { version = "= 1.28.0", features = ["serde", "v4"] }
|
||||
uuid = { version = "= 1.23.5", features = ["serde", "v4"] }
|
||||
which = "= 8.0.5"
|
||||
|
||||
ak-axum = { package = "authentik-axum", version = "2026.11.0-rc1", path = "./packages/ak-axum" }
|
||||
ak-client = { package = "authentik-client", version = "2026.11.0-rc1", path = "./packages/client-rust" }
|
||||
ak-common = { package = "authentik-common", version = "2026.11.0-rc1", path = "./packages/ak-common", default-features = false }
|
||||
ak-axum = { package = "authentik-axum", version = "2026.8.0-rc1", path = "./packages/ak-axum" }
|
||||
ak-client = { package = "authentik-client", version = "2026.8.0-rc1", path = "./packages/client-rust" }
|
||||
ak-common = { package = "authentik-common", version = "2026.8.0-rc1", path = "./packages/ak-common", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
ambiguous_negative_literals = "warn"
|
||||
@@ -281,7 +249,10 @@ verbose_file_reads = "warn"
|
||||
opt-level = 3
|
||||
|
||||
[profile.release]
|
||||
debug = 2
|
||||
lto = "fat"
|
||||
# Because of the async runtime, we want to die straightaway if we panic.
|
||||
panic = "abort"
|
||||
strip = true
|
||||
|
||||
[package]
|
||||
@@ -297,77 +268,32 @@ publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["core", "proxy"]
|
||||
core = ["proxy", "ak-common/core", "dep:pyo3", "dep:sqlx"]
|
||||
proxy = [
|
||||
"ak-common/proxy",
|
||||
"dep:ak-client",
|
||||
"dep:jsonwebtoken",
|
||||
"dep:axum-extra",
|
||||
"dep:aws-lc-rs",
|
||||
"dep:reqwest-middleware",
|
||||
"dep:moka",
|
||||
"dep:base64",
|
||||
"dep:regex",
|
||||
"dep:hyper",
|
||||
"dep:hyper-rustls",
|
||||
"dep:thiserror",
|
||||
"dep:askama",
|
||||
]
|
||||
core = ["ak-common/core", "dep:pyo3", "dep:sqlx"]
|
||||
proxy = ["ak-common/proxy"]
|
||||
|
||||
[build-dependencies]
|
||||
pyo3-build-config.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ak-axum.workspace = true
|
||||
ak-client = { workspace = true, optional = true }
|
||||
ak-common.workspace = true
|
||||
arc-swap.workspace = true
|
||||
argh.workspace = true
|
||||
askama = { workspace = true, optional = true }
|
||||
aws-lc-rs = { workspace = true, optional = true }
|
||||
base64 = { workspace = true, optional = true }
|
||||
axum-extra = { workspace = true, optional = true }
|
||||
axum-server.workspace = true
|
||||
axum.workspace = true
|
||||
color-eyre.workspace = true
|
||||
eyre.workspace = true
|
||||
futures.workspace = true
|
||||
http-body-util.workspace = true
|
||||
hyper = { workspace = true, optional = true }
|
||||
hyper-rustls = { workspace = true, optional = true }
|
||||
hyper-unix-socket.workspace = true
|
||||
hyper-util.workspace = true
|
||||
jsonwebtoken = { workspace = true, optional = true }
|
||||
metrics-exporter-prometheus.workspace = true
|
||||
metrics.workspace = true
|
||||
moka = { workspace = true, optional = true }
|
||||
metrics-exporter-prometheus.workspace = true
|
||||
nix.workspace = true
|
||||
pem.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
pyo3 = { workspace = true, optional = true }
|
||||
rand.workspace = true
|
||||
regex = { workspace = true, optional = true }
|
||||
reqwest-middleware = { workspace = true, optional = true }
|
||||
reqwest.workspace = true
|
||||
rustls.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_repr.workspace = true
|
||||
sqlx = { workspace = true, optional = true }
|
||||
thiserror = { workspace = true, optional = true }
|
||||
time.workspace = true
|
||||
tokio-retry2.workspace = true
|
||||
tokio-tungstenite.workspace = true
|
||||
tokio.workspace = true
|
||||
tower-http.workspace = true
|
||||
tower.workspace = true
|
||||
tracing.workspace = true
|
||||
url.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
rcgen.workspace = true
|
||||
tempfile.workspace = true
|
||||
which.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: gen dev-reset all test web docs core-install i18n-extract gen-locales locales-normalize install bump gen-changelog integrations
|
||||
.PHONY: gen dev-reset all clean test web docs
|
||||
|
||||
SHELL := /usr/bin/env bash
|
||||
.SHELLFLAGS += ${SHELLFLAGS} -e -o pipefail
|
||||
@@ -10,7 +10,7 @@ DOCKER_IMAGE ?= "authentik:test"
|
||||
|
||||
UNAME_S := $(shell uname -s)
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
SED_INPLACE = /usr/bin/sed -i ''
|
||||
SED_INPLACE = sed -i ''
|
||||
else
|
||||
SED_INPLACE = sed -i
|
||||
endif
|
||||
@@ -54,7 +54,7 @@ else
|
||||
NPM_VERSION = $(shell python -m scripts.generate_semver)
|
||||
endif
|
||||
|
||||
all: lint-fix lint gen web test ## Lint-fix, lint, generate the schema, generate the client libraries, lint the front end, run the python tests
|
||||
all: lint-fix lint gen web test ## Lint, build, and test everything
|
||||
|
||||
HELP_WIDTH := $(shell grep -h '^[a-z][^ ]*:.*\#\#' $(MAKEFILE_LIST) 2>/dev/null | \
|
||||
cut -d':' -f1 | awk '{printf "%d\n", length}' | sort -rn | head -1)
|
||||
@@ -70,38 +70,39 @@ go-test: ## Run the golang tests
|
||||
go test -timeout 0 -v -race -cover ./...
|
||||
|
||||
rust-test: ## Run the Rust tests
|
||||
$(CARGO) nextest run --workspace
|
||||
$(CARGO) nextest run --workspace --filterset 'kind(lib) | kind(proc-macro) | kind(bin) | kind(example)'
|
||||
|
||||
test: ## Run the server tests and produce a coverage report (locally). Usage: make test [path]
|
||||
test: ## Run the server tests and produce a coverage report (locally)
|
||||
$(UV) run coverage run manage.py test --keepdb $(or $(filter-out $@ all,$(MAKECMDGOALS)),authentik)
|
||||
$(UV) run coverage combine
|
||||
$(UV) run coverage html
|
||||
$(UV) run coverage report
|
||||
|
||||
lint-fix-rust: ## Format Rust sources (rustfmt)
|
||||
test-e2e-build-containers: ## Build containers for the e2e tests
|
||||
DOCKER_BUILDKIT=1 docker build . -f lifecycle/container/Dockerfile --progress plain --tag authentik.invalid/goauthentik/dev-server:gh-main --load
|
||||
DOCKER_BUILDKIT=1 docker build . -f lifecycle/container/proxy.Dockerfile --progress plain --tag authentik.invalid/goauthentik/dev-proxy:gh-main --load
|
||||
|
||||
test-e2e: ## Run the e2e tests
|
||||
$(CARGO) nextest run --workspace --filterset 'kind(test)'
|
||||
|
||||
lint-fix-rust:
|
||||
$(CARGO) +nightly fmt --all -- --config-path "${PWD}/.cargo/rustfmt.toml"
|
||||
|
||||
lint-fix: lint-fix-rust ## Format and automatically fix Python (black, ruff) and Rust (rustfmt) sources
|
||||
lint-fix: lint-fix-rust ## Lint and automatically fix errors in the python source code. Reports spelling errors.
|
||||
$(UV) run black $(PY_SOURCES)
|
||||
$(UV) run ruff check --fix $(PY_SOURCES)
|
||||
|
||||
lint-spellcheck: ## Reports spelling errors.
|
||||
npm run lint:spellcheck
|
||||
|
||||
lint-catalogs: ## Reports pnpm catalog pins, and pnpm's own version pin, that drifted between workspaces.
|
||||
lint-catalogs: ## Reports pnpm catalog pins that drifted between the root, web, and website workspaces.
|
||||
node ./scripts/node/lint-catalogs.ts
|
||||
|
||||
lint-locales: ## Reports translation files and generated locale lists that drifted from locales.yaml.
|
||||
$(UV) run python scripts/locales.py check
|
||||
|
||||
lint-check-types: ## Type-check the repository's Node.js scripts.
|
||||
pnpm run build:types
|
||||
|
||||
lint: ci-lint-bandit ci-lint-mypy ci-lint-cargo-deny ci-lint-cargo-machete ## Check Python (bandit, mypy), Go (golangci) and Rust dependencies (cargo deny, machete)
|
||||
golangci-lint run -v --config .github/golangci.yml
|
||||
lint: ci-lint-bandit ci-lint-mypy ci-lint-cargo-deny ci-lint-cargo-machete ## Lint the python and golang sources
|
||||
golangci-lint run -v
|
||||
|
||||
core-install:
|
||||
ifneq ($(BREW_EXISTS),)
|
||||
ifdef ($(BREW_EXISTS))
|
||||
# Clear cache to ensure fresh compilation
|
||||
$(UV) cache clean
|
||||
# Force compilation from source for lxml and xmlsec with correct environment
|
||||
@@ -110,18 +111,12 @@ else
|
||||
$(UV) sync --frozen
|
||||
endif
|
||||
|
||||
migrate: ## Apply and check system and Django migrations
|
||||
migrate: ## Run the Authentik Django server's migrations
|
||||
$(UV) run python -m lifecycle.migrate
|
||||
|
||||
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
|
||||
|
||||
gen-locales: ## Regenerate lit-localize.json, the web locale loaders, and the Transifex language mapping from locales.yaml
|
||||
$(UV) run python scripts/locales.py gen
|
||||
|
||||
locales-normalize: ## Move translation files that Transifex wrote under non-canonical names to their canonical paths
|
||||
$(UV) run python scripts/locales.py normalize
|
||||
|
||||
aws-cfn: node-install ## Generate the AWS Cloudformation template
|
||||
aws-cfn: node-install
|
||||
pnpm --dir lifecycle/aws install
|
||||
$(UV) run pnpm --dir lifecycle/aws run aws-cfn
|
||||
|
||||
@@ -129,10 +124,10 @@ run: ## Run the main authentik server and worker processes
|
||||
$(UV) run ak allinone
|
||||
|
||||
run-watch: ## Run the authentik server and worker, with auto reloading
|
||||
watchexec --on-busy-update=restart --stop-signal=SIGINT --exts py,rs --no-meta --notify -- $(UV) run ak allinone
|
||||
watchexec --on-busy-update=restart --stop-signal=SIGINT --exts py,rs,go --no-meta --notify -- $(UV) run ak allinone
|
||||
|
||||
core-i18n-extract:
|
||||
$(UV) run python -m manage makemessages \
|
||||
$(UV) run ak makemessages \
|
||||
--add-location file \
|
||||
--no-obsolete \
|
||||
--ignore web \
|
||||
@@ -141,7 +136,7 @@ core-i18n-extract:
|
||||
--ignore website \
|
||||
-l en
|
||||
|
||||
install: node-install web-install core-install ## Install all required dependencies for `node`, `web` and `core`
|
||||
install: node-install web-install core-install ## Install all requires dependencies for `node`, `web` and `core`
|
||||
|
||||
dev-drop-db:
|
||||
$(eval pg_user := $(shell $(UV) run python -m authentik.lib.config postgresql.user 2>/dev/null))
|
||||
@@ -157,10 +152,7 @@ dev-create-db:
|
||||
$(eval pg_name := $(shell $(UV) run python -m authentik.lib.config postgresql.name 2>/dev/null))
|
||||
createdb -U ${pg_user} -h ${pg_host} ${pg_name}
|
||||
|
||||
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the authentik PostgreSQL instance to a "fresh install" state.
|
||||
|
||||
make-migrations: ## Create Django migrations for model changes (pgtrigger-aware)
|
||||
$(UV) run ak makemigrations
|
||||
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
|
||||
|
||||
update-test-mmdb: ## Update test GeoIP and ASN Databases
|
||||
curl \
|
||||
@@ -188,10 +180,11 @@ endif
|
||||
## API Schema
|
||||
#########################
|
||||
|
||||
gen-build: ## Generate schema.yml and blueprints/schema.json from Django model definitions
|
||||
gen-build: ## Extract the schema from the database
|
||||
AUTHENTIK_DEBUG=true \
|
||||
AUTHENTIK_TENANTS__ENABLED=true \
|
||||
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
|
||||
$(UV) run python -m manage build_schema
|
||||
$(UV) run ak build_schema
|
||||
|
||||
gen-compose:
|
||||
$(UV) run scripts/generate_compose.py
|
||||
@@ -207,7 +200,7 @@ gen-changelog: ## (Release) generate the changelog based from the commits since
|
||||
rm merged_to_current
|
||||
rm merged_to_last
|
||||
rm cherry_picked_to_last
|
||||
pnpm exec oxfmt --write changelog.md
|
||||
npx prettier --write changelog.md
|
||||
|
||||
gen-diff: ## (Release) generate the changelog diff between the current schema and the last version
|
||||
$(eval last_version := $(shell git tag --list 'version/*' --sort 'version:refname' | grep -vE 'rc[0-9]+$$' | tail -1))
|
||||
@@ -220,7 +213,7 @@ gen-diff: ## (Release) generate the changelog diff between the current schema a
|
||||
rm schema-old.yml
|
||||
$(SED_INPLACE) 's/{/\{/g' diff.md
|
||||
$(SED_INPLACE) 's/}/\}/g' diff.md
|
||||
pnpm exec oxfmt --write diff.md
|
||||
npx prettier --write diff.md
|
||||
|
||||
gen-client-go: ## Build and install the authentik API for Golang
|
||||
$(UV) run make -C "${PWD}/packages/client-go" build
|
||||
@@ -251,54 +244,39 @@ gen-dev-config: ## Generate a local development config file
|
||||
# grants it arbitrary code execution at install — audit at review time.
|
||||
|
||||
node-preinstall: ## Verify the active Node.js and pnpm versions match what's in package.json.
|
||||
node ./scripts/node/lint-runtime.ts
|
||||
node ./scripts/node/lint-runtime.mjs
|
||||
|
||||
node-install: node-preinstall ## Install the necessary libraries to build Node.js packages and build the shared lint configs
|
||||
node-install: node-preinstall ## Install the necessary libraries to build Node.js packages
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm run build:lint-config
|
||||
|
||||
#########################
|
||||
## Web
|
||||
#########################
|
||||
|
||||
web-install: ## Install the necessary libraries to build the authentik front end
|
||||
web-install: ## Install the necessary libraries to build the Authentik UI
|
||||
pnpm --dir web install --frozen-lockfile
|
||||
|
||||
web-build: node-install ## Build the authentik front end
|
||||
web-build: node-install ## Build the Authentik UI
|
||||
pnpm --dir web run build
|
||||
|
||||
web: web-lint-fix web-lint web-check-compile ## Format and lint the front-end, run lit-analyzer and type-check
|
||||
web: web-lint-fix web-lint web-check-compile ## Automatically fix formatting issues in the Authentik UI source code, lint the code, and compile it
|
||||
|
||||
web-check: ## Run front-end lint and format checks (does no modifications)
|
||||
pnpm --dir web lint:check
|
||||
pnpm --dir web format:check
|
||||
|
||||
web-test-unit: ## Run web front-end tests once
|
||||
pnpm --dir web run test:unit
|
||||
|
||||
web-test: ## Run tests for the authentik front end in watch mode
|
||||
web-test: ## Run tests for the Authentik UI
|
||||
pnpm --dir web run test
|
||||
|
||||
web-test-e2e: ## Run front end Playwright end-to-end tests
|
||||
pnpm --dir web run test:e2e
|
||||
|
||||
web-test-visual: ## Run visual regression tests for the front-end
|
||||
pnpm --dir web run test:visual
|
||||
|
||||
web-watch: ## Build and watch the authentik front end for changes, updating automatically
|
||||
web-watch: ## Build and watch the Authentik UI for changes, updating automatically
|
||||
pnpm --dir web run watch
|
||||
|
||||
web-storybook-watch: ## Build and run the storybook documentation server
|
||||
pnpm --dir web run storybook
|
||||
|
||||
web-lint-fix: ## Format the front end source (oxfmt)
|
||||
pnpm --dir web run format
|
||||
web-lint-fix:
|
||||
pnpm --dir web run prettier
|
||||
|
||||
web-lint: ## Lint the front end (oxfmt) and run lit-analyzer
|
||||
web-lint:
|
||||
pnpm --dir web run lint
|
||||
pnpm --dir web run lit-analyse
|
||||
|
||||
web-check-compile: ## Type-check the front end
|
||||
web-check-compile:
|
||||
pnpm --dir web run tsc
|
||||
|
||||
web-i18n-extract:
|
||||
@@ -308,39 +286,30 @@ web-i18n-extract:
|
||||
## Docs
|
||||
#########################
|
||||
|
||||
docs: docs-lint-fix docs-build ## Spellcheck, format, and build the docs website
|
||||
docs: docs-lint-fix docs-build ## Automatically fix formatting issues in the Authentik docs source code, lint the code, and compile it
|
||||
|
||||
docs-install: node-install ## Install the necessary libraries to build the authentik documentation
|
||||
docs-install: node-install ## Install the necessary libraries to build the Authentik documentation
|
||||
pnpm --dir website install --frozen-lockfile
|
||||
|
||||
docs-lint-fix: lint-spellcheck ## Spellcheck and format the documentation site
|
||||
pnpm --dir website run lint
|
||||
pnpm --dir website run format
|
||||
docs-lint-fix: lint-spellcheck
|
||||
pnpm --dir website run prettier
|
||||
|
||||
docs-build: ## Build the docs website
|
||||
node ./scripts/node/lint-runtime.ts website
|
||||
docs-build:
|
||||
node ./scripts/node/lint-runtime.mjs website
|
||||
pnpm --dir website run build
|
||||
|
||||
docs-watch: ## Build and watch the topics documentation
|
||||
pnpm --dir website run start
|
||||
|
||||
docs-test: ## Run the documentation website tests
|
||||
pnpm --dir website run test
|
||||
integrations: docs-lint-fix integrations-build ## Fix formatting issues in the integrations source code, lint the code, and compile it
|
||||
|
||||
docs-check: ## Run documentation lint, typecheck, and format (does no modifications)
|
||||
pnpm --dir website run lint:check
|
||||
pnpm --dir website run build:types
|
||||
pnpm --dir website run format:check
|
||||
|
||||
integrations: docs-lint-fix integrations-build ## Spellcheck, format, and build the integrations website
|
||||
|
||||
integrations-build: ## Build the integrations website
|
||||
integrations-build:
|
||||
pnpm --dir website run build:integrations
|
||||
|
||||
integrations-watch: ## Build and watch the Integrations documentation
|
||||
pnpm --dir website/integrations run start
|
||||
|
||||
docs-api-build: ## Build the API reference site
|
||||
docs-api-build:
|
||||
pnpm --dir website run build:api
|
||||
|
||||
docs-api-watch: ## Build and watch the API documentation
|
||||
@@ -357,7 +326,7 @@ docs-api-clean: ## Clean generated API documentation
|
||||
docker: ## Build a docker image of the current source tree
|
||||
DOCKER_BUILDKIT=1 docker build . -f lifecycle/container/Dockerfile --progress plain --tag ${DOCKER_IMAGE}
|
||||
|
||||
test-docker: ## Build docker image and run full test suite in the container compose stack
|
||||
test-docker:
|
||||
BUILD=true ${PWD}/scripts/test_docker.sh
|
||||
|
||||
#########################
|
||||
@@ -387,7 +356,7 @@ ci-lint-bandit: ci--meta-debug
|
||||
$(UV) run bandit -c pyproject.toml -r $(PY_SOURCES) -iii
|
||||
|
||||
ci-lint-pending-migrations: ci--meta-debug
|
||||
$(UV) run python -m manage makemigrations --check
|
||||
$(UV) run ak makemigrations --check
|
||||
|
||||
ci-lint-cargo-deny: ci--meta-debug
|
||||
$(CARGO) deny --config "${PWD}/.cargo/deny.toml" --locked --workspace check
|
||||
@@ -399,21 +368,11 @@ ci-lint-rustfmt: ci--meta-debug
|
||||
$(CARGO) +nightly fmt --all --check -- --config-path "${PWD}/.cargo/rustfmt.toml"
|
||||
|
||||
ci-lint-clippy: ci--meta-debug
|
||||
$(CARGO) clippy --workspace --all-targets -- -D warnings
|
||||
$(CARGO) clippy --workspace -- -D warnings
|
||||
|
||||
ci-lint-catalogs: ci--meta-debug
|
||||
node ./scripts/node/lint-catalogs.ts
|
||||
|
||||
ci-lint-locales: ci--meta-debug
|
||||
$(UV) run python scripts/locales.py check
|
||||
|
||||
ci-lint-oxlint-fixtures: ci--meta-debug
|
||||
pnpm --filter @goauthentik/oxlint-config run build
|
||||
pnpm --filter @goauthentik/oxlint-config run verify
|
||||
|
||||
ci-lint-check-types: ci--meta-debug
|
||||
pnpm run build:types
|
||||
|
||||
ci-test: ci--meta-debug
|
||||
$(UV) run coverage run manage.py test --keepdb --parallel auto authentik
|
||||
$(UV) run coverage combine
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="https://docs.goauthentik.io/img/icon_top_brand_colour.svg" height="150" alt="authentik logo">
|
||||
<img src="https://goauthentik.io/img/icon_top_brand_colour.svg" height="150" alt="authentik logo">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
+13
-26
@@ -1,12 +1,12 @@
|
||||
authentik takes security very seriously. We follow the rules of [responsible disclosure](https://en.wikipedia.org/wiki/Responsible_disclosure), and we urge our community to do so as well, instead of reporting vulnerabilities publicly. This allows us to patch the issue quickly, announce its existence and release the fixed version.
|
||||
authentik takes security very seriously. We follow the rules of [responsible disclosure](https://en.wikipedia.org/wiki/Responsible_disclosure), and we urge our community to do so as well, instead of reporting vulnerabilities publicly. This allows us to patch the issue quickly, announce it's existence and release the fixed version.
|
||||
|
||||
## Independent audits and pentests
|
||||
|
||||
We are committed to engaging in regular pentesting and security audits of authentik. Defining and adhering to a cadence of external testing ensures a stronger probability that our code base, our features, and our architecture is as secure and non-exploitable as possible. For more details about specific audits and pentests, refer to [Audits and Certificates](https://docs.goauthentik.io/security/audits-and-certs/).
|
||||
We are committed to engaging in regular pentesting and security audits of authentik. Defining and adhering to a cadence of external testing ensures a stronger probability that our code base, our features, and our architecture is as secure and non-exploitable as possible. For more details about specific audits and pentests, refer to "Audits and Certificates" in our [Security documentation](https://docs.goauthentik.io/docs/security).
|
||||
|
||||
## What authentik classifies as a CVE
|
||||
|
||||
CVE (Common Vulnerability and Exposure) is a system designed to aggregate all vulnerabilities. As such, a CVE will be issued when there is either a vulnerability or exposure. Per NIST, A vulnerability is:
|
||||
CVE (Common Vulnerability and Exposure) is a system designed to aggregate all vulnerabilities. As such, a CVE will be issued when there is a either vulnerability or exposure. Per NIST, A vulnerability is:
|
||||
|
||||
“Weakness in an information system, system security procedures, internal controls, or implementation that could be exploited or triggered by a threat source.”
|
||||
|
||||
@@ -14,26 +14,21 @@ If it is determined that the issue does qualify as a CVE, a CVE number will be i
|
||||
|
||||
Even if the issue is not a CVE, we still greatly appreciate your help in hardening authentik.
|
||||
|
||||
## Our CNA
|
||||
|
||||
GitHub is the CNA (CVE Numbering Authority) for authentik. We request every authentik CVE ID from GitHub through the [repository security advisory](https://docs.github.com/en/code-security/security-advisories/working-with-repository-security-advisories/about-repository-security-advisories) that the report was filed under. This places authentik vulnerabilities in the scope of [GitHub, Inc. (CNA-2019-0009)](https://www.cve.org/PartnerInformation/ListofPartners/partner/GitHub_M).
|
||||
|
||||
Please do not reserve or assign a CVE ID for authentik from any other CNA, including your own. A second ID creates a duplicate record for the same vulnerability. If you have already reserved an ID, please withdraw it and use the ID that GitHub assigns.
|
||||
|
||||
GitHub reviews each request, so assignment can take several weeks. We publish the advisory without waiting for the ID, and the ID is added to the advisory once GitHub assigns it.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
(.x being the latest patch release for each version)
|
||||
|
||||
| Version | Supported |
|
||||
| --------- | --------- |
|
||||
| 2026.2.x | ✅ |
|
||||
| 2026.5.x | ✅ |
|
||||
| 2026.8.x | ✅ |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you discover a potential vulnerability, please report it responsibly by submitting a private security advisory via our [repository’s advisory portal](https://github.com/goauthentik/authentik/security/advisories/new).
|
||||
If you discover a potential vulnerability, please report it responsibly through one of the following channels:
|
||||
|
||||
- **Email**: [[email protected]](mailto:[email protected])
|
||||
- **GitHub**: Submit a private security advisory via our [repository’s advisory portal](https://github.com/goauthentik/authentik/security/advisories/new)
|
||||
|
||||
When submitting a report, please include as much detail as possible, such as:
|
||||
|
||||
@@ -101,22 +96,14 @@ The destinations of outgoing network requests (HTTP, TCP, etc.) made by authenti
|
||||
|
||||
## Disclosure process
|
||||
|
||||
1. Vulnerability is reported via a GitHub Security Advisory, as listed above.
|
||||
1. Report from Github or Issue is reported via Email as listed above.
|
||||
2. The authentik Security team will try to reproduce the issue and ask for more information if required.
|
||||
3. A severity level is assigned.
|
||||
4. If the issue qualifies as a CVE, a CVE ID is requested from GitHub, our CNA. See [Our CNA](#our-cna).
|
||||
5. A fix is created, and if possible tested by the issue reporter.
|
||||
6. The fix is backported to other supported versions, and if possible a workaround for other versions is created.
|
||||
7. An announcement is sent out with a fixed release date and severity level of the issue. The announcement will be sent at least 24 hours before the release of the security fix.
|
||||
8. The fixed version is released for the supported versions.
|
||||
9. The security advisory is published. If GitHub has not assigned the CVE ID by then, the ID is added to the advisory once it arrives.
|
||||
4. A fix is created, and if possible tested by the issue reporter.
|
||||
5. The fix is backported to other supported versions, and if possible a workaround for other versions is created.
|
||||
6. An announcement is sent out with a fixed release date and severity level of the issue. The announcement will be sent at least 24 hours before the release of the security fix.
|
||||
7. The fixed version is released for the supported versions.
|
||||
|
||||
## Getting security notifications
|
||||
|
||||
To get security notifications, subscribe to the mailing list [here](https://groups.google.com/g/authentik-security-announcements) or join the [discord](https://goauthentik.io/discord) server.
|
||||
|
||||
## Contact
|
||||
|
||||
For general inquiries, you can reach the authentik Security team at [[email protected]](mailto:[email protected]).
|
||||
|
||||
_Please do not use email for vulnerability reports, instead use our [repository’s advisory portal](https://github.com/goauthentik/authentik/security/advisories/new)._
|
||||
@@ -3,8 +3,8 @@
|
||||
from functools import lru_cache
|
||||
from os import environ
|
||||
|
||||
VERSION = "2026.11.0-rc1"
|
||||
VERSION_FAMILY_PREVIOUS = "2026.8"
|
||||
VERSION = "2026.8.0-rc1"
|
||||
VERSION_FAMILY_PREVIOUS = "2026.5"
|
||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from authentik import authentik_full_version
|
||||
from authentik.admin.utils import get_system_settings
|
||||
from authentik.core.api.utils import PassiveSerializer
|
||||
from authentik.lib.config import CONFIG
|
||||
from authentik.lib.utils.reflection import get_env
|
||||
@@ -59,7 +58,6 @@ class SystemInfoSerializer(PassiveSerializer):
|
||||
server_time = SerializerMethodField()
|
||||
embedded_outpost_disabled = SerializerMethodField()
|
||||
embedded_outpost_host = SerializerMethodField()
|
||||
base_url = SerializerMethodField()
|
||||
|
||||
def get_http_headers(self, request: Request) -> dict[str, str]:
|
||||
"""Get HTTP Request headers"""
|
||||
@@ -116,10 +114,6 @@ class SystemInfoSerializer(PassiveSerializer):
|
||||
return ""
|
||||
return outposts.first().config.authentik_host
|
||||
|
||||
def get_base_url(self, request: Request) -> str:
|
||||
"""Configured external base URL. Can be empty"""
|
||||
return get_system_settings().base_url
|
||||
|
||||
|
||||
class SystemView(APIView):
|
||||
"""Get system information."""
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""authentik administration overview"""
|
||||
|
||||
from django.core.cache import cache
|
||||
from django_tenants.utils import get_public_schema_name
|
||||
from drf_spectacular.utils import extend_schema
|
||||
from packaging.version import parse
|
||||
from rest_framework.fields import SerializerMethodField
|
||||
@@ -9,9 +11,10 @@ from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from authentik import authentik_build_hash, authentik_version
|
||||
from authentik.admin.tasks import UpdateVersionInfo
|
||||
from authentik.admin.tasks import VERSION_CACHE_KEY, VERSION_NULL, update_latest_version
|
||||
from authentik.core.api.utils import PassiveSerializer
|
||||
from authentik.outposts.models import Outpost
|
||||
from authentik.tenants.utils import get_current_tenant
|
||||
|
||||
|
||||
class VersionSerializer(PassiveSerializer):
|
||||
@@ -19,6 +22,7 @@ class VersionSerializer(PassiveSerializer):
|
||||
|
||||
version_current = SerializerMethodField()
|
||||
version_latest = SerializerMethodField()
|
||||
version_latest_valid = SerializerMethodField()
|
||||
build_hash = SerializerMethodField()
|
||||
outdated = SerializerMethodField()
|
||||
outpost_outdated = SerializerMethodField()
|
||||
@@ -31,16 +35,23 @@ class VersionSerializer(PassiveSerializer):
|
||||
"""Get current version"""
|
||||
return authentik_version()
|
||||
|
||||
def get_version_latest(self, _) -> UpdateVersionInfo:
|
||||
def get_version_latest(self, _) -> str:
|
||||
"""Get latest version from cache"""
|
||||
return UpdateVersionInfo.get_cached().model_dump(mode="json")
|
||||
if get_current_tenant().schema_name != get_public_schema_name():
|
||||
return authentik_version()
|
||||
version_in_cache = cache.get(VERSION_CACHE_KEY)
|
||||
if not version_in_cache: # pragma: no cover
|
||||
update_latest_version.send()
|
||||
return authentik_version()
|
||||
return version_in_cache
|
||||
|
||||
def get_version_latest_valid(self, _) -> bool:
|
||||
"""Check if latest version is valid"""
|
||||
return cache.get(VERSION_CACHE_KEY) != VERSION_NULL
|
||||
|
||||
def get_outdated(self, instance) -> bool:
|
||||
"""Check if we're running the latest version"""
|
||||
cached = UpdateVersionInfo.get_cached()
|
||||
if not cached:
|
||||
return False
|
||||
return parse(self.get_version_current(instance)) < parse(cached.version)
|
||||
return parse(self.get_version_current(instance)) < parse(self.get_version_latest(instance))
|
||||
|
||||
def get_outpost_outdated(self, _) -> bool:
|
||||
"""Check if any outpost is outdated/has a version mismatch"""
|
||||
|
||||
+2
-47
@@ -1,25 +1,15 @@
|
||||
"""authentik admin app config"""
|
||||
|
||||
from django.db import DEFAULT_DB_ALIAS
|
||||
from django.db.models.signals import post_migrate
|
||||
from prometheus_client import Info
|
||||
|
||||
from authentik.blueprints.apps import ManagedAppConfig
|
||||
from authentik.lib.config import CONFIG
|
||||
from authentik.lib.utils.time import fqdn_rand
|
||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||
from authentik.tasks.schedules.common import ScheduleSpec
|
||||
|
||||
PROM_INFO = Info("authentik_version", "Currently running authentik version")
|
||||
|
||||
|
||||
def ensure_system_settings(*args, using=DEFAULT_DB_ALIAS, **kwargs):
|
||||
"""Make sure the system settings exist"""
|
||||
from authentik.admin.models import SystemSettings
|
||||
|
||||
SystemSettings.objects.using(using).get_or_create(pk=True)
|
||||
|
||||
|
||||
class AuthentikAdminConfig(ManagedAppConfig):
|
||||
"""authentik admin app config"""
|
||||
|
||||
@@ -28,42 +18,7 @@ class AuthentikAdminConfig(ManagedAppConfig):
|
||||
verbose_name = "authentik Admin"
|
||||
default = True
|
||||
|
||||
@ManagedAppConfig.reconcile
|
||||
def system_settings(self):
|
||||
"""Make sure the system settings exist, especially after a migration"""
|
||||
post_migrate.connect(ensure_system_settings)
|
||||
ensure_system_settings()
|
||||
self._backfill_base_url()
|
||||
|
||||
def _backfill_base_url(self):
|
||||
"""Backfill base_url when it hasn't been set yet. Sources: AUTHENTIK_WEB__BASE_URL config
|
||||
value, then the embedded outpost's configured host."""
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
from authentik.admin.models import SystemSettings
|
||||
from authentik.admin.utils import get_system_settings, normalize_base_url
|
||||
from authentik.outposts.models import Outpost
|
||||
|
||||
settings = get_system_settings()
|
||||
if settings.base_url:
|
||||
return # Already set
|
||||
base_url = normalize_base_url(CONFIG.get("web.base_url", ""))
|
||||
if not base_url:
|
||||
outpost = Outpost.objects.filter(managed=MANAGED_OUTPOST).first()
|
||||
if outpost:
|
||||
base_url = normalize_base_url(outpost.config.authentik_host)
|
||||
if base_url:
|
||||
try:
|
||||
SystemSettings._meta.get_field("base_url").run_validators(base_url)
|
||||
except ValidationError:
|
||||
self.logger.warning("Discarding invalid base_url", base_url=base_url)
|
||||
base_url = ""
|
||||
if not base_url: # No source available
|
||||
return
|
||||
SystemSettings.objects.filter(pk=settings.pk).update(base_url=base_url)
|
||||
self.logger.info("Backfilled base_url", base_url=base_url)
|
||||
|
||||
@ManagedAppConfig.reconcile
|
||||
@ManagedAppConfig.reconcile_global
|
||||
def clear_update_notifications(self):
|
||||
"""Clear update notifications on startup if the notification was for the version
|
||||
we're running now."""
|
||||
@@ -80,7 +35,7 @@ class AuthentikAdminConfig(ManagedAppConfig):
|
||||
notification.delete()
|
||||
|
||||
@property
|
||||
def schedule_specs(self) -> list[ScheduleSpec]:
|
||||
def global_schedule_specs(self) -> list[ScheduleSpec]:
|
||||
from authentik.admin.tasks import update_latest_version
|
||||
|
||||
return [
|
||||
|
||||
@@ -68,22 +68,24 @@ class FileView(APIView):
|
||||
# Backend is source of truth - list all files from storage
|
||||
manager = get_file_manager(usage)
|
||||
files = manager.list_files(manageable_only=params.get("manageable_only", False))
|
||||
search_query = params.get("search", "").lower()
|
||||
search_query = params.get("search", "")
|
||||
if search_query:
|
||||
files = filter(lambda file: search_query in file.lower(), files)
|
||||
files = [
|
||||
{
|
||||
"name": file,
|
||||
"url": manager.file_url(file, request),
|
||||
"mime_type": get_content_type(file),
|
||||
"themed_urls": manager.themed_urls(file, request),
|
||||
}
|
||||
FileView.FileListSerializer(
|
||||
data={
|
||||
"name": file,
|
||||
"url": manager.file_url(file, request),
|
||||
"mime_type": get_content_type(file),
|
||||
"themed_urls": manager.themed_urls(file, request),
|
||||
}
|
||||
)
|
||||
for file in files
|
||||
]
|
||||
serializer = FileView.FileListSerializer(data=files, many=True)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
for file in files:
|
||||
file.is_valid(raise_exception=True)
|
||||
|
||||
return Response(serializer.data)
|
||||
return Response([file.data for file in files])
|
||||
|
||||
class FileUploadSerializer(PassiveSerializer):
|
||||
file = FileField(required=True)
|
||||
|
||||
@@ -92,7 +92,6 @@ class FileBackend(ManageableBackend):
|
||||
"nbf": now() - timedelta(seconds=15),
|
||||
},
|
||||
key=sha256(f"{settings.SECRET_KEY}:{self.usage}".encode()).hexdigest(),
|
||||
# Must match src/server/static.rs
|
||||
algorithm="HS256",
|
||||
)
|
||||
url = f"{prefix}/files/{path}?token={token}"
|
||||
|
||||
@@ -120,7 +120,7 @@ class TestFileAPI(FileTestFileBackendMixin, TestCase):
|
||||
reverse(
|
||||
"authentik_api:files",
|
||||
query={
|
||||
"search": "LDAP.PNG",
|
||||
"search": "ldap.png",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
|
||||
from authentik.admin.utils import system_settings_cache
|
||||
|
||||
|
||||
class SystemSettingsMiddleware:
|
||||
"""Read the system settings at most once per request"""
|
||||
|
||||
get_response: Callable[[HttpRequest], HttpResponse]
|
||||
|
||||
def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request: HttpRequest) -> HttpResponse:
|
||||
with system_settings_cache():
|
||||
return self.get_response(request)
|
||||
@@ -1,220 +0,0 @@
|
||||
# Generated by Django 5.2.17 on 2026-09-15 08:23
|
||||
|
||||
from json import loads
|
||||
import authentik.lib.models
|
||||
import authentik.lib.utils.time
|
||||
import django.core.validators
|
||||
from authentik.lib.config import CONFIG
|
||||
from django.db import connections, migrations, models
|
||||
|
||||
JSON_FIELDS = ("footer_links", "flags")
|
||||
|
||||
FIELDS = [
|
||||
"avatars",
|
||||
"base_url",
|
||||
"default_user_change_name",
|
||||
"default_user_change_email",
|
||||
"default_user_change_username",
|
||||
"event_retention",
|
||||
"reputation_lower_limit",
|
||||
"reputation_upper_limit",
|
||||
"footer_links",
|
||||
"gdpr_compliance",
|
||||
"impersonation",
|
||||
"impersonation_require_reason",
|
||||
"default_token_duration",
|
||||
"default_token_length",
|
||||
"pagination_default_page_size",
|
||||
"pagination_max_page_size",
|
||||
"flags",
|
||||
]
|
||||
|
||||
|
||||
def create_system_settings(apps, schema_editor):
|
||||
db_alias = schema_editor.connection.alias
|
||||
SystemSettings = apps.get_model("authentik_admin", "SystemSettings")
|
||||
if SystemSettings.objects.using(db_alias).exists():
|
||||
return
|
||||
|
||||
settings = {}
|
||||
with connections[db_alias].cursor() as cursor:
|
||||
cursor.execute(
|
||||
"SELECT 1 FROM information_schema.tables WHERE table_name = 'authentik_tenants_tenant'"
|
||||
)
|
||||
if cursor.fetchone() is not None:
|
||||
cursor.execute(
|
||||
f"SELECT {', '.join(FIELDS)} FROM authentik_tenants_tenant WHERE schema_name = %s", # nosec
|
||||
[CONFIG.get("postgresql.default_schema")],
|
||||
)
|
||||
tenant = cursor.fetchone()
|
||||
if tenant is not None:
|
||||
settings = dict(zip(FIELDS, tenant, strict=True))
|
||||
# The raw cursor returns jsonb as str, which JSONField would encode again
|
||||
for field in JSON_FIELDS:
|
||||
if isinstance(settings[field], str):
|
||||
settings[field] = loads(settings[field])
|
||||
|
||||
SystemSettings.objects.using(db_alias).create(**settings)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
("authentik_tenants", "0009_alter_tenant_base_url"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="VersionHistory",
|
||||
fields=[
|
||||
("id", models.BigAutoField(primary_key=True, serialize=False)),
|
||||
("timestamp", models.DateTimeField()),
|
||||
("version", models.TextField()),
|
||||
("build", models.TextField()),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "Version history",
|
||||
"verbose_name_plural": "Version history",
|
||||
"db_table": "authentik_version_history",
|
||||
"ordering": ("-timestamp",),
|
||||
"managed": False,
|
||||
"default_permissions": [],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name="SystemSettings",
|
||||
fields=[
|
||||
("id", models.BooleanField(default=True, primary_key=True, serialize=False)),
|
||||
(
|
||||
"avatars",
|
||||
models.TextField(
|
||||
default="gravatar,initials",
|
||||
help_text="Configure how authentik should show avatars for users.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"base_url",
|
||||
models.TextField(
|
||||
blank=True,
|
||||
default="",
|
||||
help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
|
||||
validators=[
|
||||
authentik.lib.models.DomainlessURLValidator(
|
||||
message="Enter a valid URL, for example https://authentik.company",
|
||||
schemes=("http", "https"),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"default_user_change_name",
|
||||
models.BooleanField(
|
||||
default=True, help_text="Enable the ability for users to change their name."
|
||||
),
|
||||
),
|
||||
(
|
||||
"default_user_change_email",
|
||||
models.BooleanField(
|
||||
default=False,
|
||||
help_text="Enable the ability for users to change their email address.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"default_user_change_username",
|
||||
models.BooleanField(
|
||||
default=False,
|
||||
help_text="Enable the ability for users to change their username.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"event_retention",
|
||||
models.TextField(
|
||||
default="days=365",
|
||||
help_text="Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3,seconds=2).",
|
||||
validators=[authentik.lib.utils.time.timedelta_string_validator],
|
||||
),
|
||||
),
|
||||
(
|
||||
"reputation_lower_limit",
|
||||
models.IntegerField(
|
||||
default=-5,
|
||||
help_text="Reputation cannot decrease lower than this value. Zero or negative.",
|
||||
validators=[django.core.validators.MaxValueValidator(0)],
|
||||
),
|
||||
),
|
||||
(
|
||||
"reputation_upper_limit",
|
||||
models.IntegerField(
|
||||
default=5,
|
||||
help_text="Reputation cannot increase higher than this value. Zero or positive.",
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
),
|
||||
),
|
||||
(
|
||||
"footer_links",
|
||||
models.JSONField(
|
||||
blank=True,
|
||||
default=list,
|
||||
help_text="The option configures the footer links on the flow executor pages.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"gdpr_compliance",
|
||||
models.BooleanField(
|
||||
default=True,
|
||||
help_text="When enabled, all the events caused by a user will be deleted upon the user's deletion.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"impersonation",
|
||||
models.BooleanField(
|
||||
default=True, help_text="Globally enable/disable impersonation."
|
||||
),
|
||||
),
|
||||
(
|
||||
"impersonation_require_reason",
|
||||
models.BooleanField(
|
||||
default=True,
|
||||
help_text="Require administrators to provide a reason for impersonating a user.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"default_token_duration",
|
||||
models.TextField(
|
||||
default="days=1",
|
||||
help_text="Default token duration",
|
||||
validators=[authentik.lib.utils.time.timedelta_string_validator],
|
||||
),
|
||||
),
|
||||
(
|
||||
"default_token_length",
|
||||
models.PositiveIntegerField(
|
||||
default=60,
|
||||
help_text="Default token length",
|
||||
validators=[django.core.validators.MinValueValidator(1)],
|
||||
),
|
||||
),
|
||||
(
|
||||
"pagination_default_page_size",
|
||||
models.PositiveIntegerField(
|
||||
default=20,
|
||||
help_text="Default page size for API responses, if no size was requested.",
|
||||
),
|
||||
),
|
||||
(
|
||||
"pagination_max_page_size",
|
||||
models.PositiveIntegerField(default=100, help_text="Maximum page size"),
|
||||
),
|
||||
("flags", models.JSONField(default=dict)),
|
||||
],
|
||||
options={
|
||||
"verbose_name": "System settings",
|
||||
"verbose_name_plural": "System settings",
|
||||
"default_permissions": [],
|
||||
},
|
||||
bases=(authentik.lib.models.InternallyManagedMixin, models.Model),
|
||||
),
|
||||
migrations.RunPython(code=create_system_settings, reverse_code=migrations.RunPython.noop),
|
||||
]
|
||||
@@ -1,28 +0,0 @@
|
||||
# Generated by Django 5.2.17 on 2026-09-30 08:15
|
||||
|
||||
import authentik.lib.models
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("authentik_admin", "0001_initial"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="systemsettings",
|
||||
name="base_url",
|
||||
field=models.TextField(
|
||||
default="",
|
||||
help_text="Configure the base URL under which this authentik instance is reachable, e.g. https://authentik.company",
|
||||
validators=[
|
||||
authentik.lib.models.DomainlessURLValidator(
|
||||
message="Enter a valid URL, for example https://authentik.company",
|
||||
schemes=("http", "https"),
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
]
|
||||
+1
-124
@@ -1,130 +1,7 @@
|
||||
"""authentik admin models"""
|
||||
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import IntegrityError, models
|
||||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from rest_framework.serializers import Serializer
|
||||
|
||||
from authentik.lib.models import (
|
||||
DomainlessURLValidator,
|
||||
InternallyManagedMixin,
|
||||
SerializerModel,
|
||||
)
|
||||
from authentik.lib.utils.time import timedelta_string_validator
|
||||
|
||||
DEFAULT_TOKEN_DURATION = "days=1" # nosec
|
||||
DEFAULT_TOKEN_LENGTH = 60
|
||||
DEFAULT_REPUTATION_LOWER_LIMIT = -5
|
||||
DEFAULT_REPUTATION_UPPER_LIMIT = 5
|
||||
|
||||
|
||||
class SystemSettings(InternallyManagedMixin, SerializerModel):
|
||||
"""Global settings for this authentik instance"""
|
||||
|
||||
id = models.BooleanField(primary_key=True, default=True)
|
||||
|
||||
avatars = models.TextField(
|
||||
help_text=_("Configure how authentik should show avatars for users."),
|
||||
default="gravatar,initials",
|
||||
)
|
||||
base_url = models.TextField(
|
||||
default="",
|
||||
validators=[
|
||||
DomainlessURLValidator(
|
||||
schemes=("http", "https"),
|
||||
message=_("Enter a valid URL, for example https://authentik.company"),
|
||||
)
|
||||
],
|
||||
help_text=_(
|
||||
"Configure the base URL under which this authentik instance is "
|
||||
"reachable, e.g. https://authentik.company"
|
||||
),
|
||||
)
|
||||
default_user_change_name = models.BooleanField(
|
||||
help_text=_("Enable the ability for users to change their name."), default=True
|
||||
)
|
||||
default_user_change_email = models.BooleanField(
|
||||
help_text=_("Enable the ability for users to change their email address."), default=False
|
||||
)
|
||||
default_user_change_username = models.BooleanField(
|
||||
help_text=_("Enable the ability for users to change their username."), default=False
|
||||
)
|
||||
event_retention = models.TextField(
|
||||
default="days=365",
|
||||
validators=[timedelta_string_validator],
|
||||
help_text=_(
|
||||
"Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3,seconds=2)."
|
||||
),
|
||||
)
|
||||
reputation_lower_limit = models.IntegerField(
|
||||
help_text=_("Reputation cannot decrease lower than this value. Zero or negative."),
|
||||
default=DEFAULT_REPUTATION_LOWER_LIMIT,
|
||||
validators=[MaxValueValidator(0)],
|
||||
)
|
||||
reputation_upper_limit = models.IntegerField(
|
||||
help_text=_("Reputation cannot increase higher than this value. Zero or positive."),
|
||||
default=DEFAULT_REPUTATION_UPPER_LIMIT,
|
||||
validators=[MinValueValidator(0)],
|
||||
)
|
||||
footer_links = models.JSONField(
|
||||
help_text=_("The option configures the footer links on the flow executor pages."),
|
||||
default=list,
|
||||
blank=True,
|
||||
)
|
||||
gdpr_compliance = models.BooleanField(
|
||||
help_text=_(
|
||||
"When enabled, all the events caused by a user "
|
||||
"will be deleted upon the user's deletion."
|
||||
),
|
||||
default=True,
|
||||
)
|
||||
impersonation = models.BooleanField(
|
||||
help_text=_("Globally enable/disable impersonation."), default=True
|
||||
)
|
||||
impersonation_require_reason = models.BooleanField(
|
||||
help_text=_("Require administrators to provide a reason for impersonating a user."),
|
||||
default=True,
|
||||
)
|
||||
default_token_duration = models.TextField(
|
||||
help_text=_("Default token duration"),
|
||||
default=DEFAULT_TOKEN_DURATION,
|
||||
validators=[timedelta_string_validator],
|
||||
)
|
||||
default_token_length = models.PositiveIntegerField(
|
||||
help_text=_("Default token length"),
|
||||
default=DEFAULT_TOKEN_LENGTH,
|
||||
validators=[MinValueValidator(1)],
|
||||
)
|
||||
|
||||
pagination_default_page_size = models.PositiveIntegerField(
|
||||
help_text=_("Default page size for API responses, if no size was requested."),
|
||||
default=20,
|
||||
)
|
||||
pagination_max_page_size = models.PositiveIntegerField(
|
||||
help_text=_("Maximum page size"),
|
||||
default=100,
|
||||
)
|
||||
|
||||
flags = models.JSONField(default=dict)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.pk:
|
||||
raise IntegrityError("Only one instance of system settings is allowed")
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
@property
|
||||
def serializer(self) -> Serializer:
|
||||
from authentik.admin.api.settings import SettingsSerializer
|
||||
|
||||
return SettingsSerializer
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "System settings"
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("System settings")
|
||||
verbose_name_plural = _("System settings")
|
||||
default_permissions = []
|
||||
|
||||
|
||||
class VersionHistory(models.Model):
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
|
||||
from authentik.admin.models import SystemSettings
|
||||
from authentik.admin.tasks import _set_prom_info
|
||||
from authentik.admin.utils import clear_system_settings_cache
|
||||
from authentik.root.signals import post_startup
|
||||
|
||||
|
||||
@receiver(post_startup)
|
||||
def post_startup_admin_metrics(sender, **_):
|
||||
_set_prom_info()
|
||||
|
||||
|
||||
@receiver(post_save, sender=SystemSettings)
|
||||
def system_settings_saved(**_):
|
||||
clear_system_settings_cache()
|
||||
+17
-62
@@ -1,12 +1,9 @@
|
||||
"""authentik admin tasks"""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
from django.core.cache import cache
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from dramatiq import actor
|
||||
from packaging.version import parse
|
||||
from pydantic import BaseModel, Field, HttpUrl, ValidationError
|
||||
from requests import RequestException
|
||||
from structlog.stdlib import get_logger
|
||||
|
||||
@@ -18,10 +15,10 @@ from authentik.lib.utils.http import get_http_session
|
||||
from authentik.tasks.middleware import CurrentTask
|
||||
|
||||
LOGGER = get_logger()
|
||||
VERSION_CACHE_KEY = "goauthentik.io/admin/latest_version"
|
||||
VERSION_NULL = "0.0.0"
|
||||
VERSION_CACHE_KEY = "authentik_latest_version"
|
||||
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
|
||||
LOCAL_VERSION = parse(authentik_version())
|
||||
VERSION_URL = "https://version.goauthentik.io/versions/authentik/latest.json"
|
||||
|
||||
|
||||
def _set_prom_info():
|
||||
@@ -29,90 +26,48 @@ def _set_prom_info():
|
||||
PROM_INFO.info(
|
||||
{
|
||||
"version": authentik_version(),
|
||||
"latest": UpdateVersionInfo.get_cached().version,
|
||||
"latest": cache.get(VERSION_CACHE_KEY, ""),
|
||||
"build_hash": authentik_build_hash(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class UpdateVersionReason(StrEnum):
|
||||
"""Reason why an authentik update was released"""
|
||||
|
||||
bugfix = "bugfix"
|
||||
feature = "feature"
|
||||
security = "security"
|
||||
other = "other"
|
||||
|
||||
|
||||
class UpdateVersionInfo(BaseModel):
|
||||
version: str
|
||||
changelog: str
|
||||
changelog_url: HttpUrl
|
||||
reason: UpdateVersionReason
|
||||
valid: bool = Field(default=True)
|
||||
|
||||
@staticmethod
|
||||
def get_invalid() -> UpdateVersionInfo:
|
||||
return UpdateVersionInfo(
|
||||
version="0.0.0",
|
||||
changelog="",
|
||||
changelog_url="https://docs.goauthentik.io",
|
||||
reason=UpdateVersionReason.other,
|
||||
valid=False,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_cached() -> UpdateVersionInfo:
|
||||
return cache.get(VERSION_CACHE_KEY, UpdateVersionInfo.get_invalid())
|
||||
|
||||
@staticmethod
|
||||
def cache_invalid():
|
||||
cache.set(
|
||||
VERSION_CACHE_KEY,
|
||||
UpdateVersionInfo(
|
||||
version="0.0.0",
|
||||
changelog="",
|
||||
changelog_url="",
|
||||
reason=UpdateVersionReason.other,
|
||||
valid=False,
|
||||
),
|
||||
VERSION_CACHE_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
@actor(description=_("Update latest version info."))
|
||||
def update_latest_version():
|
||||
self = CurrentTask.get_task()
|
||||
if CONFIG.get_bool("disable_update_check"):
|
||||
UpdateVersionInfo.cache_invalid()
|
||||
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
|
||||
self.info("Version check disabled.")
|
||||
return
|
||||
try:
|
||||
response = get_http_session().get(VERSION_URL)
|
||||
response = get_http_session().get(
|
||||
"https://version.goauthentik.io/version.json",
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
upstream_version = UpdateVersionInfo.model_validate(data.get("stable", {}))
|
||||
upstream_version = data.get("stable", {}).get("version")
|
||||
cache.set(VERSION_CACHE_KEY, upstream_version, VERSION_CACHE_TIMEOUT)
|
||||
self.info("Successfully updated latest Version")
|
||||
_set_prom_info()
|
||||
# Check if upstream version is newer than what we're running,
|
||||
# and if no event exists yet, create one.
|
||||
if LOCAL_VERSION < parse(upstream_version.version):
|
||||
if LOCAL_VERSION < parse(upstream_version):
|
||||
# Event has already been created, don't create duplicate
|
||||
if Event.objects.filter(
|
||||
action=EventAction.UPDATE_AVAILABLE,
|
||||
context__new_version=upstream_version.version,
|
||||
context__new_version=upstream_version,
|
||||
).exists():
|
||||
return
|
||||
Event.new(
|
||||
EventAction.UPDATE_AVAILABLE,
|
||||
message=_(
|
||||
"New version {version} available!".format(version=upstream_version.version)
|
||||
"New version {version} available!".format(
|
||||
version=upstream_version,
|
||||
)
|
||||
),
|
||||
new_version=upstream_version.version,
|
||||
changelog=upstream_version.changelog_url,
|
||||
reason=upstream_version.reason,
|
||||
new_version=upstream_version,
|
||||
changelog=data.get("stable", {}).get("changelog_url"),
|
||||
).save()
|
||||
except (RequestException, IndexError, ValidationError) as exc:
|
||||
UpdateVersionInfo.cache_invalid()
|
||||
except (RequestException, IndexError) as exc:
|
||||
cache.set(VERSION_CACHE_KEY, VERSION_NULL, VERSION_CACHE_TIMEOUT)
|
||||
raise exc
|
||||
@@ -1,74 +0,0 @@
|
||||
"""Tests for backfilling base_url during the system settings reconcile"""
|
||||
|
||||
from django.apps import apps
|
||||
from django.test import TestCase
|
||||
|
||||
from authentik.admin.utils import get_system_settings
|
||||
from authentik.blueprints.tests import reconcile_app
|
||||
from authentik.events.logs import capture_logs
|
||||
from authentik.lib.config import CONFIG
|
||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||
from authentik.outposts.models import Outpost, OutpostConfig
|
||||
|
||||
|
||||
class TestBaseURLBackfill(TestCase):
|
||||
"""The system settings reconcile seeds base_url from the config value or the embedded
|
||||
outpost host"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.settings = get_system_settings()
|
||||
self.settings.base_url = ""
|
||||
self.settings.save()
|
||||
|
||||
@reconcile_app("authentik_outposts")
|
||||
def test_backfill_from_outpost(self):
|
||||
"""base_url is backfilled from the embedded outpost host, without a trailing slash"""
|
||||
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
|
||||
outpost.config = OutpostConfig(authentik_host="https://outpost.example.com/")
|
||||
outpost.save()
|
||||
with CONFIG.patch("web.base_url", ""):
|
||||
apps.get_app_config("authentik_admin").system_settings()
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://outpost.example.com")
|
||||
|
||||
@reconcile_app("authentik_outposts")
|
||||
def test_backfill_from_config(self):
|
||||
"""The AUTHENTIK_WEB__BASE_URL config value takes precedence over the outpost host"""
|
||||
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
|
||||
outpost.config = OutpostConfig(authentik_host="https://outpost.example.com")
|
||||
outpost.save()
|
||||
with CONFIG.patch("web.base_url", "https://config.example.com"):
|
||||
apps.get_app_config("authentik_admin").system_settings()
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://config.example.com")
|
||||
|
||||
def test_backfill_does_not_overwrite(self):
|
||||
"""A configured base_url is never overwritten by the backfill"""
|
||||
self.settings.base_url = "https://set.example.com"
|
||||
self.settings.save()
|
||||
with CONFIG.patch("web.base_url", "https://config.example.com"):
|
||||
apps.get_app_config("authentik_admin").system_settings()
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://set.example.com")
|
||||
|
||||
@reconcile_app("authentik_outposts")
|
||||
def test_backfill_discards_invalid_outpost_host(self):
|
||||
"""An outpost host the settings API would reject is discarded rather than written,
|
||||
since the backfill's `.update()` skips field validation"""
|
||||
outpost = Outpost.objects.get(managed=MANAGED_OUTPOST)
|
||||
outpost.config = OutpostConfig(authentik_host="outpost.example.com")
|
||||
outpost.save()
|
||||
with CONFIG.patch("web.base_url", ""), capture_logs() as logs:
|
||||
apps.get_app_config("authentik_admin").system_settings()
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "")
|
||||
self.assertTrue(any("Discarding invalid base_url" in log.event for log in logs))
|
||||
|
||||
def test_backfill_no_outpost(self):
|
||||
"""With no embedded outpost and no config value, base_url stays empty"""
|
||||
Outpost.objects.filter(managed=MANAGED_OUTPOST).delete()
|
||||
with CONFIG.patch("web.base_url", ""):
|
||||
apps.get_app_config("authentik_admin").system_settings()
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "")
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Tests for the base_url setting's admin API surface"""
|
||||
|
||||
from django.urls import reverse
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
from authentik.admin.utils import get_system_settings
|
||||
from authentik.core.tests.utils import create_test_admin_user
|
||||
|
||||
|
||||
class TestBaseURLSettings(APITestCase):
|
||||
"""base_url read and written through the admin settings and system-info APIs"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.settings = get_system_settings()
|
||||
self.settings.base_url = ""
|
||||
self.settings.save()
|
||||
self.client.force_login(create_test_admin_user())
|
||||
|
||||
def test_settings_roundtrip(self):
|
||||
"""base_url can be written and read back through the settings API"""
|
||||
response = self.client.patch(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={"base_url": "https://authentik.company"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://authentik.company")
|
||||
|
||||
def test_settings_rejects_invalid(self):
|
||||
"""A value that is not a URL is rejected"""
|
||||
response = self.client.patch(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={"base_url": "not-a-url"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
def test_settings_accepts_internal_hostname(self):
|
||||
"""A hostname without a public-suffix shaped last label is accepted."""
|
||||
response = self.client.patch(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={"base_url": "https://auth.svr001"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://auth.svr001")
|
||||
|
||||
def test_settings_saves_with_internal_hostname_stored(self):
|
||||
"""An unrelated setting can still be saved."""
|
||||
self.settings.base_url = "https://auth.svr001"
|
||||
self.settings.save()
|
||||
current = self.client.get(reverse("authentik_api:system_settings")).json()
|
||||
response = self.client.put(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={**current, "avatars": "initials"},
|
||||
format="json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.avatars, "initials")
|
||||
self.assertEqual(self.settings.base_url, "https://auth.svr001")
|
||||
|
||||
def test_settings_rejects_empty(self):
|
||||
"""The field cannot be cleared, a base URL is required"""
|
||||
self.settings.base_url = "https://auth.svr001"
|
||||
self.settings.save()
|
||||
response = self.client.patch(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={"base_url": ""},
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertJSONEqual(response.content, {"base_url": ["This field may not be blank."]})
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://auth.svr001")
|
||||
|
||||
def test_settings_normalizes_trailing_slash(self):
|
||||
"""A trailing slash is stripped when saving through the settings API"""
|
||||
response = self.client.patch(
|
||||
reverse("authentik_api:system_settings"),
|
||||
data={"base_url": "https://authentik.company/"},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.settings.refresh_from_db()
|
||||
self.assertEqual(self.settings.base_url, "https://authentik.company")
|
||||
|
||||
def test_system_info_exposes_base_url(self):
|
||||
"""The admin system info endpoint exposes the configured base_url"""
|
||||
self.settings.base_url = "https://info.example.com"
|
||||
self.settings.save()
|
||||
response = self.client.get(reverse("authentik_api:admin_system"))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()["base_url"], "https://info.example.com")
|
||||
@@ -1,24 +0,0 @@
|
||||
"""Tests for the normalize_base_url helper"""
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from authentik.admin.utils import normalize_base_url
|
||||
|
||||
|
||||
class TestNormalizeBaseURL(SimpleTestCase):
|
||||
"""normalize_base_url strips whitespace and trailing slashes"""
|
||||
|
||||
def test_normalize(self):
|
||||
cases = {
|
||||
None: "",
|
||||
"": "",
|
||||
" ": "",
|
||||
"https://authentik.company": "https://authentik.company",
|
||||
"https://authentik.company/": "https://authentik.company",
|
||||
"https://authentik.company///": "https://authentik.company",
|
||||
" https://authentik.company/ ": "https://authentik.company",
|
||||
"https://authentik.company/authentik/": "https://authentik.company/authentik",
|
||||
}
|
||||
for value, expected in cases.items():
|
||||
with self.subTest(value=value):
|
||||
self.assertEqual(normalize_base_url(value), expected)
|
||||
@@ -1,32 +0,0 @@
|
||||
from django.http import HttpRequest, HttpResponse
|
||||
from django.test import RequestFactory, TestCase
|
||||
|
||||
from authentik.admin.middleware import SystemSettingsMiddleware
|
||||
from authentik.admin.models import SystemSettings
|
||||
from authentik.admin.utils import get_system_settings
|
||||
|
||||
|
||||
class TestSystemSettingsCache(TestCase):
|
||||
def test_scoped_to_request(self):
|
||||
"""Settings are only cached within a single request"""
|
||||
seen = []
|
||||
|
||||
def view(request: HttpRequest) -> HttpResponse:
|
||||
seen.extend([get_system_settings(), get_system_settings()])
|
||||
return HttpResponse()
|
||||
|
||||
middleware = SystemSettingsMiddleware(view)
|
||||
middleware(RequestFactory().get("/"))
|
||||
middleware(RequestFactory().get("/"))
|
||||
self.assertIs(seen[0], seen[1])
|
||||
self.assertIsNot(seen[1], seen[2])
|
||||
self.assertIs(seen[2], seen[3])
|
||||
self.assertIsNot(get_system_settings(), get_system_settings())
|
||||
|
||||
def test_fresh_outside_requests(self):
|
||||
"""System settings cache is not used outside of a request"""
|
||||
first = get_system_settings()
|
||||
SystemSettings.objects.filter(pk=True).update(avatars="none")
|
||||
second = get_system_settings()
|
||||
self.assertIsNot(first, second)
|
||||
self.assertEqual(second.avatars, "none")
|
||||
@@ -1,12 +1,12 @@
|
||||
"""test admin tasks"""
|
||||
|
||||
from django.apps import apps
|
||||
from django.core.cache import cache
|
||||
from django.test import TestCase
|
||||
from requests_mock import Mocker
|
||||
|
||||
from authentik.admin.tasks import (
|
||||
VERSION_URL,
|
||||
UpdateVersionInfo,
|
||||
VERSION_CACHE_KEY,
|
||||
update_latest_version,
|
||||
)
|
||||
from authentik.events.models import Event, EventAction
|
||||
@@ -29,9 +29,9 @@ class TestAdminTasks(TestCase):
|
||||
def test_version_valid_response(self):
|
||||
"""Test Update checker with valid response"""
|
||||
with Mocker() as mocker, CONFIG.patch("disable_update_check", False):
|
||||
mocker.get(VERSION_URL, json=RESPONSE_VALID)
|
||||
mocker.get("https://version.goauthentik.io/version.json", json=RESPONSE_VALID)
|
||||
update_latest_version.send()
|
||||
self.assertEqual(UpdateVersionInfo.get_cached().version, "99999999.9999999")
|
||||
self.assertEqual(cache.get(VERSION_CACHE_KEY), "99999999.9999999")
|
||||
self.assertTrue(
|
||||
Event.objects.filter(
|
||||
action=EventAction.UPDATE_AVAILABLE,
|
||||
@@ -55,9 +55,9 @@ class TestAdminTasks(TestCase):
|
||||
def test_version_error(self):
|
||||
"""Test Update checker with invalid response"""
|
||||
with Mocker() as mocker:
|
||||
mocker.get(VERSION_URL, status_code=400)
|
||||
mocker.get("https://version.goauthentik.io/version.json", status_code=400)
|
||||
update_latest_version.send()
|
||||
self.assertFalse(UpdateVersionInfo.get_cached().valid)
|
||||
self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
|
||||
self.assertFalse(
|
||||
Event.objects.filter(
|
||||
action=EventAction.UPDATE_AVAILABLE, context__new_version="0.0.0"
|
||||
@@ -68,7 +68,7 @@ class TestAdminTasks(TestCase):
|
||||
"""Test Update checker while its disabled"""
|
||||
with CONFIG.patch("disable_update_check", True):
|
||||
update_latest_version.send()
|
||||
self.assertFalse(UpdateVersionInfo.get_cached().valid)
|
||||
self.assertEqual(cache.get(VERSION_CACHE_KEY), "0.0.0")
|
||||
|
||||
def test_clear_update_notifications(self):
|
||||
"""Test clear of previous notification"""
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
"""Tests for the base_url field validators"""
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from authentik.admin.models import SystemSettings
|
||||
|
||||
|
||||
class TestValidateBaseURL(SimpleTestCase):
|
||||
"""base_url accepts an http or https URL whose host needs no domain part"""
|
||||
|
||||
def test_validate(self):
|
||||
field = SystemSettings._meta.get_field("base_url")
|
||||
cases = {
|
||||
"https://authentik.company": True,
|
||||
"http://authentik.company": True,
|
||||
"HTTPS://authentik.company": True,
|
||||
"https://authentik.company/authentik": True,
|
||||
# Hostnames Django's own URLValidator rejects
|
||||
"https://auth.svr001": True,
|
||||
"https://auth": True,
|
||||
"https://auth.s1": True,
|
||||
"http://localhost:9000": True,
|
||||
"https://192.168.1.5:9443": True,
|
||||
"https://[fd00::1]:9443": True,
|
||||
# Not a URL at all.
|
||||
"authentik.company": False,
|
||||
"//authentik.company": False,
|
||||
"not a url": False,
|
||||
"https://": False,
|
||||
"http://": False,
|
||||
# Only http and https.
|
||||
"ftp://authentik.company": False,
|
||||
"javascript:alert(1)": False,
|
||||
# A host that is not a host.
|
||||
"http:///nohost": False,
|
||||
"https://.": False,
|
||||
"https://auth svr001": False,
|
||||
"https://my_host.example.com": False,
|
||||
"https://auth.svr001\nBcc: [email protected]": False,
|
||||
"https://auth.svr001\tfoo": False,
|
||||
}
|
||||
for value, valid in cases.items():
|
||||
with self.subTest(value=value):
|
||||
if valid:
|
||||
field.run_validators(value)
|
||||
continue
|
||||
with self.assertRaises(ValidationError):
|
||||
field.run_validators(value)
|
||||
@@ -3,7 +3,6 @@
|
||||
from django.urls import path
|
||||
|
||||
from authentik.admin.api.meta import AppsViewSet, ModelViewSet
|
||||
from authentik.admin.api.settings import SettingsView
|
||||
from authentik.admin.api.system import SystemView
|
||||
from authentik.admin.api.version import VersionView
|
||||
from authentik.admin.api.version_history import VersionHistoryViewSet
|
||||
@@ -11,7 +10,6 @@ from authentik.admin.api.version_history import VersionHistoryViewSet
|
||||
api_urlpatterns = [
|
||||
("admin/apps", AppsViewSet, "apps"),
|
||||
("admin/models", ModelViewSet, "models"),
|
||||
path("admin/settings/", SettingsView.as_view(), name="system_settings"),
|
||||
path("admin/version/", VersionView.as_view(), name="admin_version"),
|
||||
("admin/version/history", VersionHistoryViewSet, "version_history"),
|
||||
path("admin/system/", SystemView.as_view(), name="admin_system"),
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
"""authentik admin utils"""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
|
||||
from authentik.admin.models import SystemSettings
|
||||
|
||||
_CTX_SYSTEM_SETTINGS = ContextVar[dict[str, SystemSettings] | None](
|
||||
"authentik_system_settings", default=None
|
||||
)
|
||||
|
||||
|
||||
def get_system_settings() -> SystemSettings:
|
||||
cache = _CTX_SYSTEM_SETTINGS.get()
|
||||
if cache is None:
|
||||
return SystemSettings.objects.get(pk=True)
|
||||
if "settings" not in cache:
|
||||
cache["settings"] = SystemSettings.objects.get(pk=True)
|
||||
return cache["settings"]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def system_settings_cache() -> Iterator[None]:
|
||||
token = _CTX_SYSTEM_SETTINGS.set({})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_CTX_SYSTEM_SETTINGS.reset(token)
|
||||
|
||||
|
||||
def clear_system_settings_cache() -> None:
|
||||
if (cache := _CTX_SYSTEM_SETTINGS.get()) is not None:
|
||||
cache.clear()
|
||||
|
||||
|
||||
def normalize_base_url(value: str | None) -> str:
|
||||
"""Normalize a configured base URL: strip whitespace and trailing slashes."""
|
||||
return (value or "").strip().rstrip("/")
|
||||
@@ -16,7 +16,6 @@ from structlog.stdlib import get_logger
|
||||
from authentik.common.oauth.constants import SCOPE_AUTHENTIK_API
|
||||
from authentik.core.middleware import CTX_AUTH_VIA
|
||||
from authentik.core.models import Token, TokenIntents, User, UserTypes
|
||||
from authentik.lib.tracing import active_tracer
|
||||
from authentik.outposts.models import Outpost
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -88,7 +87,6 @@ class IPCUser(VirtualUser):
|
||||
class TokenAuthentication(BaseAuthentication):
|
||||
"""Token-based authentication using HTTP Bearer authentication"""
|
||||
|
||||
@active_tracer().instrument()
|
||||
def authenticate(self, request: Request) -> tuple[User, Any] | None:
|
||||
"""Token-based authentication using HTTP Bearer authentication"""
|
||||
auth = get_authorization_header(request)
|
||||
|
||||
@@ -6,7 +6,6 @@ from drf_spectacular.plumbing import build_object_type
|
||||
from rest_framework import pagination
|
||||
from rest_framework.response import Response
|
||||
|
||||
from authentik.admin.utils import get_system_settings
|
||||
from authentik.api.search.ql import QLSearch
|
||||
from authentik.api.v3.schema.pagination import PAGINATION
|
||||
from authentik.api.v3.schema.search import AUTOCOMPLETE_SCHEMA
|
||||
@@ -23,12 +22,11 @@ class Pagination(pagination.PageNumberPagination):
|
||||
page_size_query_param = "page_size"
|
||||
|
||||
def get_page_size(self, request: Request) -> int:
|
||||
settings = get_system_settings()
|
||||
if self.page_size_query_param in request.query_params:
|
||||
page_size = super().get_page_size(request)
|
||||
if page_size is not None:
|
||||
return min(page_size, settings.pagination_max_page_size)
|
||||
return settings.pagination_default_page_size
|
||||
return min(super().get_page_size(request), request.tenant.pagination_max_page_size)
|
||||
return request.tenant.pagination_default_page_size
|
||||
|
||||
def get_paginated_response(self, data) -> Response:
|
||||
previous_page_number = 0
|
||||
|
||||
@@ -11,8 +11,6 @@ class AKQLSchemaSerializer(DjangoQLSchemaSerializer):
|
||||
if not isinstance(field, JSONSearchField):
|
||||
continue
|
||||
serialization["models"].update(field.get_nested_options(self))
|
||||
# Ensure the related model exists, even with no suggested keys
|
||||
serialization["models"].setdefault(field.relation(), {})
|
||||
return serialization
|
||||
|
||||
def serialize_field(self, field):
|
||||
|
||||
@@ -96,14 +96,3 @@ class QLTest(APITestCase):
|
||||
content = loads(res.content)
|
||||
self.assertEqual(content["pagination"]["count"], 1)
|
||||
self.assertEqual(content["results"][0]["username"], self.user.username)
|
||||
|
||||
def test_autocomplete_json_relation(self):
|
||||
"""Test that the autocomplete schema includes the model a JSON field relates to,
|
||||
even when no nested keys are suggested"""
|
||||
self.client.force_login(self.user)
|
||||
res = self.client.get(reverse("authentik_api:user-list"))
|
||||
self.assertEqual(res.status_code, 200)
|
||||
autocomplete = loads(res.content)["autocomplete"]
|
||||
attributes = autocomplete["models"]["authentik_core.user"]["attributes"]
|
||||
self.assertEqual(attributes["type"], "relation")
|
||||
self.assertIn(attributes["relation"], autocomplete["models"])
|
||||
@@ -10,6 +10,9 @@ from authentik.admin.api.version_history import VersionHistoryViewSet
|
||||
from authentik.api.v3.urls import router
|
||||
from authentik.core.tests.utils import RequestFactory, create_test_admin_user
|
||||
from authentik.lib.generators import generate_id
|
||||
from authentik.tenants.api.domains import DomainViewSet
|
||||
from authentik.tenants.api.tenants import TenantViewSet
|
||||
from authentik.tenants.utils import get_current_tenant
|
||||
|
||||
|
||||
class TestModelViewSets(TestCase):
|
||||
@@ -39,6 +42,7 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
|
||||
req = self.factory.get(
|
||||
f"/?{urlencode({'ordering': ordering_field}, doseq=True)}", user=self.user
|
||||
)
|
||||
req.tenant = get_current_tenant()
|
||||
res = view(req)
|
||||
self.assertEqual(res.status_code, 200)
|
||||
|
||||
@@ -48,6 +52,7 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
|
||||
req = self.factory.get(
|
||||
f"/?{urlencode({'search': generate_id()}, doseq=True)}", user=self.user
|
||||
)
|
||||
req.tenant = get_current_tenant()
|
||||
res = view(req)
|
||||
self.assertEqual(res.status_code, 200)
|
||||
|
||||
@@ -63,6 +68,6 @@ def viewset_tester_factory(test_viewset: type[ModelViewSet], full=True) -> dict[
|
||||
for _, viewset, _ in router.registry:
|
||||
if not issubclass(viewset, ModelViewSet | ReadOnlyModelViewSet):
|
||||
continue
|
||||
full = viewset not in [VersionHistoryViewSet]
|
||||
full = viewset not in [VersionHistoryViewSet, DomainViewSet, TenantViewSet]
|
||||
for test, case in viewset_tester_factory(viewset, full=full).items():
|
||||
setattr(TestModelViewSets, f"test_viewset_{viewset.__name__}_{test}", case)
|
||||
@@ -13,7 +13,7 @@ class LocalAnonRateThrottle(AnonRateThrottle):
|
||||
protective layer amplifies DB load under flood.
|
||||
|
||||
Points the throttle's cache at the ``throttle`` LocMemCache alias instead.
|
||||
Counters are per-process (per server worker)
|
||||
Counters are per-process (per gunicorn worker)
|
||||
"""
|
||||
|
||||
cache = caches["throttle"]
|
||||
@@ -20,7 +20,6 @@ from rest_framework.views import APIView
|
||||
|
||||
from authentik.admin.files.manager import get_file_manager
|
||||
from authentik.admin.files.usage import FileUsage
|
||||
from authentik.admin.utils import get_system_settings
|
||||
from authentik.core.api.utils import PassiveSerializer
|
||||
from authentik.events.context_processors.base import get_context_processors
|
||||
from authentik.lib.config import CONFIG
|
||||
@@ -38,8 +37,6 @@ class Capabilities(models.TextChoices):
|
||||
CAN_IMPERSONATE = "can_impersonate"
|
||||
CAN_DEBUG = "can_debug"
|
||||
IS_ENTERPRISE = "is_enterprise"
|
||||
CAN_REQUEST = "can_request"
|
||||
CAN_AGENT_SELF_SERVICE = "can_agent_self_service"
|
||||
|
||||
|
||||
class ErrorReportingConfigSerializer(PassiveSerializer):
|
||||
@@ -79,13 +76,13 @@ class ConfigView(APIView):
|
||||
for processor in get_context_processors():
|
||||
if cap := processor.capability():
|
||||
caps.append(cap)
|
||||
if get_system_settings().impersonation:
|
||||
if request.tenant.impersonation:
|
||||
caps.append(Capabilities.CAN_IMPERSONATE)
|
||||
if settings.DEBUG: # pragma: no cover
|
||||
caps.append(Capabilities.CAN_DEBUG)
|
||||
if "authentik.enterprise" in settings.INSTALLED_APPS:
|
||||
caps.append(Capabilities.IS_ENTERPRISE)
|
||||
for _, result in capabilities.send(sender=ConfigView, request=request):
|
||||
for _, result in capabilities.send(sender=ConfigView):
|
||||
if result:
|
||||
caps.append(result)
|
||||
return caps
|
||||
|
||||
+20
-55
@@ -23,7 +23,7 @@ from rest_framework.viewsets import ModelViewSet
|
||||
|
||||
from authentik.api.validation import validate
|
||||
from authentik.blueprints.models import BlueprintInstance
|
||||
from authentik.blueprints.v1.common import Blueprint, EntryInvalidError
|
||||
from authentik.blueprints.v1.common import Blueprint
|
||||
from authentik.blueprints.v1.importer import Importer
|
||||
from authentik.blueprints.v1.oci import OCI_PREFIX
|
||||
from authentik.blueprints.v1.tasks import apply_blueprint, blueprints_find_dict
|
||||
@@ -154,8 +154,12 @@ def check_blueprint_perms(blueprint: Blueprint, user: User, explicit_action: str
|
||||
if not user.has_perm(perm):
|
||||
raise PermissionDenied(
|
||||
{
|
||||
entry.id: _("User lacks permission to create {model}").format(
|
||||
model=full_model
|
||||
entry.id: _(
|
||||
"User lacks permission to create {model}".format_map(
|
||||
{
|
||||
"model": full_model,
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
@@ -175,7 +179,6 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
|
||||
|
||||
logs = LogEventSerializer(many=True, read_only=True)
|
||||
success = BooleanField(read_only=True)
|
||||
imported = BooleanField(read_only=True)
|
||||
|
||||
@extend_schema(
|
||||
responses={
|
||||
@@ -212,7 +215,16 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
|
||||
apply_blueprint.send_with_options(args=(blueprint.pk,), rel_obj=blueprint)
|
||||
return self.retrieve(request, *args, **kwargs)
|
||||
|
||||
def _blueprint_from_upload(self, body: BlueprintUploadSerializer) -> Importer:
|
||||
@extend_schema(
|
||||
request={"multipart/form-data": BlueprintUploadSerializer},
|
||||
responses={200: BlueprintImportResultSerializer},
|
||||
)
|
||||
@action(url_path="import", detail=False, methods=["POST"], parser_classes=(MultiPartParser,))
|
||||
@validate(
|
||||
BlueprintUploadSerializer,
|
||||
)
|
||||
def import_(self, request: Request, body: BlueprintUploadSerializer) -> Response:
|
||||
"""Import blueprint from .yaml file and apply it once, without creating an instance"""
|
||||
string_contents = ""
|
||||
if body.validated_data.get("file"):
|
||||
file = cast(InMemoryUploadedFile, body.validated_data["file"])
|
||||
@@ -224,68 +236,21 @@ class BlueprintInstanceViewSet(UsedByMixin, ModelViewSet):
|
||||
else:
|
||||
raise ValidationError("Either path or file must be set")
|
||||
context = body.validated_data.get("context") or {}
|
||||
try:
|
||||
importer = Importer.from_string(string_contents, context)
|
||||
except EntryInvalidError as exc:
|
||||
raise ValidationError(_("Invalid blueprint file: {exc}".format(exc=str(exc)))) from None
|
||||
importer = Importer.from_string(string_contents, context)
|
||||
|
||||
check_blueprint_perms(importer.blueprint, self.request.user)
|
||||
return importer
|
||||
check_blueprint_perms(importer.blueprint, request.user)
|
||||
|
||||
@extend_schema(
|
||||
request={"multipart/form-data": BlueprintUploadSerializer},
|
||||
responses={200: BlueprintImportResultSerializer},
|
||||
)
|
||||
@action(
|
||||
url_path="validate",
|
||||
url_name="validate",
|
||||
detail=False,
|
||||
methods=["POST"],
|
||||
parser_classes=(MultiPartParser,),
|
||||
)
|
||||
@validate(BlueprintUploadSerializer)
|
||||
def validate_(self, request: Request, body: BlueprintUploadSerializer) -> Response:
|
||||
"""Validate blueprint from .yaml file and return any errors"""
|
||||
importer = self._blueprint_from_upload(body)
|
||||
valid, logs = importer.validate()
|
||||
|
||||
import_response = self.BlueprintImportResultSerializer(
|
||||
data={
|
||||
"logs": [LogEventSerializer(log).data for log in logs],
|
||||
"success": valid,
|
||||
"imported": False,
|
||||
}
|
||||
)
|
||||
import_response.is_valid(raise_exception=True)
|
||||
return Response(data=import_response.initial_data, status=200)
|
||||
|
||||
@extend_schema(
|
||||
request={"multipart/form-data": BlueprintUploadSerializer},
|
||||
responses={200: BlueprintImportResultSerializer},
|
||||
)
|
||||
@action(
|
||||
url_path="import",
|
||||
url_name="import",
|
||||
detail=False,
|
||||
methods=["POST"],
|
||||
parser_classes=(MultiPartParser,),
|
||||
)
|
||||
@validate(BlueprintUploadSerializer)
|
||||
def import_(self, request: Request, body: BlueprintUploadSerializer) -> Response:
|
||||
"""Import blueprint from .yaml file and apply it once, without creating an instance"""
|
||||
importer = self._blueprint_from_upload(body)
|
||||
valid, logs = importer.validate()
|
||||
|
||||
import_response = self.BlueprintImportResultSerializer(
|
||||
data={
|
||||
"logs": [LogEventSerializer(log).data for log in logs],
|
||||
"success": valid,
|
||||
"imported": False,
|
||||
}
|
||||
)
|
||||
import_response.is_valid(raise_exception=True)
|
||||
|
||||
if valid:
|
||||
import_response.initial_data["imported"] = importer.apply()
|
||||
import_response.initial_data["success"] = importer.apply()
|
||||
import_response.is_valid()
|
||||
return Response(data=import_response.initial_data, status=200)
|
||||
@@ -20,6 +20,9 @@ class ManagedAppConfig(AppConfig):
|
||||
|
||||
logger: BoundLogger
|
||||
|
||||
RECONCILE_GLOBAL_CATEGORY: str = "global"
|
||||
RECONCILE_TENANT_CATEGORY: str = "tenant"
|
||||
|
||||
def __init__(self, app_name: str, *args, **kwargs) -> None:
|
||||
super().__init__(app_name, *args, **kwargs)
|
||||
self.logger = get_logger().bind(app_name=app_name)
|
||||
@@ -30,7 +33,8 @@ class ManagedAppConfig(AppConfig):
|
||||
return super().ready()
|
||||
|
||||
def _on_startup_callback(self, sender, **_):
|
||||
self._reconcile()
|
||||
self._reconcile_global()
|
||||
self._reconcile_tenant()
|
||||
|
||||
def import_related(self):
|
||||
"""Automatically import related modules which rely on just being imported
|
||||
@@ -65,20 +69,22 @@ class ManagedAppConfig(AppConfig):
|
||||
"""Load module"""
|
||||
import_module(path)
|
||||
|
||||
def _reconcile(self) -> None:
|
||||
for name in dir(self):
|
||||
def _reconcile(self, prefix: str) -> None:
|
||||
for meth_name in dir(self):
|
||||
# Check the attribute on the class to avoid evaluating @property descriptors.
|
||||
# Using getattr(self, ...) on a @property would evaluate it, which can trigger
|
||||
# expensive side effects (e.g. schedule_specs iterating all providers
|
||||
# expensive side effects (e.g. tenant_schedule_specs iterating all providers
|
||||
# and running PolicyEngine queries for every user).
|
||||
class_attr = getattr(type(self), name, None)
|
||||
class_attr = getattr(type(self), meth_name, None)
|
||||
if class_attr is None or isinstance(class_attr, property):
|
||||
continue
|
||||
if not callable(class_attr):
|
||||
continue
|
||||
if not getattr(class_attr, "_authentik_managed_reconcile", False):
|
||||
category = getattr(class_attr, "_authentik_managed_reconcile", None)
|
||||
if category != prefix:
|
||||
continue
|
||||
meth = getattr(self, name)
|
||||
meth = getattr(self, meth_name)
|
||||
name = meth_name.replace(prefix, "")
|
||||
try:
|
||||
self.logger.debug("Starting reconciler", name=name)
|
||||
meth()
|
||||
@@ -87,16 +93,54 @@ class ManagedAppConfig(AppConfig):
|
||||
self.logger.warning("Failed to run reconcile", name=name, exc=exc)
|
||||
|
||||
@staticmethod
|
||||
def reconcile(func: Callable):
|
||||
"""Mark a function to be called on startup"""
|
||||
func._authentik_managed_reconcile = True
|
||||
def reconcile_tenant(func: Callable):
|
||||
"""Mark a function to be called on startup (for each tenant)"""
|
||||
func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_TENANT_CATEGORY
|
||||
return func
|
||||
|
||||
@staticmethod
|
||||
def reconcile_global(func: Callable):
|
||||
"""Mark a function to be called on startup (globally)"""
|
||||
func._authentik_managed_reconcile = ManagedAppConfig.RECONCILE_GLOBAL_CATEGORY
|
||||
return func
|
||||
|
||||
@property
|
||||
def schedule_specs(self) -> list[ScheduleSpec]:
|
||||
"""Get a list of schedule specs that must exist"""
|
||||
def tenant_schedule_specs(self) -> list[ScheduleSpec]:
|
||||
"""Get a list of schedule specs that must exist in each tenant"""
|
||||
return []
|
||||
|
||||
@property
|
||||
def global_schedule_specs(self) -> list[ScheduleSpec]:
|
||||
"""Get a list of schedule specs that must exist in the default tenant"""
|
||||
return []
|
||||
|
||||
def _reconcile_tenant(self) -> None:
|
||||
"""reconcile ourselves for tenanted methods"""
|
||||
from authentik.tenants.models import Tenant
|
||||
|
||||
try:
|
||||
tenants = list(Tenant.objects.filter(ready=True))
|
||||
except (DatabaseError, ProgrammingError, InternalError) as exc:
|
||||
self.logger.debug("Failed to get tenants to run reconcile", exc=exc)
|
||||
return
|
||||
for tenant in tenants:
|
||||
with tenant:
|
||||
self._reconcile(self.RECONCILE_TENANT_CATEGORY)
|
||||
|
||||
def _reconcile_global(self) -> None:
|
||||
"""
|
||||
reconcile ourselves for global methods.
|
||||
Used for signals, tasks, etc. Database queries should not be made in here.
|
||||
"""
|
||||
from django_tenants.utils import get_public_schema_name, schema_context
|
||||
|
||||
try:
|
||||
with schema_context(get_public_schema_name()):
|
||||
self._reconcile(self.RECONCILE_GLOBAL_CATEGORY)
|
||||
except (DatabaseError, ProgrammingError, InternalError) as exc:
|
||||
self.logger.debug("Failed to access database to run reconcile", exc=exc)
|
||||
return
|
||||
|
||||
|
||||
class AuthentikBlueprintsConfig(ManagedAppConfig):
|
||||
"""authentik Blueprints app"""
|
||||
@@ -110,14 +154,14 @@ class AuthentikBlueprintsConfig(ManagedAppConfig):
|
||||
super().import_models()
|
||||
self.import_module("authentik.blueprints.v1.meta.apply_blueprint")
|
||||
|
||||
@ManagedAppConfig.reconcile
|
||||
@ManagedAppConfig.reconcile_global
|
||||
def tasks_middlewares(self):
|
||||
from authentik.blueprints.v1.tasks import BlueprintWatcherMiddleware
|
||||
|
||||
get_broker().add_middleware(BlueprintWatcherMiddleware())
|
||||
|
||||
@property
|
||||
def schedule_specs(self) -> list[ScheduleSpec]:
|
||||
def tenant_schedule_specs(self) -> list[ScheduleSpec]:
|
||||
from authentik.blueprints.v1.tasks import blueprints_discovery, clear_failed_blueprints
|
||||
|
||||
return [
|
||||
|
||||
@@ -8,6 +8,7 @@ from structlog.stdlib import get_logger
|
||||
|
||||
from authentik.blueprints.models import BlueprintInstance
|
||||
from authentik.blueprints.v1.importer import Importer
|
||||
from authentik.tenants.models import Tenant
|
||||
|
||||
LOGGER = get_logger()
|
||||
|
||||
@@ -16,22 +17,20 @@ class Command(BaseCommand):
|
||||
"""Apply blueprint from commandline"""
|
||||
|
||||
@no_translations
|
||||
def handle(self, *args, blueprints: list[str], dry_run: bool, **options):
|
||||
def handle(self, *args, **options):
|
||||
"""Apply all blueprints in order, abort when one fails to import"""
|
||||
for blueprint_path in blueprints:
|
||||
content = BlueprintInstance(path=blueprint_path).retrieve()
|
||||
importer = Importer.from_string(content)
|
||||
valid, logs = importer.validate()
|
||||
if not valid:
|
||||
self.stderr.write("Blueprint invalid")
|
||||
for log in logs:
|
||||
self.stderr.write(f"\t{log.logger}: {log.event}: {log.attributes}")
|
||||
sys_exit(1)
|
||||
if not dry_run:
|
||||
importer.apply()
|
||||
else:
|
||||
LOGGER.info("Dry-run enabled, not applying blueprint")
|
||||
for tenant in Tenant.objects.filter(ready=True):
|
||||
with tenant:
|
||||
for blueprint_path in options.get("blueprints", []):
|
||||
content = BlueprintInstance(path=blueprint_path).retrieve()
|
||||
importer = Importer.from_string(content)
|
||||
valid, logs = importer.validate()
|
||||
if not valid:
|
||||
self.stderr.write("Blueprint invalid")
|
||||
for log in logs:
|
||||
self.stderr.write(f"\t{log.logger}: {log.event}: {log.attributes}")
|
||||
sys_exit(1)
|
||||
importer.apply()
|
||||
|
||||
def add_arguments(self, parser: ArgumentParser):
|
||||
parser.add_argument("--dry-run", action="store_true", default=False)
|
||||
parser.add_argument("blueprints", nargs="+", type=str)
|
||||
@@ -1,18 +1,19 @@
|
||||
"""Export blueprint of current authentik install"""
|
||||
|
||||
from django.core.management.base import BaseCommand, no_translations
|
||||
from django.core.management.base import no_translations
|
||||
from structlog.stdlib import get_logger
|
||||
|
||||
from authentik.blueprints.v1.exporter import Exporter
|
||||
from authentik.tenants.management import TenantCommand
|
||||
|
||||
LOGGER = get_logger()
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
class Command(TenantCommand):
|
||||
"""Export blueprint of current authentik install"""
|
||||
|
||||
@no_translations
|
||||
def handle(self, *args, **options):
|
||||
def handle_per_tenant(self, *args, **options):
|
||||
"""Export blueprint of current authentik install"""
|
||||
exporter = Exporter()
|
||||
self.stdout.write(exporter.export_to_string())
|
||||
@@ -73,11 +73,6 @@ class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [("authentik_flows", "0001_initial")]
|
||||
|
||||
# migration_blueprint_import below treats "a flow already exists" as "this is an existing
|
||||
# install". That only holds if we run before any migration that creates a flow, which is
|
||||
# otherwise up to how Django happens to order the plan.
|
||||
run_before = [("authentik_core", "0040_provider_invalidation_flow")]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="BlueprintInstance",
|
||||
|
||||
@@ -13,12 +13,12 @@ from structlog import get_logger
|
||||
from authentik.blueprints.v1.oci import OCI_PREFIX, BlueprintOCIClient, OCIException
|
||||
from authentik.lib.config import CONFIG
|
||||
from authentik.lib.models import CreatedUpdatedModel, SerializerModel
|
||||
from authentik.lib.tracing.exceptions import TracingIgnoredException
|
||||
from authentik.lib.sentry import SentryIgnoredException
|
||||
|
||||
LOGGER = get_logger()
|
||||
|
||||
|
||||
class BlueprintRetrievalFailed(TracingIgnoredException):
|
||||
class BlueprintRetrievalFailed(SentryIgnoredException):
|
||||
"""Error raised when we are unable to fetch the blueprint contents, whether it be HTTP files
|
||||
not being accessible or local files not being readable"""
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
version: 1
|
||||
context:
|
||||
foo.bar.baz: not-nested
|
||||
foo:
|
||||
bar:
|
||||
baz:
|
||||
qux: nested
|
||||
bar:
|
||||
- baz:
|
||||
- list-element
|
||||
baz.0.name: has-priority
|
||||
baz:
|
||||
- name: does-not-have-priority
|
||||
qux:
|
||||
- quux: !Context nested_ref_value
|
||||
nested_ref_value: ref-value
|
||||
entries:
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context foo.bar.baz
|
||||
attrs:
|
||||
is_superuser: false
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context foo.bar.baz.qux
|
||||
attrs:
|
||||
is_superuser: false
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context bar.0.baz.0
|
||||
attrs:
|
||||
is_superuser: false
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context baz.0.name
|
||||
attrs:
|
||||
is_superuser: false
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context qux.0.quux
|
||||
attrs:
|
||||
is_superuser: false
|
||||
- model: authentik_core.group
|
||||
identifiers:
|
||||
name: !Context [foo.bar.non.existing, default-value]
|
||||
attrs:
|
||||
is_superuser: false
|
||||
@@ -21,7 +21,6 @@ entries:
|
||||
provider_type: github
|
||||
consumer_key: !Env foo
|
||||
consumer_secret: !Env [bar, baz]
|
||||
consumer_secret2: !Env [non-existing, !Context foo]
|
||||
authentication_flow:
|
||||
!Find [
|
||||
authentik_flows.Flow,
|
||||
@@ -56,10 +55,6 @@ entries:
|
||||
suffix,
|
||||
]
|
||||
policy_pk2: !Format ["%%s-%%s", !KeyOf policy, suffix]
|
||||
boolEq:
|
||||
!Condition [EQ, "2", "2"]
|
||||
boolNeq:
|
||||
!Condition [NEQ, 2, "2"]
|
||||
boolAnd:
|
||||
!Condition [AND, !Context foo, !Format ["%%s", "a_string"], 1]
|
||||
boolNand:
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
"""Test blueprint JSON Schema generation"""
|
||||
|
||||
from json import dumps, loads
|
||||
|
||||
from django.test import TestCase
|
||||
from jsonschema import Draft7Validator
|
||||
from jsonschema.exceptions import SchemaError
|
||||
|
||||
from authentik.blueprints.v1.schema import SchemaBuilder
|
||||
|
||||
|
||||
class TestSchema(TestCase):
|
||||
"""Test blueprint schema generation"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.builder = SchemaBuilder()
|
||||
self.builder.build()
|
||||
# Validate the artifact consumers actually get. `build_schema` dumps with
|
||||
# `json_default` to resolve gettext_lazy proxies into strings, so the
|
||||
# in-memory dict still holds lazy objects that no JSON Schema validator
|
||||
# would accept. Round-tripping here matches the published schema.json.
|
||||
self.schema = loads(dumps(self.builder.schema, default=SchemaBuilder.json_default))
|
||||
|
||||
def test_schema_declares_a_dialect(self):
|
||||
"""The generated schema must say which dialect it is written in"""
|
||||
self.assertIn("$schema", self.schema)
|
||||
|
||||
def test_schema_is_valid_against_its_declared_dialect(self):
|
||||
"""Regression for #24248.
|
||||
|
||||
The schema declared draft-07 but used `$defs`, which is 2020-12
|
||||
vocabulary — draft-07 spells it `definitions`. A validator honouring the
|
||||
declared dialect therefore could not resolve `#/$defs/...` references,
|
||||
so nothing that consumed the published schema.json could validate a
|
||||
blueprint.
|
||||
"""
|
||||
self.assertEqual(self.schema["$schema"], "http://json-schema.org/draft-07/schema")
|
||||
try:
|
||||
Draft7Validator.check_schema(self.schema)
|
||||
except SchemaError as exc: # pragma: no cover - failure path
|
||||
self.fail(f"generated schema is not valid draft-07: {exc}")
|
||||
|
||||
def test_schema_uses_draft_07_definitions_keyword(self):
|
||||
"""`$defs` is 2020-12; under the declared draft-07 dialect it is inert.
|
||||
|
||||
Keeping it would leave every definition unreachable while looking
|
||||
correct in the emitted file.
|
||||
"""
|
||||
self.assertIn("definitions", self.schema)
|
||||
self.assertNotIn("$defs", self.schema)
|
||||
|
||||
def test_every_ref_resolves(self):
|
||||
"""A `$ref` pointing at a keyword the dialect does not define is dead.
|
||||
|
||||
This is what the issue actually reported: refs into `#/$defs/...` that
|
||||
no draft-07 validator could follow.
|
||||
"""
|
||||
refs = self._collect_refs(self.schema)
|
||||
self.assertGreater(len(refs), 0, "expected the schema to contain $refs")
|
||||
for ref in refs:
|
||||
self.assertTrue(
|
||||
ref.startswith("#/definitions/"),
|
||||
f"$ref {ref!r} does not point into #/definitions/",
|
||||
)
|
||||
pointer = ref.removeprefix("#/definitions/")
|
||||
self.assertIn(
|
||||
pointer,
|
||||
self.schema["definitions"],
|
||||
f"$ref {ref!r} does not resolve to a definition",
|
||||
)
|
||||
|
||||
def test_blueprint_entry_definition_is_populated(self):
|
||||
"""The entry oneOf is what blueprints are actually validated against."""
|
||||
self.assertGreater(len(self.schema["definitions"]["blueprint_entry"]["oneOf"]), 0)
|
||||
|
||||
def _collect_refs(self, node) -> list[str]:
|
||||
"""Every `$ref` value anywhere in the schema."""
|
||||
found = []
|
||||
if isinstance(node, dict):
|
||||
for key, value in node.items():
|
||||
if key == "$ref" and isinstance(value, str):
|
||||
found.append(value)
|
||||
else:
|
||||
found.extend(self._collect_refs(value))
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
found.extend(self._collect_refs(item))
|
||||
return found
|
||||
@@ -1,19 +1,14 @@
|
||||
"""Test blueprints v1"""
|
||||
|
||||
from os import chmod, environ, unlink, write
|
||||
from pathlib import Path
|
||||
from tempfile import mkstemp
|
||||
from uuid import UUID
|
||||
|
||||
from django.db.models.signals import post_save
|
||||
from django.test import TransactionTestCase
|
||||
from django.utils.text import slugify
|
||||
from yaml import load
|
||||
|
||||
from authentik.blueprints.models import BlueprintInstance
|
||||
from authentik.blueprints.tests import apply_blueprint
|
||||
from authentik.blueprints.v1.common import BlueprintLoader, KeyOf
|
||||
from authentik.blueprints.v1.exporter import Exporter, FlowExporter
|
||||
from authentik.blueprints.v1.common import BlueprintLoader
|
||||
from authentik.blueprints.v1.exporter import FlowExporter
|
||||
from authentik.blueprints.v1.importer import Importer, transaction_rollback
|
||||
from authentik.core.models import Group
|
||||
from authentik.flows.models import Flow, FlowDesignation, FlowStageBinding
|
||||
@@ -166,19 +161,6 @@ class TestBlueprintsV1(TransactionTestCase):
|
||||
|
||||
self.assertEqual(Prompt.objects.filter(field_key="username").count(), count_before)
|
||||
|
||||
def test_nested_context_keys(self):
|
||||
"""Test nested context keys resolution"""
|
||||
importer = Importer.from_string(load_fixture("fixtures/nested_contexts.yaml"))
|
||||
self.assertTrue(importer.validate()[0])
|
||||
self.assertTrue(importer.apply())
|
||||
|
||||
self.assertTrue(Group.objects.filter(name="not-nested").exists())
|
||||
self.assertTrue(Group.objects.filter(name="nested").exists())
|
||||
self.assertTrue(Group.objects.filter(name="list-element").exists())
|
||||
self.assertTrue(Group.objects.filter(name="has-priority").exists())
|
||||
self.assertTrue(Group.objects.filter(name="ref-value").exists())
|
||||
self.assertTrue(Group.objects.filter(name="default-value").exists())
|
||||
|
||||
@apply_blueprint("system/providers-oauth2.yaml")
|
||||
def test_import_yaml_tags(self):
|
||||
"""Test some yaml tags"""
|
||||
@@ -208,8 +190,6 @@ class TestBlueprintsV1(TransactionTestCase):
|
||||
{
|
||||
"policy_pk1": str(policy.pk) + "-suffix",
|
||||
"policy_pk2": str(policy.pk) + "-suffix",
|
||||
"boolEq": True,
|
||||
"boolNeq": False,
|
||||
"boolAnd": True,
|
||||
"boolNand": False,
|
||||
"boolOr": True,
|
||||
@@ -328,113 +308,12 @@ class TestBlueprintsV1(TransactionTestCase):
|
||||
exporter = FlowExporter(flow)
|
||||
export_yaml = exporter.export_to_string()
|
||||
|
||||
binding_pks = []
|
||||
|
||||
def capture_binding_pk(sender, instance, **kwargs):
|
||||
binding_pks.append(instance.policy_binding_uuid)
|
||||
|
||||
# Inspect the signal instance: reloading from the database would hide a string UUID.
|
||||
post_save.connect(capture_binding_pk, sender=PolicyBinding)
|
||||
try:
|
||||
importer = Importer.from_string(export_yaml)
|
||||
self.assertTrue(importer.validate()[0])
|
||||
self.assertTrue(importer.apply())
|
||||
finally:
|
||||
post_save.disconnect(capture_binding_pk, sender=PolicyBinding)
|
||||
|
||||
self.assertTrue(binding_pks)
|
||||
for binding_pk in binding_pks:
|
||||
self.assertIsInstance(binding_pk, UUID)
|
||||
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
|
||||
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
||||
|
||||
def test_export_uses_keyof_references(self):
|
||||
"""Test that exporting a flow rewrites references between exported objects
|
||||
as !KeyOf tags instead of raw primary keys"""
|
||||
flow_slug = generate_id()
|
||||
stage_name = generate_id()
|
||||
policy_name = generate_id()
|
||||
with transaction_rollback():
|
||||
flow_policy = ExpressionPolicy.objects.create(
|
||||
name=policy_name,
|
||||
expression="return True",
|
||||
)
|
||||
flow = Flow.objects.create(
|
||||
slug=flow_slug,
|
||||
designation=FlowDesignation.AUTHENTICATION,
|
||||
name=generate_id(),
|
||||
title=generate_id(),
|
||||
)
|
||||
PolicyBinding.objects.create(policy=flow_policy, target=flow, order=0)
|
||||
|
||||
user_login = UserLoginStage.objects.create(name=stage_name)
|
||||
fsb = FlowStageBinding.objects.create(target=flow, stage=user_login, order=0)
|
||||
PolicyBinding.objects.create(policy=flow_policy, target=fsb, order=0)
|
||||
|
||||
exporter = FlowExporter(flow)
|
||||
export = exporter.export()
|
||||
export_yaml = exporter.export_to_string()
|
||||
|
||||
entries_by_model = {}
|
||||
for entry in export.entries:
|
||||
entries_by_model.setdefault(entry.model, []).append(entry)
|
||||
|
||||
flow_entry = entries_by_model["authentik_flows.flow"][0]
|
||||
stage_entry = entries_by_model["authentik_stages_user_login.userloginstage"][0]
|
||||
stage_binding_entry = entries_by_model["authentik_flows.flowstagebinding"][0]
|
||||
policy_entry = entries_by_model["authentik_policies_expression.expressionpolicy"][0]
|
||||
policy_binding_entries = entries_by_model["authentik_policies.policybinding"]
|
||||
|
||||
self.assertIsNotNone(flow_entry.id)
|
||||
self.assertIsNotNone(stage_entry.id)
|
||||
# ids are derived from a readable, unique, non-UUID field (slug/name) when available,
|
||||
# rather than an opaque counter
|
||||
self.assertEqual(flow_entry.id, f"flow-{slugify(flow_slug)}")
|
||||
self.assertEqual(stage_entry.id, f"userloginstage-{slugify(stage_name)}")
|
||||
|
||||
# Policy is exported without any explicit extra identifiers, but its unique,
|
||||
# non-UUID `name` field is still picked up automatically as a stable identifier
|
||||
self.assertEqual(policy_entry.identifiers.get("name"), policy_name)
|
||||
# The primary key is instance-local and not portable, so it must not be used as
|
||||
# an identifier whenever a stable identifier could be found instead
|
||||
for entry in (flow_entry, stage_entry, policy_entry):
|
||||
self.assertNotIn("pk", entry.identifiers)
|
||||
|
||||
self.assertIsInstance(stage_binding_entry.identifiers["target"], KeyOf)
|
||||
self.assertEqual(stage_binding_entry.identifiers["target"].id_from, flow_entry.id)
|
||||
self.assertIsInstance(stage_binding_entry.identifiers["stage"], KeyOf)
|
||||
self.assertEqual(stage_binding_entry.identifiers["stage"].id_from, stage_entry.id)
|
||||
|
||||
binding_targets = {pb.identifiers["target"].id_from for pb in policy_binding_entries}
|
||||
self.assertIn(flow_entry.id, binding_targets)
|
||||
self.assertIn(stage_binding_entry.id, binding_targets)
|
||||
for policy_binding_entry in policy_binding_entries:
|
||||
self.assertIsInstance(policy_binding_entry.identifiers["policy"], KeyOf)
|
||||
self.assertEqual(policy_binding_entry.identifiers["policy"].id_from, policy_entry.id)
|
||||
|
||||
self.assertIn("!KeyOf", export_yaml)
|
||||
|
||||
importer = Importer.from_string(export_yaml)
|
||||
self.assertTrue(importer.validate()[0])
|
||||
self.assertTrue(importer.apply())
|
||||
self.assertTrue(UserLoginStage.objects.filter(name=stage_name).exists())
|
||||
self.assertTrue(Flow.objects.filter(slug=flow_slug).exists())
|
||||
|
||||
def test_export_default_blueprints_no_static_identifiers(self):
|
||||
"""Test that exporting a full instance after applying all default blueprints
|
||||
never falls back to an opaque, non-portable `pk` identifier, e.g. for models
|
||||
such as FlowStageBinding that have no unique text field of their own"""
|
||||
for blueprint_file in sorted(Path("blueprints/default").glob("*.yaml")):
|
||||
rel_path = str(blueprint_file.relative_to("blueprints"))
|
||||
importer = Importer.from_string(BlueprintInstance(path=rel_path).retrieve())
|
||||
self.assertTrue(importer.validate()[0])
|
||||
self.assertTrue(importer.apply())
|
||||
|
||||
export = Exporter().export()
|
||||
for entry in export.entries:
|
||||
self.assertNotIn(
|
||||
"pk", entry.identifiers, f"{entry.model} entry has a static pk identifier"
|
||||
)
|
||||
|
||||
def test_export_validate_import_prompt(self):
|
||||
"""Test export and validate it"""
|
||||
with transaction_rollback():
|
||||
|
||||
@@ -12,7 +12,6 @@ from authentik.core.tests.utils import create_test_admin_user
|
||||
from authentik.flows.models import Flow
|
||||
from authentik.lib.config import CONFIG
|
||||
from authentik.lib.generators import generate_id
|
||||
from authentik.providers.oauth2.models import ScopeMapping
|
||||
from authentik.stages.invitation.models import InvitationStage
|
||||
from authentik.stages.user_write.models import UserWriteStage
|
||||
|
||||
@@ -96,7 +95,7 @@ class TestBlueprintsV1API(APITestCase):
|
||||
continue_without_invitation = True
|
||||
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={
|
||||
"path": "example/flows-invitation-enrollment-minimal.yaml",
|
||||
"context": dumps(
|
||||
@@ -113,7 +112,6 @@ class TestBlueprintsV1API(APITestCase):
|
||||
)
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertTrue(res.json()["success"])
|
||||
self.assertTrue(res.json()["imported"])
|
||||
|
||||
flow = Flow.objects.get(slug=slug)
|
||||
self.assertEqual(flow.name, flow_name)
|
||||
@@ -138,7 +136,7 @@ class TestBlueprintsV1API(APITestCase):
|
||||
file.flush()
|
||||
file.seek(0)
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={"path": "", "file": file},
|
||||
format="multipart",
|
||||
)
|
||||
@@ -149,14 +147,13 @@ class TestBlueprintsV1API(APITestCase):
|
||||
file = SimpleUploadedFile("invalid-blueprint.yaml", b'{"version": 3}')
|
||||
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={"file": file},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertFalse(res.json()["success"])
|
||||
self.assertFalse(res.json()["imported"])
|
||||
self.assertGreater(len(res.json()["logs"]), 0)
|
||||
|
||||
def test_api_import_invalid_blueprint_with_yaml_tag_returns_result_payload(self):
|
||||
@@ -184,20 +181,19 @@ class TestBlueprintsV1API(APITestCase):
|
||||
file = SimpleUploadedFile("invalid-blueprint-tag.yaml", content.encode())
|
||||
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={"file": file},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertFalse(res.json()["success"])
|
||||
self.assertFalse(res.json()["imported"])
|
||||
self.assertGreater(len(res.json()["logs"]), 0)
|
||||
|
||||
def test_api_import_unknown_path(self):
|
||||
"""Path not in available blueprints is rejected (covers api.py:56)."""
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={"path": "does/not/exist.yaml"},
|
||||
format="multipart",
|
||||
)
|
||||
@@ -207,7 +203,7 @@ class TestBlueprintsV1API(APITestCase):
|
||||
def test_api_import_blank_context(self):
|
||||
"""Blank context is normalized to empty dict (covers api.py:62)."""
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={
|
||||
"path": "example/flows-invitation-enrollment-minimal.yaml",
|
||||
"context": "",
|
||||
@@ -219,7 +215,7 @@ class TestBlueprintsV1API(APITestCase):
|
||||
def test_api_import_invalid_json_context(self):
|
||||
"""Malformed JSON context raises ValidationError (covers api.py:65-66)."""
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={
|
||||
"path": "example/flows-invitation-enrollment-minimal.yaml",
|
||||
"context": "{not json",
|
||||
@@ -232,7 +228,7 @@ class TestBlueprintsV1API(APITestCase):
|
||||
def test_api_import_non_object_context(self):
|
||||
"""JSON context that isn't an object is rejected (covers api.py:68)."""
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-import"),
|
||||
reverse("authentik_api:blueprintinstance-import-"),
|
||||
data={
|
||||
"path": "example/flows-invitation-enrollment-minimal.yaml",
|
||||
"context": "[1, 2, 3]",
|
||||
@@ -241,29 +237,3 @@ class TestBlueprintsV1API(APITestCase):
|
||||
)
|
||||
self.assertEqual(res.status_code, 400)
|
||||
self.assertIn("Context must be a JSON object", res.content.decode())
|
||||
|
||||
def test_api_validate(self):
|
||||
"""Test that the import endpoint applies the supplied context to the real blueprint"""
|
||||
content = """
|
||||
version: 1
|
||||
entries:
|
||||
- model: authentik_providers_oauth2.scopemapping
|
||||
id: sm
|
||||
identifiers: { scope_name: test-tag-scope }
|
||||
attrs:
|
||||
name: test-tag-scope
|
||||
scope_name: test-tag-scope
|
||||
expression: "return {}"
|
||||
"""
|
||||
file = SimpleUploadedFile("test.yaml", content.encode())
|
||||
|
||||
res = self.client.post(
|
||||
reverse("authentik_api:blueprintinstance-validate"),
|
||||
data={"file": file},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
self.assertEqual(res.status_code, 200)
|
||||
self.assertTrue(res.json()["success"])
|
||||
self.assertFalse(res.json()["imported"])
|
||||
self.assertFalse(ScopeMapping.objects.filter(scope_name="test-tag-scope"))
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Test blueprints v1 tasks"""
|
||||
|
||||
from hashlib import sha512
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile, mkdtemp
|
||||
|
||||
from django.test import TransactionTestCase
|
||||
@@ -157,216 +156,3 @@ class TestBlueprintsV1Tasks(TransactionTestCase):
|
||||
instance.status,
|
||||
BlueprintInstanceStatus.UNKNOWN,
|
||||
)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_valid_crlf(self):
|
||||
"""Test discovered hash matches the applied hash for a file with CRLF line endings"""
|
||||
blueprint_id = generate_id()
|
||||
with NamedTemporaryFile(suffix=".yaml", dir=TMP) as file:
|
||||
file.write(
|
||||
f"version: 1\r\nentries: []\r\nmetadata:\r\n name: {blueprint_id}\r\n".encode()
|
||||
)
|
||||
file.flush()
|
||||
file_hash = sha512(Path(file.name).read_text(encoding="utf-8").encode()).hexdigest()
|
||||
for _ in range(2):
|
||||
blueprints_discovery.send()
|
||||
instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
|
||||
self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
|
||||
found = next(
|
||||
found for found in blueprints_find() if found.path == Path(file.name).name
|
||||
)
|
||||
self.assertEqual(found.hash, file_hash)
|
||||
self.assertEqual(instance.last_applied_hash, found.hash)
|
||||
file.seek(0)
|
||||
self.assertIn(b"\r\n", file.read())
|
||||
|
||||
def write_blueprint(self, file, value: str):
|
||||
file.seek(0)
|
||||
file.truncate()
|
||||
file.write(f"version: 1\nentries: []\ncontext:\n secret: {value}\n")
|
||||
file.flush()
|
||||
return next(found for found in blueprints_find() if found.path == Path(file.name).name).hash
|
||||
|
||||
def write_secret(self, file, value: str):
|
||||
file.seek(0)
|
||||
file.truncate()
|
||||
file.write(value)
|
||||
file.flush()
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_content_changed(self):
|
||||
"""Test hash changes when the contents of a referenced `!File` change"""
|
||||
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
|
||||
for label, reference in (
|
||||
("direct", f"!File {secret.name}"),
|
||||
("argument of another tag", f'!Format ["client-%s", !File {secret.name}]'),
|
||||
("reached through a cycle", f"&anchor [*anchor, !File {secret.name}]"),
|
||||
("reached through an alias", f"&anchor [!File {secret.name}]\n other: *anchor"),
|
||||
):
|
||||
with (
|
||||
self.subTest(label),
|
||||
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
|
||||
):
|
||||
self.write_secret(secret, "initial")
|
||||
before = self.write_blueprint(file, reference)
|
||||
self.write_secret(secret, "rotated")
|
||||
self.assertNotEqual(before, self.write_blueprint(file, reference))
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_created(self):
|
||||
"""Test hash changes when a referenced `!File` that was missing appears"""
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
secret_path = Path(TMP) / generate_id()
|
||||
reference = f"!File {secret_path}"
|
||||
before = self.write_blueprint(file, reference)
|
||||
secret_path.write_text("created")
|
||||
try:
|
||||
after = self.write_blueprint(file, reference)
|
||||
finally:
|
||||
secret_path.unlink()
|
||||
self.assertNotEqual(before, after)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_removed(self):
|
||||
"""Test hash changes when a referenced `!File` that existed disappears"""
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
secret_path = Path(TMP) / generate_id()
|
||||
secret_path.write_text("present")
|
||||
reference = f"!File {secret_path}"
|
||||
try:
|
||||
before = self.write_blueprint(file, reference)
|
||||
finally:
|
||||
secret_path.unlink()
|
||||
self.assertNotEqual(before, self.write_blueprint(file, reference))
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_contents_swapped(self):
|
||||
"""Test hash changes when two referenced `!File`s exchange their contents"""
|
||||
with (
|
||||
NamedTemporaryFile(mode="w+", dir=TMP) as first,
|
||||
NamedTemporaryFile(mode="w+", dir=TMP) as second,
|
||||
):
|
||||
self.write_secret(first, "alpha")
|
||||
self.write_secret(second, "beta")
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
reference = f"[!File {first.name}, !File {second.name}]"
|
||||
before = self.write_blueprint(file, reference)
|
||||
self.write_secret(first, "beta")
|
||||
self.write_secret(second, "alpha")
|
||||
self.assertNotEqual(before, self.write_blueprint(file, reference))
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_missing_and_readable_swapped(self):
|
||||
"""Test hash changes when one referenced `!File` disappears as another appears
|
||||
with the same contents"""
|
||||
first = Path(TMP) / generate_id()
|
||||
second = Path(TMP) / generate_id()
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
reference = f"[!File {first}, !File {second}]"
|
||||
second.write_text("shared")
|
||||
try:
|
||||
before = self.write_blueprint(file, reference)
|
||||
finally:
|
||||
second.unlink()
|
||||
first.write_text("shared")
|
||||
try:
|
||||
after = self.write_blueprint(file, reference)
|
||||
finally:
|
||||
first.unlink()
|
||||
self.assertNotEqual(before, after)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_hashed_once_per_route(self):
|
||||
"""Test a referenced `!File` is folded into the hash once for each route to it"""
|
||||
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
|
||||
self.write_secret(secret, "initial")
|
||||
for label, reference, routes in (
|
||||
("cycle", f"&anchor [*anchor, !File {secret.name}]", 1),
|
||||
("alias", f"&anchor [!File {secret.name}]\n other: *anchor", 2),
|
||||
):
|
||||
with (
|
||||
self.subTest(label),
|
||||
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
|
||||
):
|
||||
content = f"version: 1\nentries: []\ncontext:\n secret: {reference}\n"
|
||||
expected = sha512(content.encode())
|
||||
for _ in range(routes):
|
||||
expected.update(sha512(b"initial").digest())
|
||||
self.assertEqual(self.write_blueprint(file, reference), expected.hexdigest())
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_content_unchanged(self):
|
||||
"""Test hash is stable when a referenced `!File` does not change"""
|
||||
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
|
||||
self.write_secret(secret, "initial")
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
reference = f"!File {secret.name}"
|
||||
self.assertEqual(
|
||||
self.write_blueprint(file, reference),
|
||||
self.write_blueprint(file, reference),
|
||||
)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_unreadable_hash_stable(self):
|
||||
"""Test hash is stable when a referenced `!File` cannot be read"""
|
||||
for label, reference in (
|
||||
("missing file", f"!File {Path(TMP) / generate_id()}"),
|
||||
("path from a tag", f'!File [!Env [{generate_id()}, "{TMP}/fallback"], "default"]'),
|
||||
("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
|
||||
("path no syscall can take", '!File "\\0"'),
|
||||
("deeply nested", "[" * 50 + f'!File "{TMP}/fallback"' + "]" * 50),
|
||||
):
|
||||
with (
|
||||
self.subTest(label),
|
||||
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file,
|
||||
):
|
||||
self.assertEqual(
|
||||
self.write_blueprint(file, reference),
|
||||
self.write_blueprint(file, reference),
|
||||
)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_unreadable_discovery_continues(self):
|
||||
"""Test a blueprint that cannot be hashed does not stop others being discovered"""
|
||||
for label, reference in (
|
||||
("path from a mapping", f'!File {{path: "{TMP}/fallback"}}'),
|
||||
("path no syscall can take", '!File "\\0"'),
|
||||
("path outside the filesystem encoding", '!File "\\ud800"'),
|
||||
("sequence containing itself", "&anchor [*anchor]"),
|
||||
("mapping containing itself", "&anchor {key: *anchor}"),
|
||||
("two anchors containing each other", "&outer [{inner: &inner [*outer]}, *inner]"),
|
||||
):
|
||||
with (
|
||||
self.subTest(label),
|
||||
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as broken,
|
||||
NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as healthy,
|
||||
):
|
||||
broken.write(f"version: 1\nentries: []\ncontext:\n secret: {reference}\n")
|
||||
broken.flush()
|
||||
healthy.write(f"version: 1\nentries: []\nmetadata:\n name: {generate_id()}\n")
|
||||
healthy.flush()
|
||||
found = [blueprint.path for blueprint in blueprints_find()]
|
||||
self.assertIn(Path(healthy.name).name, found)
|
||||
self.assertIn(Path(broken.name).name, found)
|
||||
|
||||
@CONFIG.patch("blueprints_dir", TMP)
|
||||
def test_file_tag_applied_on_change(self):
|
||||
"""Test blueprint is re-applied when the contents of a referenced `!File` change"""
|
||||
blueprint_id = generate_id()
|
||||
with NamedTemporaryFile(mode="w+", dir=TMP) as secret:
|
||||
self.write_secret(secret, "initial")
|
||||
with NamedTemporaryFile(mode="w+", suffix=".yaml", dir=TMP) as file:
|
||||
file.write(
|
||||
f"version: 1\nentries: []\n"
|
||||
f"metadata:\n name: {blueprint_id}\n"
|
||||
f"context:\n secret: !File {secret.name}\n"
|
||||
)
|
||||
file.flush()
|
||||
blueprints_discovery.send()
|
||||
instance = BlueprintInstance.objects.filter(name=blueprint_id).first()
|
||||
before = instance.last_applied_hash
|
||||
self.assertEqual(instance.status, BlueprintInstanceStatus.SUCCESSFUL)
|
||||
self.write_secret(secret, "rotated")
|
||||
blueprints_discovery.send()
|
||||
instance.refresh_from_db()
|
||||
self.assertNotEqual(instance.last_applied_hash, before)
|
||||
@@ -1,12 +1,11 @@
|
||||
"""transfer common classes"""
|
||||
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Generator, Iterable, Mapping, Sequence
|
||||
from collections.abc import Generator, Iterable, Mapping
|
||||
from copy import copy
|
||||
from dataclasses import asdict, dataclass, field, is_dataclass
|
||||
from enum import Enum
|
||||
from functools import reduce
|
||||
from itertools import count
|
||||
from json import JSONDecodeError, loads
|
||||
from operator import ixor
|
||||
from os import getenv
|
||||
@@ -15,17 +14,15 @@ from uuid import UUID
|
||||
|
||||
from deepmerge import always_merger
|
||||
from django.apps import apps
|
||||
from django.db.models import CharField, Model, Q, TextField, UniqueConstraint
|
||||
from django.utils.text import slugify
|
||||
from django.db.models import Model, Q
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.fields import Field
|
||||
from rest_framework.relations import ManyRelatedField, PrimaryKeyRelatedField
|
||||
from rest_framework.serializers import Serializer
|
||||
from structlog.stdlib import get_logger
|
||||
from yaml import SafeDumper, SafeLoader, ScalarNode, SequenceNode
|
||||
|
||||
from authentik.lib.models import SerializerModel
|
||||
from authentik.lib.tracing.exceptions import TracingIgnoredException
|
||||
from authentik.lib.sentry import SentryIgnoredException
|
||||
from authentik.policies.models import PolicyBindingModel
|
||||
|
||||
LOGGER = get_logger()
|
||||
@@ -35,7 +32,7 @@ class UNSET:
|
||||
"""Used to test whether a key has not been set."""
|
||||
|
||||
|
||||
def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]:
|
||||
def get_attrs(obj: SerializerModel) -> dict[str, Any]:
|
||||
"""Get object's attributes via their serializer, and convert it to a normal dict"""
|
||||
serializer: Serializer = obj.serializer(obj)
|
||||
data = dict(serializer.data)
|
||||
@@ -48,151 +45,7 @@ def get_attrs(obj: SerializerModel) -> tuple[dict[str, Any], dict[str, Field]]:
|
||||
data.pop(field_name, None)
|
||||
if field_name.endswith("_set"):
|
||||
data.pop(field_name, None)
|
||||
return data, serializer.fields
|
||||
|
||||
|
||||
def _relation_target_model(ser_field: Field) -> type[Model] | None:
|
||||
"""Get the model a relational serializer field points to, if any"""
|
||||
if isinstance(ser_field, ManyRelatedField):
|
||||
ser_field = ser_field.child_relation
|
||||
if isinstance(ser_field, PrimaryKeyRelatedField) and ser_field.queryset is not None:
|
||||
return ser_field.queryset.model
|
||||
return None
|
||||
|
||||
|
||||
def resolve_references(
|
||||
attrs: dict[str, Any], fields: dict[str, Field], reference_index: ReferenceIndex
|
||||
) -> dict[str, Any]:
|
||||
"""Replace any attrs value that references another exported object with a `KeyOf` tag"""
|
||||
for name, _field in fields.items():
|
||||
if name not in attrs or attrs[name] is None:
|
||||
continue
|
||||
target_model = _relation_target_model(_field)
|
||||
if target_model is None:
|
||||
continue
|
||||
if isinstance(_field, ManyRelatedField):
|
||||
attrs[name] = [
|
||||
(
|
||||
KeyOf(id_from=entry_id)
|
||||
if (entry_id := reference_index.lookup(value, target_model))
|
||||
else value
|
||||
)
|
||||
for value in attrs[name]
|
||||
]
|
||||
else:
|
||||
entry_id = reference_index.lookup(attrs[name], target_model)
|
||||
if entry_id:
|
||||
attrs[name] = KeyOf(id_from=entry_id)
|
||||
return attrs
|
||||
|
||||
|
||||
def _stable_identifier_fields(model_class: type[Model]) -> list[str]:
|
||||
"""List the names of unique, non-relational text fields on a model (other than its
|
||||
primary key) that could serve as stable identifiers, portable across authentik instances"""
|
||||
return [
|
||||
model_field.attname
|
||||
for model_field in model_class._meta.fields
|
||||
if not model_field.primary_key
|
||||
and isinstance(model_field, CharField | TextField)
|
||||
and model_field.unique
|
||||
]
|
||||
|
||||
|
||||
def _is_stable_value(value: Any) -> bool:
|
||||
"""A value is considered stable (portable across instances) if it's a non-empty
|
||||
string that isn't a UUID, which is almost always instance-local (e.g. a random default)"""
|
||||
if not value or not isinstance(value, str):
|
||||
return False
|
||||
try:
|
||||
UUID(value)
|
||||
return False
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
|
||||
def _readable_key(obj: Model) -> str | None:
|
||||
"""Find a unique, human-readable text field on `obj` (not a UUID) to make
|
||||
a !KeyOf id easier to read than a bare counter, e.g. a slug or name."""
|
||||
for field_name in _stable_identifier_fields(type(obj)):
|
||||
value = getattr(obj, field_name, None)
|
||||
if not _is_stable_value(value):
|
||||
continue
|
||||
slug = slugify(value)
|
||||
if slug:
|
||||
return slug
|
||||
return None
|
||||
|
||||
|
||||
def _unique_together_groups(model_class: type[Model]) -> Iterable[tuple[str, ...]]:
|
||||
"""Field-name groups declared unique together on a model, via either the legacy
|
||||
Meta.unique_together or a plain (unconditional) Meta.constraints UniqueConstraint"""
|
||||
yield from model_class._meta.unique_together
|
||||
for constraint in model_class._meta.constraints:
|
||||
if not isinstance(constraint, UniqueConstraint):
|
||||
continue
|
||||
if not constraint.condition and constraint.fields:
|
||||
yield constraint.fields
|
||||
|
||||
|
||||
def _composite_identifier_fields(
|
||||
model_class: type[Model], all_attrs: dict[str, Any], fields: dict[str, Field]
|
||||
) -> list[str]:
|
||||
"""When no single field can serve as a stable identifier, fall back to a composite
|
||||
of fields that together identify the instance: a declared unique-together group if
|
||||
one is fully known, otherwise every populated relation to another exported object
|
||||
(e.g. a binding's target and policy), mirroring how such join objects are naturally
|
||||
keyed. Portable across instances, as relations are resolved to !KeyOf tags."""
|
||||
for group in _unique_together_groups(model_class):
|
||||
if all(name in all_attrs and all_attrs[name] is not None for name in group):
|
||||
return list(group)
|
||||
return [
|
||||
name
|
||||
for name, ser_field in fields.items()
|
||||
if name in all_attrs
|
||||
and all_attrs[name] is not None
|
||||
and _relation_target_model(ser_field) is not None
|
||||
]
|
||||
|
||||
|
||||
class ReferenceIndex:
|
||||
"""Tracks exported model instances so relations between them can be
|
||||
rewritten as !KeyOf references instead of raw primary keys."""
|
||||
|
||||
def __init__(self):
|
||||
self._entries: dict[Any, tuple[type[Model], str]] = {}
|
||||
self._used: set[str] = set()
|
||||
self._seen_ids: set[str] = set()
|
||||
self._counter = count(1)
|
||||
|
||||
def register(self, obj: Model) -> str:
|
||||
"""Register an exported model instance, returning the id assigned to it"""
|
||||
readable_key = _readable_key(obj)
|
||||
entry_id = f"{obj._meta.model_name}-{readable_key or next(self._counter)}"
|
||||
if entry_id in self._seen_ids:
|
||||
entry_id = f"{entry_id}-{next(self._counter)}"
|
||||
self._seen_ids.add(entry_id)
|
||||
self._entries[obj.pk] = (type(obj), entry_id)
|
||||
return entry_id
|
||||
|
||||
def id_for(self, obj: Model) -> str | None:
|
||||
"""Get the id assigned to a previously registered model instance, if any"""
|
||||
entry = self._entries.get(obj.pk)
|
||||
return entry[1] if entry else None
|
||||
|
||||
def lookup(self, value: Any, target_model: type[Model]) -> str | None:
|
||||
"""Look up the id of a registered model instance by its primary key,
|
||||
provided it is an instance of `target_model`"""
|
||||
entry = self._entries.get(value)
|
||||
if entry and issubclass(entry[0], target_model):
|
||||
self._used.add(entry[1])
|
||||
return entry[1]
|
||||
return None
|
||||
|
||||
def clear_unused_ids(self, entries: Iterable[BlueprintEntry], objects: Iterable[Model]) -> None:
|
||||
"""Strip the id from any entry that is never referenced by a !KeyOf tag"""
|
||||
for entry, obj in zip(entries, objects, strict=True):
|
||||
if self.id_for(obj) not in self._used:
|
||||
entry.id = None
|
||||
return data
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -239,39 +92,20 @@ class BlueprintEntry:
|
||||
self.__tag_contexts: list[YAMLTagContext] = []
|
||||
|
||||
@staticmethod
|
||||
def from_model(
|
||||
model: SerializerModel,
|
||||
reference_index: ReferenceIndex | None = None,
|
||||
) -> BlueprintEntry:
|
||||
def from_model(model: SerializerModel, *extra_identifier_names: str) -> BlueprintEntry:
|
||||
"""Convert a SerializerModel instance to a blueprint Entry"""
|
||||
all_attrs, fields = get_attrs(model)
|
||||
if reference_index is not None:
|
||||
all_attrs = resolve_references(all_attrs, fields, reference_index)
|
||||
identifiers = {
|
||||
"pk": model.pk,
|
||||
}
|
||||
all_attrs = get_attrs(model)
|
||||
|
||||
identifier_names = [
|
||||
field_name
|
||||
for field_name in _stable_identifier_fields(type(model))
|
||||
if field_name in all_attrs and _is_stable_value(all_attrs[field_name])
|
||||
]
|
||||
|
||||
if not identifier_names:
|
||||
identifier_names = _composite_identifier_fields(type(model), all_attrs, fields)
|
||||
|
||||
identifiers = {}
|
||||
for identifier_name in identifier_names:
|
||||
identifiers[identifier_name] = all_attrs.pop(identifier_name, None)
|
||||
# Only fall back to the (instance-local, non-portable) primary key when no other
|
||||
# stable identifier could be found
|
||||
if not identifiers:
|
||||
identifiers["pk"] = model.pk
|
||||
entry = BlueprintEntry(
|
||||
for extra_identifier_name in extra_identifier_names:
|
||||
identifiers[extra_identifier_name] = all_attrs.pop(extra_identifier_name, None)
|
||||
return BlueprintEntry(
|
||||
identifiers=identifiers,
|
||||
model=f"{model._meta.app_label}.{model._meta.model_name}",
|
||||
attrs=all_attrs,
|
||||
)
|
||||
if reference_index is not None:
|
||||
entry.id = reference_index.id_for(model)
|
||||
return entry
|
||||
|
||||
def get_tag_context(
|
||||
self,
|
||||
@@ -398,14 +232,9 @@ class KeyOf(YAMLTag):
|
||||
|
||||
id_from: str
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
loader: BlueprintLoader | None = None,
|
||||
node: ScalarNode | None = None,
|
||||
id_from: str | None = None,
|
||||
) -> None:
|
||||
def __init__(self, loader: BlueprintLoader, node: ScalarNode) -> None:
|
||||
super().__init__()
|
||||
self.id_from = node.value if node is not None else id_from
|
||||
self.id_from = node.value
|
||||
|
||||
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||
for _entry in blueprint.iter_entries():
|
||||
@@ -439,11 +268,7 @@ class Env(YAMLTag):
|
||||
self.default = loader.construct_object(node.value[1])
|
||||
|
||||
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||
if env := getenv(self.key):
|
||||
return env
|
||||
if isinstance(self.default, YAMLTag):
|
||||
return self.default.resolve(entry, blueprint)
|
||||
return self.default
|
||||
return getenv(self.key) or self.default
|
||||
|
||||
|
||||
class File(YAMLTag):
|
||||
@@ -489,47 +314,13 @@ class Context(YAMLTag):
|
||||
self.key = loader.construct_object(node.value[0])
|
||||
self.default = loader.construct_object(node.value[1])
|
||||
|
||||
def _resolve(
|
||||
self,
|
||||
entry: BlueprintEntry,
|
||||
blueprint: Blueprint,
|
||||
context: Sequence | Mapping,
|
||||
path: str,
|
||||
_segment: str | int | None = None,
|
||||
) -> Any:
|
||||
"""Recursively resolve context"""
|
||||
if _segment is not None:
|
||||
context = context[_segment]
|
||||
|
||||
if isinstance(context, YAMLTag):
|
||||
context = context.resolve(entry, blueprint)
|
||||
|
||||
value = UNSET
|
||||
|
||||
if isinstance(context, Sequence) and not isinstance(context, (str, bytes)):
|
||||
if path.isdigit() and 0 <= int(path) < len(context):
|
||||
value = context[int(path)]
|
||||
elif path in context:
|
||||
value = context[path]
|
||||
|
||||
if value is not UNSET:
|
||||
if isinstance(value, YAMLTag):
|
||||
value = value.resolve(entry, blueprint)
|
||||
return value
|
||||
|
||||
if "." in path:
|
||||
new_head, new_key = path.split(".", 1)
|
||||
|
||||
if isinstance(context, Sequence) and not isinstance(context, (str, bytes)):
|
||||
if new_head.isdigit() and 0 <= int(new_head) < len(context):
|
||||
return self._resolve(entry, blueprint, context, new_key, int(new_head))
|
||||
elif new_head in context:
|
||||
return self._resolve(entry, blueprint, context, new_key, new_head)
|
||||
|
||||
return self.default
|
||||
|
||||
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||
return self._resolve(entry, blueprint, blueprint.context, self.key)
|
||||
value = self.default
|
||||
if self.key in blueprint.context:
|
||||
value = blueprint.context[self.key]
|
||||
if isinstance(value, YAMLTag):
|
||||
return value.resolve(entry, blueprint)
|
||||
return value
|
||||
|
||||
|
||||
class ParseJSON(YAMLTag):
|
||||
@@ -639,14 +430,12 @@ class FindObject(Find):
|
||||
class Condition(YAMLTag):
|
||||
"""Convert all values to a single boolean"""
|
||||
|
||||
mode: Literal["EQ", "NEQ", "AND", "NAND", "OR", "NOR", "XOR", "XNOR"]
|
||||
mode: Literal["AND", "NAND", "OR", "NOR", "XOR", "XNOR"]
|
||||
args: list[Any]
|
||||
|
||||
_COMPARATORS = {
|
||||
# Using all and any here instead of from operator import iand, ior
|
||||
# to improve performance
|
||||
"EQ": lambda args: all(x == args[0] for x in args),
|
||||
"NEQ": lambda args: not all(x == args[0] for x in args),
|
||||
"AND": all,
|
||||
"NAND": lambda args: not all(args),
|
||||
"OR": any,
|
||||
@@ -904,9 +693,6 @@ class BlueprintDumper(SafeDumper):
|
||||
self.add_representer(
|
||||
BlueprintEntryDesiredState, lambda self, data: self.represent_str(data.value)
|
||||
)
|
||||
self.add_representer(
|
||||
KeyOf, lambda self, data: self.represent_scalar("!KeyOf", data.id_from)
|
||||
)
|
||||
self.add_representer(None, lambda self, data: self.represent_str(str(data)))
|
||||
|
||||
def ignore_aliases(self, data):
|
||||
@@ -950,7 +736,7 @@ class BlueprintLoader(SafeLoader):
|
||||
self.add_constructor("!ParseJSON", ParseJSON)
|
||||
|
||||
|
||||
class EntryInvalidError(TracingIgnoredException):
|
||||
class EntryInvalidError(SentryIgnoredException):
|
||||
"""Error raised when an entry is invalid"""
|
||||
|
||||
entry_model: str | None
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Blueprint exporter"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from django.apps import apps
|
||||
@@ -16,14 +15,13 @@ from authentik.blueprints.v1.common import (
|
||||
BlueprintDumper,
|
||||
BlueprintEntry,
|
||||
BlueprintMetadata,
|
||||
ReferenceIndex,
|
||||
)
|
||||
from authentik.blueprints.v1.importer import is_model_allowed
|
||||
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_GENERATED
|
||||
from authentik.events.models import Event
|
||||
from authentik.flows.models import Flow, FlowStageBinding, Stage
|
||||
from authentik.policies.models import Policy, PolicyBinding
|
||||
from authentik.stages.prompt.models import Prompt, PromptStage
|
||||
from authentik.stages.prompt.models import PromptStage
|
||||
|
||||
|
||||
class Exporter:
|
||||
@@ -38,21 +36,13 @@ class Exporter:
|
||||
|
||||
def get_entries(self) -> Iterable[BlueprintEntry]:
|
||||
"""Get blueprint entries"""
|
||||
reference_index = ReferenceIndex()
|
||||
instances: list[Model] = []
|
||||
for model in apps.get_models():
|
||||
if not is_model_allowed(model):
|
||||
continue
|
||||
if model in self.excluded_models:
|
||||
continue
|
||||
for obj in self.get_model_instances(model):
|
||||
instances.append(obj)
|
||||
reference_index.register(obj)
|
||||
entries = [
|
||||
BlueprintEntry.from_model(obj, reference_index=reference_index) for obj in instances
|
||||
]
|
||||
reference_index.clear_unused_ids(entries, instances)
|
||||
return entries
|
||||
yield BlueprintEntry.from_model(obj)
|
||||
|
||||
def get_model_instances(self, model: type[Model]) -> QuerySet:
|
||||
"""Return a queryset for `model`. Can be used to filter some
|
||||
@@ -106,74 +96,54 @@ class FlowExporter(Exporter):
|
||||
"pbm_uuid", flat=True
|
||||
)
|
||||
|
||||
def _stages(self) -> Iterable[Stage]:
|
||||
"""Get all stages attached to self.flow"""
|
||||
return Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
|
||||
def walk_stages(self) -> Iterable[BlueprintEntry]:
|
||||
"""Convert all stages attached to self.flow into BlueprintEntry objects"""
|
||||
stages = Stage.objects.filter(flow=self.flow).select_related().select_subclasses()
|
||||
for stage in stages:
|
||||
if isinstance(stage, PromptStage):
|
||||
pass
|
||||
yield BlueprintEntry.from_model(stage, "name")
|
||||
|
||||
def _stage_bindings(self) -> Iterable[FlowStageBinding]:
|
||||
"""Get all bindings attached to self.flow"""
|
||||
return FlowStageBinding.objects.filter(target=self.flow).select_related()
|
||||
def walk_stage_bindings(self) -> Iterable[BlueprintEntry]:
|
||||
"""Convert all bindings attached to self.flow into BlueprintEntry objects"""
|
||||
bindings = FlowStageBinding.objects.filter(target=self.flow).select_related()
|
||||
for binding in bindings:
|
||||
yield BlueprintEntry.from_model(binding, "target", "stage", "order")
|
||||
|
||||
def _policies(self) -> Iterable[Policy]:
|
||||
"""Get all policies. This is done at the beginning of the export for stages that have
|
||||
def walk_policies(self) -> Iterable[BlueprintEntry]:
|
||||
"""Walk over all policies. This is done at the beginning of the export for stages that have
|
||||
a direct foreign key to a policy."""
|
||||
# Special case for PromptStage as that has a direct M2M to policy, we have to ensure
|
||||
# all policies referenced in there we also include here
|
||||
prompt_stages = PromptStage.objects.filter(flow=self.flow).values_list("pk", flat=True)
|
||||
query = Q(bindings__in=self.pbm_uuids) | Q(promptstage__in=prompt_stages)
|
||||
return Policy.objects.filter(query).select_related()
|
||||
policies = Policy.objects.filter(query).select_related()
|
||||
for policy in policies:
|
||||
yield BlueprintEntry.from_model(policy)
|
||||
|
||||
def _policy_bindings(self) -> Iterable[PolicyBinding]:
|
||||
"""Get all policybindings relative to us. This is run at the end of the export, as
|
||||
def walk_policy_bindings(self) -> Iterable[BlueprintEntry]:
|
||||
"""Walk over all policybindings relative to us. This is run at the end of the export, as
|
||||
we are sure all objects exist now."""
|
||||
return PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
|
||||
bindings = PolicyBinding.objects.filter(target__in=self.pbm_uuids).select_related()
|
||||
for binding in bindings:
|
||||
yield BlueprintEntry.from_model(binding, "policy", "target", "order")
|
||||
|
||||
def _stage_prompts(self) -> Iterable[Prompt]:
|
||||
"""Get all prompts associated with any PromptStages, deduplicated as multiple stages
|
||||
may share the same prompt"""
|
||||
def walk_stage_prompts(self) -> Iterable[BlueprintEntry]:
|
||||
"""Walk over all prompts associated with any PromptStages"""
|
||||
prompt_stages = PromptStage.objects.filter(flow=self.flow)
|
||||
prompts: dict[Any, Prompt] = {}
|
||||
for stage in prompt_stages:
|
||||
for prompt in stage.fields.all():
|
||||
prompts[prompt.pk] = prompt
|
||||
return prompts.values()
|
||||
yield BlueprintEntry.from_model(prompt)
|
||||
|
||||
def get_entries(self) -> Iterable[BlueprintEntry]:
|
||||
reference_index = ReferenceIndex()
|
||||
reference_index.register(self.flow)
|
||||
|
||||
prompts = list(self._stage_prompts()) if self.with_stage_prompts else []
|
||||
policies = list(self._policies()) if self.with_policies else []
|
||||
stages = list(self._stages())
|
||||
stage_bindings = list(self._stage_bindings())
|
||||
policy_bindings = list(self._policy_bindings()) if self.with_policies else []
|
||||
|
||||
for obj in (*prompts, *policies, *stages, *stage_bindings, *policy_bindings):
|
||||
reference_index.register(obj)
|
||||
|
||||
objects = [self.flow, *prompts, *policies, *stages, *stage_bindings, *policy_bindings]
|
||||
entries = [
|
||||
BlueprintEntry.from_model(self.flow, reference_index=reference_index),
|
||||
*(
|
||||
BlueprintEntry.from_model(prompt, reference_index=reference_index)
|
||||
for prompt in prompts
|
||||
),
|
||||
*(
|
||||
BlueprintEntry.from_model(policy, reference_index=reference_index)
|
||||
for policy in policies
|
||||
),
|
||||
*(
|
||||
BlueprintEntry.from_model(stage, reference_index=reference_index)
|
||||
for stage in stages
|
||||
),
|
||||
*(
|
||||
BlueprintEntry.from_model(binding, reference_index=reference_index)
|
||||
for binding in stage_bindings
|
||||
),
|
||||
*(
|
||||
BlueprintEntry.from_model(binding, reference_index=reference_index)
|
||||
for binding in policy_bindings
|
||||
),
|
||||
]
|
||||
reference_index.clear_unused_ids(entries, objects)
|
||||
entries = []
|
||||
entries.append(BlueprintEntry.from_model(self.flow, "slug"))
|
||||
if self.with_stage_prompts:
|
||||
entries.extend(self.walk_stage_prompts())
|
||||
if self.with_policies:
|
||||
entries.extend(self.walk_policies())
|
||||
entries.extend(self.walk_stages())
|
||||
entries.extend(self.walk_stage_bindings())
|
||||
if self.with_policies:
|
||||
entries.extend(self.walk_policy_bindings())
|
||||
return entries
|
||||
@@ -1,60 +0,0 @@
|
||||
"""Blueprint hashing"""
|
||||
|
||||
from collections.abc import Generator
|
||||
from hashlib import sha512
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from yaml import load
|
||||
from yaml.error import YAMLError
|
||||
|
||||
from authentik.blueprints.v1.common import BlueprintLoader, File, YAMLTag
|
||||
|
||||
|
||||
def iter_file_tags(value: Any, ancestors: frozenset[int] = frozenset()) -> Generator[File]:
|
||||
"""Find all `!File` tags in a loaded blueprint, including tags used as arguments
|
||||
of other tags. A node is not descended into again below itself; a node reached by
|
||||
several routes is visited once per route."""
|
||||
if id(value) in ancestors:
|
||||
return
|
||||
ancestors = ancestors | {id(value)}
|
||||
if isinstance(value, File):
|
||||
yield value
|
||||
if isinstance(value, dict):
|
||||
children = value.values()
|
||||
elif isinstance(value, list | tuple):
|
||||
children = value
|
||||
elif isinstance(value, YAMLTag):
|
||||
children = vars(value).values()
|
||||
else:
|
||||
return
|
||||
for child in children:
|
||||
yield from iter_file_tags(child, ancestors)
|
||||
|
||||
|
||||
# One byte where a readable reference contributes a 64-byte digest
|
||||
MISSING_FILE_MARKER = b"\0"
|
||||
|
||||
|
||||
def blueprint_hash(content: str) -> str:
|
||||
"""Hash a blueprint's content and the contents of the files it references with
|
||||
`!File` tags"""
|
||||
hasher = sha512(content.encode())
|
||||
try:
|
||||
raw_blueprint = load(content, BlueprintLoader)
|
||||
except YAMLError:
|
||||
return hasher.hexdigest()
|
||||
for tag in iter_file_tags(raw_blueprint):
|
||||
# Mapping-node tags have no path; nested tags cannot be resolved here
|
||||
path = getattr(tag, "path", None)
|
||||
if not isinstance(path, str):
|
||||
continue
|
||||
try:
|
||||
referenced = Path(path).read_bytes()
|
||||
except OSError, ValueError:
|
||||
# An unreadable reference still takes its place in the sequence, so a file
|
||||
# that goes missing while another appears cannot leave the hash unchanged
|
||||
hasher.update(MISSING_FILE_MARKER)
|
||||
continue
|
||||
hasher.update(sha512(referenced).digest())
|
||||
return hasher.hexdigest()
|
||||
@@ -20,7 +20,6 @@ from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.serializers import BaseSerializer, Serializer
|
||||
from structlog.stdlib import BoundLogger, get_logger
|
||||
from yaml import load
|
||||
from yaml.error import YAMLError
|
||||
|
||||
from authentik.blueprints.v1.common import (
|
||||
Blueprint,
|
||||
@@ -46,14 +45,14 @@ from authentik.events.logs import LogEvent, capture_logs
|
||||
from authentik.events.utils import cleanse_dict
|
||||
from authentik.flows.models import Stage
|
||||
from authentik.lib.models import InternallyManagedMixin, SerializerModel
|
||||
from authentik.lib.tracing.exceptions import TracingIgnoredException
|
||||
from authentik.lib.sentry import SentryIgnoredException
|
||||
from authentik.lib.utils.reflection import get_apps
|
||||
from authentik.outposts.models import OutpostServiceConnection
|
||||
from authentik.policies.models import Policy, PolicyBindingModel
|
||||
from authentik.rbac.models import Role
|
||||
|
||||
# Context set when the serializer is created in a blueprint context
|
||||
# Update website/docs/customize/blueprints/v1/models.mdx when used
|
||||
# Update website/docs/customize/blueprints/v1/models.md when used
|
||||
SERIALIZER_CONTEXT_BLUEPRINT = "blueprint_entry"
|
||||
|
||||
|
||||
@@ -97,7 +96,7 @@ def is_model_allowed(model: type[Model]) -> bool:
|
||||
)
|
||||
|
||||
|
||||
class DoRollback(TracingIgnoredException):
|
||||
class DoRollback(SentryIgnoredException):
|
||||
"""Exception to trigger a rollback"""
|
||||
|
||||
|
||||
@@ -155,16 +154,13 @@ class Importer:
|
||||
@staticmethod
|
||||
def from_string(yaml_input: str, context: dict | None = None) -> Importer:
|
||||
"""Parse YAML string and create blueprint importer from it"""
|
||||
try:
|
||||
import_dict = load(yaml_input, BlueprintLoader)
|
||||
except YAMLError as exc:
|
||||
raise EntryInvalidError(exc) from exc
|
||||
import_dict = load(yaml_input, BlueprintLoader)
|
||||
try:
|
||||
_import = from_dict(
|
||||
Blueprint, import_dict, config=Config(cast=[BlueprintEntryDesiredState])
|
||||
)
|
||||
except DaciteError as exc:
|
||||
raise EntryInvalidError(exc) from exc
|
||||
raise EntryInvalidError from exc
|
||||
return Importer(_import, context)
|
||||
|
||||
@property
|
||||
@@ -323,7 +319,7 @@ class Importer:
|
||||
model_instance = model()
|
||||
# pk needs to be set on the model instance otherwise a new one will be generated
|
||||
if "pk" in updated_identifiers:
|
||||
model_instance.pk = model._meta.pk.to_python(updated_identifiers["pk"])
|
||||
model_instance.pk = updated_identifiers["pk"]
|
||||
serializer.instance = model_instance
|
||||
return serializer
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ class MetaModelRegistry:
|
||||
|
||||
def get_models(self):
|
||||
"""Wrapper for django's `get_models` to list all models"""
|
||||
models = list(apps.get_models())
|
||||
models = apps.get_models()
|
||||
for _, value in self.models.items():
|
||||
models.append(value)
|
||||
return sorted(models, key=str)
|
||||
|
||||
@@ -16,14 +16,14 @@ from requests.exceptions import RequestException
|
||||
from structlog import get_logger
|
||||
from structlog.stdlib import BoundLogger
|
||||
|
||||
from authentik.lib.tracing.exceptions import TracingIgnoredException
|
||||
from authentik.lib.sentry import SentryIgnoredException
|
||||
from authentik.lib.utils.http import authentik_user_agent
|
||||
|
||||
OCI_MEDIA_TYPE = "application/vnd.goauthentik.blueprint.v1+yaml"
|
||||
OCI_PREFIX = "oci://"
|
||||
|
||||
|
||||
class OCIException(TracingIgnoredException):
|
||||
class OCIException(SentryIgnoredException):
|
||||
"""OCI-related errors"""
|
||||
|
||||
|
||||
|
||||
@@ -75,19 +75,19 @@ class SchemaBuilder:
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/definitions/blueprint_entry"},
|
||||
"items": {"$ref": "#/$defs/blueprint_entry"},
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
"type": "array",
|
||||
"items": {"$ref": "#/definitions/blueprint_entry"},
|
||||
"items": {"$ref": "#/$defs/blueprint_entry"},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
"definitions": {"blueprint_entry": {"oneOf": []}},
|
||||
"$defs": {"blueprint_entry": {"oneOf": []}},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@@ -118,7 +118,7 @@ class SchemaBuilder:
|
||||
}
|
||||
)
|
||||
model_path = f"{model._meta.app_label}.{model._meta.model_name}"
|
||||
self.schema["definitions"]["blueprint_entry"]["oneOf"].append(
|
||||
self.schema["$defs"]["blueprint_entry"]["oneOf"].append(
|
||||
self.template_entry(model_path, model, serializer)
|
||||
)
|
||||
|
||||
@@ -127,11 +127,11 @@ class SchemaBuilder:
|
||||
model_schema = self.to_jsonschema(serializer)
|
||||
model_schema["required"] = []
|
||||
def_name = f"model_{model_path}"
|
||||
def_path = f"#/definitions/{def_name}"
|
||||
self.schema["definitions"][def_name] = model_schema
|
||||
def_path = f"#/$defs/{def_name}"
|
||||
self.schema["$defs"][def_name] = model_schema
|
||||
def_name_perm = f"model_{model_path}_permissions"
|
||||
def_path_perm = f"#/definitions/{def_name_perm}"
|
||||
self.schema["definitions"][def_name_perm] = self.model_permissions(model)
|
||||
def_path_perm = f"#/$defs/{def_name_perm}"
|
||||
self.schema["$defs"][def_name_perm] = self.model_permissions(model)
|
||||
template = {
|
||||
"type": "object",
|
||||
"required": ["model", "identifiers"],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""v1 blueprints tasks"""
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from hashlib import sha512
|
||||
from pathlib import Path
|
||||
from sys import platform
|
||||
from uuid import UUID
|
||||
@@ -30,7 +31,6 @@ from authentik.blueprints.models import (
|
||||
BlueprintRetrievalFailed,
|
||||
)
|
||||
from authentik.blueprints.v1.common import BlueprintLoader, BlueprintMetadata, EntryInvalidError
|
||||
from authentik.blueprints.v1.hash import blueprint_hash
|
||||
from authentik.blueprints.v1.importer import Importer
|
||||
from authentik.blueprints.v1.labels import LABEL_AUTHENTIK_INSTANTIATE
|
||||
from authentik.blueprints.v1.oci import OCI_PREFIX
|
||||
@@ -40,6 +40,7 @@ from authentik.lib.config import CONFIG
|
||||
from authentik.tasks.apps import PRIORITY_HIGH
|
||||
from authentik.tasks.middleware import CurrentTask
|
||||
from authentik.tasks.schedules.models import Schedule
|
||||
from authentik.tenants.models import Tenant
|
||||
|
||||
LOGGER = get_logger()
|
||||
|
||||
@@ -91,16 +92,20 @@ class BlueprintEventHandler(FileSystemEventHandler):
|
||||
def on_created(self, event: FileSystemEvent):
|
||||
"""Process file creation"""
|
||||
LOGGER.debug("new blueprint file created, starting discovery")
|
||||
Schedule.dispatch_by_actor(blueprints_discovery)
|
||||
for tenant in Tenant.objects.filter(ready=True):
|
||||
with tenant:
|
||||
Schedule.dispatch_by_actor(blueprints_discovery)
|
||||
|
||||
def on_modified(self, event: FileSystemEvent):
|
||||
"""Process file modification"""
|
||||
path = Path(event.src_path)
|
||||
root = Path(CONFIG.get("blueprints_dir")).absolute()
|
||||
rel_path = str(path.relative_to(root))
|
||||
for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
|
||||
LOGGER.debug("modified blueprint file, starting apply", instance=instance)
|
||||
apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
|
||||
for tenant in Tenant.objects.filter(ready=True):
|
||||
with tenant:
|
||||
for instance in BlueprintInstance.objects.filter(path=rel_path, enabled=True):
|
||||
LOGGER.debug("modified blueprint file, starting apply", instance=instance)
|
||||
apply_blueprint.send_with_options(args=(instance.pk,), rel_obj=instance)
|
||||
|
||||
|
||||
@actor(
|
||||
@@ -124,9 +129,8 @@ def blueprints_find() -> list[BlueprintFile]:
|
||||
if any(part for part in rel_path.parts if part.startswith(".")):
|
||||
continue
|
||||
with open(path, encoding="utf-8") as blueprint_file:
|
||||
content = blueprint_file.read()
|
||||
try:
|
||||
raw_blueprint = load(content, BlueprintLoader)
|
||||
raw_blueprint = load(blueprint_file.read(), BlueprintLoader)
|
||||
except YAMLError as exc:
|
||||
raw_blueprint = None
|
||||
LOGGER.warning("failed to parse blueprint", exc=exc, path=str(rel_path))
|
||||
@@ -137,7 +141,7 @@ def blueprints_find() -> list[BlueprintFile]:
|
||||
if version != 1:
|
||||
LOGGER.warning("invalid blueprint version", version=version, path=str(rel_path))
|
||||
continue
|
||||
file_hash = blueprint_hash(content)
|
||||
file_hash = sha512(path.read_bytes()).hexdigest()
|
||||
blueprint = BlueprintFile(str(rel_path), version, file_hash, int(path.stat().st_mtime))
|
||||
blueprint.meta = from_dict(BlueprintMetadata, metadata) if metadata else None
|
||||
blueprints.append(blueprint)
|
||||
@@ -198,7 +202,7 @@ def apply_blueprint(instance_pk: UUID):
|
||||
self.info(f"Blueprint {instance.name} is disabled, skipping")
|
||||
return
|
||||
blueprint_content = instance.retrieve()
|
||||
file_hash = blueprint_hash(blueprint_content)
|
||||
file_hash = sha512(blueprint_content.encode()).hexdigest()
|
||||
importer = Importer.from_string(blueprint_content, instance.context)
|
||||
if importer.blueprint.metadata:
|
||||
instance.metadata = asdict(importer.blueprint.metadata)
|
||||
|
||||
Loaded 100 of 4677 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user