Compare commits
99 Commits
better-ver
...
providers/
| Author | SHA1 | Date | |
|---|---|---|---|
| 7549a6b83d | |||
| bb45b714e2 | |||
| 20e07486ee | |||
| 0cb7cf2c96 | |||
| 07736a90b2 | |||
| ec28a86259 | |||
| 260800c60b | |||
| ee4780394d | |||
| 23b746941f | |||
| 3c2ce40afd | |||
| 2aceed285e | |||
| 81e5fef667 | |||
| 7aa6593760 | |||
| c40a17beb9 | |||
| 335c9fbc10 | |||
| 51b53caf61 | |||
| 989100a900 | |||
| 8e1531d051 | |||
| f6f37d6d92 | |||
| 5b6ca70f22 | |||
| a74674c3d6 | |||
| f46984dec4 | |||
| c7963e4af7 | |||
| 6e30b11974 | |||
| 13bd4069e4 | |||
| 3b913ac5ef | |||
| fed094b317 | |||
| 88d83c10a4 | |||
| 5af2378738 | |||
| 6ec745ddc0 | |||
| a44375a9d8 | |||
| 3bf9cf681a | |||
| b8cf0e5dc4 | |||
| 2180bdf7c2 | |||
| 8af2d189d9 | |||
| 66f96a280e | |||
| 09d5c6fa43 | |||
| 6eb4e78b22 | |||
| c3eada8d33 | |||
| 48130a7463 | |||
| 9ffb2443f6 | |||
| 0b4aed7a3d | |||
| 86dd1a96f6 | |||
| 0ce017b77e | |||
| e22e79f310 | |||
| ac575aecfa | |||
| fd61fb31b5 | |||
| d7f6e5b79d | |||
| 09ded2a19a | |||
| 6d4c9a3446 | |||
| 74b5380f32 | |||
| c65b3e8ae5 | |||
| 88fa7e37dc | |||
| 8bfc9ab7c9 | |||
| f145580dae | |||
| 31eb4a6315 | |||
| 48696e3d7d | |||
| 734db4dee6 | |||
| 856ac052e7 | |||
| dea2d67ceb | |||
| a844fb41d4 | |||
| f4da22aea8 | |||
| 1464852b92 | |||
| 6aebf45aea | |||
| fad6ac76af | |||
| c60a145f95 | |||
| 652a32d968 | |||
| bd5a66a3c7 | |||
| a4c4b07614 | |||
| aaf76bab92 | |||
| 814f3fc43d | |||
| d017af1347 | |||
| 6e11554f62 | |||
| 14f2edc04b | |||
| 9f6173d8b2 | |||
| 52c3ba551d | |||
| 633c6ff245 | |||
| e5cb925f70 | |||
| a0b1327456 | |||
| 891907390b | |||
| e1c47c0f00 | |||
| 0b71aa43d1 | |||
| b4d26d5092 | |||
| 8a9f6fb1ce | |||
| 355f302cb7 | |||
| 11666f5658 | |||
| d54fe15511 | |||
| baa4deda99 | |||
| b7417e77c7 | |||
| a01bb551d0 | |||
| 9a03bdeaf1 | |||
| 6b530ff764 | |||
| e77a3241f0 | |||
| a718ff2617 | |||
| 969fa82b7f | |||
| bb47a70310 | |||
| a306cecb73 | |||
| 760879c3db | |||
| ef5d3580e8 |
36
.bumpversion.cfg
Normal file
36
.bumpversion.cfg
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
[bumpversion]
|
||||||
|
current_version = 2025.6.1
|
||||||
|
tag = True
|
||||||
|
commit = True
|
||||||
|
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<rc_t>[a-zA-Z-]+)(?P<rc_n>[1-9]\\d*))?
|
||||||
|
serialize =
|
||||||
|
{major}.{minor}.{patch}-{rc_t}{rc_n}
|
||||||
|
{major}.{minor}.{patch}
|
||||||
|
message = release: {new_version}
|
||||||
|
tag_name = version/{new_version}
|
||||||
|
|
||||||
|
[bumpversion:part:rc_t]
|
||||||
|
values =
|
||||||
|
rc
|
||||||
|
final
|
||||||
|
optional_value = final
|
||||||
|
|
||||||
|
[bumpversion:file:pyproject.toml]
|
||||||
|
|
||||||
|
[bumpversion:file:uv.lock]
|
||||||
|
|
||||||
|
[bumpversion:file:package.json]
|
||||||
|
|
||||||
|
[bumpversion:file:docker-compose.yml]
|
||||||
|
|
||||||
|
[bumpversion:file:schema.yml]
|
||||||
|
|
||||||
|
[bumpversion:file:blueprints/schema.json]
|
||||||
|
|
||||||
|
[bumpversion:file:authentik/__init__.py]
|
||||||
|
|
||||||
|
[bumpversion:file:internal/constants/constants.go]
|
||||||
|
|
||||||
|
[bumpversion:file:web/src/common/constants.ts]
|
||||||
|
|
||||||
|
[bumpversion:file:lifecycle/aws/template.yaml]
|
||||||
@ -5,8 +5,10 @@ dist/**
|
|||||||
build/**
|
build/**
|
||||||
build_docs/**
|
build_docs/**
|
||||||
*Dockerfile
|
*Dockerfile
|
||||||
|
**/*Dockerfile
|
||||||
blueprints/local
|
blueprints/local
|
||||||
.git
|
.git
|
||||||
!gen-ts-api/node_modules
|
!gen-ts-api/node_modules
|
||||||
!gen-ts-api/dist/**
|
!gen-ts-api/dist/**
|
||||||
!gen-go-api/
|
!gen-go-api/
|
||||||
|
.venv
|
||||||
|
|||||||
@ -1,9 +1,13 @@
|
|||||||
"""Helper script to get the actual branch name, docker safe"""
|
"""Helper script to get the actual branch name, docker safe"""
|
||||||
|
|
||||||
|
import configparser
|
||||||
import os
|
import os
|
||||||
from importlib.metadata import version as package_version
|
|
||||||
from json import dumps
|
from json import dumps
|
||||||
from time import time
|
from time import time
|
||||||
|
|
||||||
|
parser = configparser.ConfigParser()
|
||||||
|
parser.read(".bumpversion.cfg")
|
||||||
|
|
||||||
# Decide if we should push the image or not
|
# Decide if we should push the image or not
|
||||||
should_push = True
|
should_push = True
|
||||||
if len(os.environ.get("DOCKER_USERNAME", "")) < 1:
|
if len(os.environ.get("DOCKER_USERNAME", "")) < 1:
|
||||||
@ -27,7 +31,7 @@ is_release = "dev" not in image_names[0]
|
|||||||
sha = os.environ["GITHUB_SHA"] if not is_pull_request else os.getenv("PR_HEAD_SHA")
|
sha = os.environ["GITHUB_SHA"] if not is_pull_request else os.getenv("PR_HEAD_SHA")
|
||||||
|
|
||||||
# 2042.1.0 or 2042.1.0-rc1
|
# 2042.1.0 or 2042.1.0-rc1
|
||||||
version = package_version("authentik")
|
version = parser.get("bumpversion", "current_version")
|
||||||
# 2042.1
|
# 2042.1
|
||||||
version_family = ".".join(version.split("-", 1)[0].split(".")[:-1])
|
version_family = ".".join(version.split("-", 1)[0].split(".")[:-1])
|
||||||
prerelease = "-" in version
|
prerelease = "-" in version
|
||||||
|
|||||||
7
.github/dependabot.yml
vendored
7
.github/dependabot.yml
vendored
@ -100,6 +100,13 @@ updates:
|
|||||||
goauthentik:
|
goauthentik:
|
||||||
patterns:
|
patterns:
|
||||||
- "@goauthentik/*"
|
- "@goauthentik/*"
|
||||||
|
eslint:
|
||||||
|
patterns:
|
||||||
|
- "@eslint/*"
|
||||||
|
- "@typescript-eslint/*"
|
||||||
|
- "eslint-*"
|
||||||
|
- "eslint"
|
||||||
|
- "typescript-eslint"
|
||||||
- package-ecosystem: npm
|
- package-ecosystem: npm
|
||||||
directory: "/lifecycle/aws"
|
directory: "/lifecycle/aws"
|
||||||
schedule:
|
schedule:
|
||||||
|
|||||||
62
.github/workflows/ci-website.yml
vendored
62
.github/workflows/ci-website.yml
vendored
@ -41,32 +41,60 @@ jobs:
|
|||||||
- name: test
|
- name: test
|
||||||
working-directory: website/
|
working-directory: website/
|
||||||
run: npm test
|
run: npm test
|
||||||
build:
|
build-container:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
name: ${{ matrix.job }}
|
permissions:
|
||||||
strategy:
|
# Needed to upload container images to ghcr.io
|
||||||
fail-fast: false
|
packages: write
|
||||||
matrix:
|
# Needed for attestation
|
||||||
job:
|
id-token: write
|
||||||
- build
|
attestations: write
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
with:
|
||||||
node-version-file: website/package.json
|
ref: ${{ github.event.pull_request.head.sha }}
|
||||||
cache: "npm"
|
- name: Set up QEMU
|
||||||
cache-dependency-path: website/package-lock.json
|
uses: docker/setup-qemu-action@v3.6.0
|
||||||
- working-directory: website/
|
- name: Set up Docker Buildx
|
||||||
run: npm ci
|
uses: docker/setup-buildx-action@v3
|
||||||
- name: build
|
- name: prepare variables
|
||||||
working-directory: website/
|
uses: ./.github/actions/docker-push-variables
|
||||||
run: npm run ${{ matrix.job }}
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
with:
|
||||||
|
image-name: ghcr.io/goauthentik/dev-docs
|
||||||
|
- name: Login to Container Registry
|
||||||
|
if: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Build Docker Image
|
||||||
|
id: push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
|
file: website/Dockerfile
|
||||||
|
push: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
context: .
|
||||||
|
cache-from: type=registry,ref=ghcr.io/goauthentik/dev-docs:buildcache
|
||||||
|
cache-to: ${{ steps.ev.outputs.shouldPush == 'true' && 'type=registry,ref=ghcr.io/goauthentik/dev-docs:buildcache,mode=max' || '' }}
|
||||||
|
- uses: actions/attest-build-provenance@v2
|
||||||
|
id: attest
|
||||||
|
if: ${{ steps.ev.outputs.shouldPush == 'true' }}
|
||||||
|
with:
|
||||||
|
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
||||||
|
subject-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
push-to-registry: true
|
||||||
ci-website-mark:
|
ci-website-mark:
|
||||||
if: always()
|
if: always()
|
||||||
needs:
|
needs:
|
||||||
- lint
|
- lint
|
||||||
- test
|
- test
|
||||||
- build
|
- build-container
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: re-actors/alls-green@release/v1
|
- uses: re-actors/alls-green@release/v1
|
||||||
|
|||||||
45
.github/workflows/release-publish.yml
vendored
45
.github/workflows/release-publish.yml
vendored
@ -20,6 +20,49 @@ jobs:
|
|||||||
release: true
|
release: true
|
||||||
registry_dockerhub: true
|
registry_dockerhub: true
|
||||||
registry_ghcr: true
|
registry_ghcr: true
|
||||||
|
build-docs:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
# Needed to upload container images to ghcr.io
|
||||||
|
packages: write
|
||||||
|
# Needed for attestation
|
||||||
|
id-token: write
|
||||||
|
attestations: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3.6.0
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
- name: prepare variables
|
||||||
|
uses: ./.github/actions/docker-push-variables
|
||||||
|
id: ev
|
||||||
|
env:
|
||||||
|
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
|
||||||
|
with:
|
||||||
|
image-name: ghcr.io/goauthentik/docs
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Build Docker Image
|
||||||
|
id: push
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
tags: ${{ steps.ev.outputs.imageTags }}
|
||||||
|
file: website/Dockerfile
|
||||||
|
push: true
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
context: .
|
||||||
|
- uses: actions/attest-build-provenance@v2
|
||||||
|
id: attest
|
||||||
|
if: true
|
||||||
|
with:
|
||||||
|
subject-name: ${{ steps.ev.outputs.attestImageNames }}
|
||||||
|
subject-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
push-to-registry: true
|
||||||
build-outpost:
|
build-outpost:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
@ -193,6 +236,6 @@ jobs:
|
|||||||
SENTRY_ORG: authentik-security-inc
|
SENTRY_ORG: authentik-security-inc
|
||||||
SENTRY_PROJECT: authentik
|
SENTRY_PROJECT: authentik
|
||||||
with:
|
with:
|
||||||
version: authentik@${{ steps.ev.outputs.version }}
|
release: authentik@${{ steps.ev.outputs.version }}
|
||||||
sourcemaps: "./web/dist"
|
sourcemaps: "./web/dist"
|
||||||
url_prefix: "~/static/dist"
|
url_prefix: "~/static/dist"
|
||||||
|
|||||||
50
Dockerfile
50
Dockerfile
@ -1,26 +1,7 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
# Stage 1: Build website
|
# Stage 1: Build webui
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/library/node:24 AS website-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/library/node:24-slim AS node-builder
|
||||||
|
|
||||||
ENV NODE_ENV=production
|
|
||||||
|
|
||||||
WORKDIR /work/website
|
|
||||||
|
|
||||||
RUN --mount=type=bind,target=/work/website/package.json,src=./website/package.json \
|
|
||||||
--mount=type=bind,target=/work/website/package-lock.json,src=./website/package-lock.json \
|
|
||||||
--mount=type=cache,id=npm-website,sharing=shared,target=/root/.npm \
|
|
||||||
npm ci --include=dev
|
|
||||||
|
|
||||||
COPY ./website /work/website/
|
|
||||||
COPY ./blueprints /work/blueprints/
|
|
||||||
COPY ./schema.yml /work/
|
|
||||||
COPY ./SECURITY.md /work/
|
|
||||||
|
|
||||||
RUN npm run build-bundled
|
|
||||||
|
|
||||||
# Stage 2: Build webui
|
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/library/node:24 AS web-builder
|
|
||||||
|
|
||||||
ARG GIT_BUILD_HASH
|
ARG GIT_BUILD_HASH
|
||||||
ENV GIT_BUILD_HASH=$GIT_BUILD_HASH
|
ENV GIT_BUILD_HASH=$GIT_BUILD_HASH
|
||||||
@ -32,7 +13,7 @@ RUN --mount=type=bind,target=/work/web/package.json,src=./web/package.json \
|
|||||||
--mount=type=bind,target=/work/web/package-lock.json,src=./web/package-lock.json \
|
--mount=type=bind,target=/work/web/package-lock.json,src=./web/package-lock.json \
|
||||||
--mount=type=bind,target=/work/web/packages/sfe/package.json,src=./web/packages/sfe/package.json \
|
--mount=type=bind,target=/work/web/packages/sfe/package.json,src=./web/packages/sfe/package.json \
|
||||||
--mount=type=bind,target=/work/web/scripts,src=./web/scripts \
|
--mount=type=bind,target=/work/web/scripts,src=./web/scripts \
|
||||||
--mount=type=cache,id=npm-web,sharing=shared,target=/root/.npm \
|
--mount=type=cache,id=npm-ak,sharing=shared,target=/root/.npm \
|
||||||
npm ci --include=dev
|
npm ci --include=dev
|
||||||
|
|
||||||
COPY ./package.json /work
|
COPY ./package.json /work
|
||||||
@ -43,7 +24,7 @@ COPY ./gen-ts-api /work/web/node_modules/@goauthentik/api
|
|||||||
RUN npm run build && \
|
RUN npm run build && \
|
||||||
npm run build:sfe
|
npm run build:sfe
|
||||||
|
|
||||||
# Stage 3: Build go proxy
|
# Stage 2: Build go proxy
|
||||||
FROM --platform=${BUILDPLATFORM} docker.io/library/golang:1.24-bookworm AS go-builder
|
FROM --platform=${BUILDPLATFORM} docker.io/library/golang:1.24-bookworm AS go-builder
|
||||||
|
|
||||||
ARG TARGETOS
|
ARG TARGETOS
|
||||||
@ -68,8 +49,8 @@ RUN --mount=type=bind,target=/go/src/goauthentik.io/go.mod,src=./go.mod \
|
|||||||
COPY ./cmd /go/src/goauthentik.io/cmd
|
COPY ./cmd /go/src/goauthentik.io/cmd
|
||||||
COPY ./authentik/lib /go/src/goauthentik.io/authentik/lib
|
COPY ./authentik/lib /go/src/goauthentik.io/authentik/lib
|
||||||
COPY ./web/static.go /go/src/goauthentik.io/web/static.go
|
COPY ./web/static.go /go/src/goauthentik.io/web/static.go
|
||||||
COPY --from=web-builder /work/web/robots.txt /go/src/goauthentik.io/web/robots.txt
|
COPY --from=node-builder /work/web/robots.txt /go/src/goauthentik.io/web/robots.txt
|
||||||
COPY --from=web-builder /work/web/security.txt /go/src/goauthentik.io/web/security.txt
|
COPY --from=node-builder /work/web/security.txt /go/src/goauthentik.io/web/security.txt
|
||||||
COPY ./internal /go/src/goauthentik.io/internal
|
COPY ./internal /go/src/goauthentik.io/internal
|
||||||
COPY ./go.mod /go/src/goauthentik.io/go.mod
|
COPY ./go.mod /go/src/goauthentik.io/go.mod
|
||||||
COPY ./go.sum /go/src/goauthentik.io/go.sum
|
COPY ./go.sum /go/src/goauthentik.io/go.sum
|
||||||
@ -80,7 +61,7 @@ RUN --mount=type=cache,sharing=locked,target=/go/pkg/mod \
|
|||||||
CGO_ENABLED=1 GOFIPS140=latest GOARM="${TARGETVARIANT#v}" \
|
CGO_ENABLED=1 GOFIPS140=latest GOARM="${TARGETVARIANT#v}" \
|
||||||
go build -o /go/authentik ./cmd/server
|
go build -o /go/authentik ./cmd/server
|
||||||
|
|
||||||
# Stage 4: MaxMind GeoIP
|
# Stage 3: MaxMind GeoIP
|
||||||
FROM --platform=${BUILDPLATFORM} ghcr.io/maxmind/geoipupdate:v7.1.0 AS geoip
|
FROM --platform=${BUILDPLATFORM} ghcr.io/maxmind/geoipupdate:v7.1.0 AS geoip
|
||||||
|
|
||||||
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City GeoLite2-ASN"
|
ENV GEOIPUPDATE_EDITION_IDS="GeoLite2-City GeoLite2-ASN"
|
||||||
@ -93,10 +74,10 @@ RUN --mount=type=secret,id=GEOIPUPDATE_ACCOUNT_ID \
|
|||||||
mkdir -p /usr/share/GeoIP && \
|
mkdir -p /usr/share/GeoIP && \
|
||||||
/bin/sh -c "GEOIPUPDATE_LICENSE_KEY_FILE=/run/secrets/GEOIPUPDATE_LICENSE_KEY /usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
/bin/sh -c "GEOIPUPDATE_LICENSE_KEY_FILE=/run/secrets/GEOIPUPDATE_LICENSE_KEY /usr/bin/entry.sh || echo 'Failed to get GeoIP database, disabling'; exit 0"
|
||||||
|
|
||||||
# Stage 5: Download uv
|
# Stage 4: Download uv
|
||||||
FROM ghcr.io/astral-sh/uv:0.7.11 AS uv
|
FROM ghcr.io/astral-sh/uv:0.7.13 AS uv
|
||||||
# Stage 6: Base python image
|
# Stage 5: Base python image
|
||||||
FROM ghcr.io/goauthentik/fips-python:3.13.3-slim-bookworm-fips AS python-base
|
FROM ghcr.io/goauthentik/fips-python:3.13.4-slim-bookworm-fips AS python-base
|
||||||
|
|
||||||
ENV VENV_PATH="/ak-root/.venv" \
|
ENV VENV_PATH="/ak-root/.venv" \
|
||||||
PATH="/lifecycle:/ak-root/.venv/bin:$PATH" \
|
PATH="/lifecycle:/ak-root/.venv/bin:$PATH" \
|
||||||
@ -109,7 +90,7 @@ WORKDIR /ak-root/
|
|||||||
|
|
||||||
COPY --from=uv /uv /uvx /bin/
|
COPY --from=uv /uv /uvx /bin/
|
||||||
|
|
||||||
# Stage 7: Python dependencies
|
# Stage 6: Python dependencies
|
||||||
FROM python-base AS python-deps
|
FROM python-base AS python-deps
|
||||||
|
|
||||||
ARG TARGETARCH
|
ARG TARGETARCH
|
||||||
@ -144,7 +125,7 @@ RUN --mount=type=bind,target=pyproject.toml,src=pyproject.toml \
|
|||||||
--mount=type=cache,target=/root/.cache/uv \
|
--mount=type=cache,target=/root/.cache/uv \
|
||||||
uv sync --frozen --no-install-project --no-dev
|
uv sync --frozen --no-install-project --no-dev
|
||||||
|
|
||||||
# Stage 8: Run
|
# Stage 7: Run
|
||||||
FROM python-base AS final-image
|
FROM python-base AS final-image
|
||||||
|
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
@ -187,9 +168,8 @@ COPY ./lifecycle/ /lifecycle
|
|||||||
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
|
COPY ./authentik/sources/kerberos/krb5.conf /etc/krb5.conf
|
||||||
COPY --from=go-builder /go/authentik /bin/authentik
|
COPY --from=go-builder /go/authentik /bin/authentik
|
||||||
COPY --from=python-deps /ak-root/.venv /ak-root/.venv
|
COPY --from=python-deps /ak-root/.venv /ak-root/.venv
|
||||||
COPY --from=web-builder /work/web/dist/ /web/dist/
|
COPY --from=node-builder /work/web/dist/ /web/dist/
|
||||||
COPY --from=web-builder /work/web/authentik/ /web/authentik/
|
COPY --from=node-builder /work/web/authentik/ /web/authentik/
|
||||||
COPY --from=website-builder /work/website/build/ /website/help/
|
|
||||||
COPY --from=geoip /usr/share/GeoIP /geoip
|
COPY --from=geoip /usr/share/GeoIP /geoip
|
||||||
|
|
||||||
USER 1000
|
USER 1000
|
||||||
|
|||||||
16
Makefile
16
Makefile
@ -57,7 +57,7 @@ migrate: ## Run the Authentik Django server's migrations
|
|||||||
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
|
i18n-extract: core-i18n-extract web-i18n-extract ## Extract strings that require translation into files to send to a translation service
|
||||||
|
|
||||||
aws-cfn:
|
aws-cfn:
|
||||||
cd lifecycle/aws && npm i && npm run aws-cfn
|
cd lifecycle/aws && npm run aws-cfn
|
||||||
|
|
||||||
run: ## Run the main authentik server process
|
run: ## Run the main authentik server process
|
||||||
uv run ak server
|
uv run ak server
|
||||||
@ -86,15 +86,6 @@ dev-create-db:
|
|||||||
|
|
||||||
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
|
dev-reset: dev-drop-db dev-create-db migrate ## Drop and restore the Authentik PostgreSQL instance to a "fresh install" state.
|
||||||
|
|
||||||
bump:
|
|
||||||
uv version $(version)
|
|
||||||
$(MAKE) gen-build
|
|
||||||
$(MAKE) gen-compose
|
|
||||||
$(MAKE) aws-cfn
|
|
||||||
npm version --no-git-tag-version --allow-same-version $(version)
|
|
||||||
cd ${PWD}/web && npm version --no-git-tag-version --allow-same-version $(version)
|
|
||||||
echo $(version) > ${PWD}/internal/constants/VERSION
|
|
||||||
|
|
||||||
#########################
|
#########################
|
||||||
## API Schema
|
## API Schema
|
||||||
#########################
|
#########################
|
||||||
@ -103,15 +94,12 @@ gen-build: ## Extract the schema from the database
|
|||||||
AUTHENTIK_DEBUG=true \
|
AUTHENTIK_DEBUG=true \
|
||||||
AUTHENTIK_TENANTS__ENABLED=true \
|
AUTHENTIK_TENANTS__ENABLED=true \
|
||||||
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
|
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
|
||||||
uv run ak make_blueprint_schema > blueprints/schema.json
|
uv run ak make_blueprint_schema --file blueprints/schema.json
|
||||||
AUTHENTIK_DEBUG=true \
|
AUTHENTIK_DEBUG=true \
|
||||||
AUTHENTIK_TENANTS__ENABLED=true \
|
AUTHENTIK_TENANTS__ENABLED=true \
|
||||||
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
|
AUTHENTIK_OUTPOSTS__DISABLE_EMBEDDED_OUTPOST=true \
|
||||||
uv run ak spectacular --file schema.yml
|
uv run ak spectacular --file schema.yml
|
||||||
|
|
||||||
gen-compose:
|
|
||||||
uv run scripts/generate_docker_compose.py
|
|
||||||
|
|
||||||
gen-changelog: ## (Release) generate the changelog based from the commits since the last tag
|
gen-changelog: ## (Release) generate the changelog based from the commits since the last tag
|
||||||
git log --pretty=format:" - %s" $(shell git describe --tags $(shell git rev-list --tags --max-count=1))...$(shell git branch --show-current) | sort > changelog.md
|
git log --pretty=format:" - %s" $(shell git describe --tags $(shell git rev-list --tags --max-count=1))...$(shell git branch --show-current) | sort > changelog.md
|
||||||
npx prettier --write changelog.md
|
npx prettier --write changelog.md
|
||||||
|
|||||||
@ -1,28 +1,20 @@
|
|||||||
"""authentik root module"""
|
"""authentik root module"""
|
||||||
|
|
||||||
from functools import lru_cache
|
|
||||||
from importlib.metadata import version
|
|
||||||
from os import environ
|
from os import environ
|
||||||
|
|
||||||
|
__version__ = "2025.6.1"
|
||||||
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
ENV_GIT_HASH_KEY = "GIT_BUILD_HASH"
|
||||||
|
|
||||||
|
|
||||||
@lru_cache
|
def get_build_hash(fallback: str | None = None) -> str:
|
||||||
def authentik_version() -> str:
|
|
||||||
return version("authentik")
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache
|
|
||||||
def authentik_build_hash(fallback: str | None = None) -> str:
|
|
||||||
"""Get build hash"""
|
"""Get build hash"""
|
||||||
build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "")
|
build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "")
|
||||||
return fallback if build_hash == "" and fallback else build_hash
|
return fallback if build_hash == "" and fallback else build_hash
|
||||||
|
|
||||||
|
|
||||||
@lru_cache
|
def get_full_version() -> str:
|
||||||
def authentik_full_version() -> str:
|
|
||||||
"""Get full version, with build hash appended"""
|
"""Get full version, with build hash appended"""
|
||||||
version = authentik_version()
|
version = __version__
|
||||||
if (build_hash := authentik_build_hash()) != "":
|
if (build_hash := get_build_hash()) != "":
|
||||||
return f"{version}+{build_hash}"
|
return f"{version}+{build_hash}"
|
||||||
return version
|
return version
|
||||||
|
|||||||
@ -1,79 +0,0 @@
|
|||||||
"""authentik administration metrics"""
|
|
||||||
|
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
from django.db.models.functions import ExtractHour
|
|
||||||
from drf_spectacular.utils import extend_schema, extend_schema_field
|
|
||||||
from guardian.shortcuts import get_objects_for_user
|
|
||||||
from rest_framework.fields import IntegerField, SerializerMethodField
|
|
||||||
from rest_framework.permissions import IsAuthenticated
|
|
||||||
from rest_framework.request import Request
|
|
||||||
from rest_framework.response import Response
|
|
||||||
from rest_framework.views import APIView
|
|
||||||
|
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
|
||||||
from authentik.events.models import EventAction
|
|
||||||
|
|
||||||
|
|
||||||
class CoordinateSerializer(PassiveSerializer):
|
|
||||||
"""Coordinates for diagrams"""
|
|
||||||
|
|
||||||
x_cord = IntegerField(read_only=True)
|
|
||||||
y_cord = IntegerField(read_only=True)
|
|
||||||
|
|
||||||
|
|
||||||
class LoginMetricsSerializer(PassiveSerializer):
|
|
||||||
"""Login Metrics per 1h"""
|
|
||||||
|
|
||||||
logins = SerializerMethodField()
|
|
||||||
logins_failed = SerializerMethodField()
|
|
||||||
authorizations = SerializerMethodField()
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_logins(self, _):
|
|
||||||
"""Get successful logins per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.LOGIN
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_logins_failed(self, _):
|
|
||||||
"""Get failed logins per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.LOGIN_FAILED
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_authorizations(self, _):
|
|
||||||
"""Get successful authorizations per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.AUTHORIZE_APPLICATION
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class AdministrationMetricsViewSet(APIView):
|
|
||||||
"""Login Metrics per 1h"""
|
|
||||||
|
|
||||||
permission_classes = [IsAuthenticated]
|
|
||||||
|
|
||||||
@extend_schema(responses={200: LoginMetricsSerializer(many=False)})
|
|
||||||
def get(self, request: Request) -> Response:
|
|
||||||
"""Login Metrics per 1h"""
|
|
||||||
serializer = LoginMetricsSerializer(True)
|
|
||||||
serializer.context["user"] = request.user
|
|
||||||
return Response(serializer.data)
|
|
||||||
@ -16,7 +16,7 @@ from rest_framework.request import Request
|
|||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
from authentik.enterprise.license import LicenseKey
|
from authentik.enterprise.license import LicenseKey
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
@ -78,7 +78,7 @@ class SystemInfoSerializer(PassiveSerializer):
|
|||||||
"""Get versions"""
|
"""Get versions"""
|
||||||
return {
|
return {
|
||||||
"architecture": platform.machine(),
|
"architecture": platform.machine(),
|
||||||
"authentik_version": authentik_full_version(),
|
"authentik_version": get_full_version(),
|
||||||
"environment": get_env(),
|
"environment": get_env(),
|
||||||
"openssl_fips_enabled": (
|
"openssl_fips_enabled": (
|
||||||
backend._fips_enabled if LicenseKey.get_total().status().is_valid else None
|
backend._fips_enabled if LicenseKey.get_total().status().is_valid else None
|
||||||
|
|||||||
@ -10,7 +10,7 @@ from rest_framework.request import Request
|
|||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
from authentik import authentik_build_hash, authentik_version
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.admin.tasks import VERSION_CACHE_KEY, VERSION_NULL, update_latest_version
|
from authentik.admin.tasks import VERSION_CACHE_KEY, VERSION_NULL, update_latest_version
|
||||||
from authentik.core.api.utils import PassiveSerializer
|
from authentik.core.api.utils import PassiveSerializer
|
||||||
from authentik.outposts.models import Outpost
|
from authentik.outposts.models import Outpost
|
||||||
@ -29,11 +29,11 @@ class VersionSerializer(PassiveSerializer):
|
|||||||
|
|
||||||
def get_build_hash(self, _) -> str:
|
def get_build_hash(self, _) -> str:
|
||||||
"""Get build hash, if version is not latest or released"""
|
"""Get build hash, if version is not latest or released"""
|
||||||
return authentik_build_hash()
|
return get_build_hash()
|
||||||
|
|
||||||
def get_version_current(self, _) -> str:
|
def get_version_current(self, _) -> str:
|
||||||
"""Get current version"""
|
"""Get current version"""
|
||||||
return authentik_version()
|
return __version__
|
||||||
|
|
||||||
def get_version_latest(self, _) -> str:
|
def get_version_latest(self, _) -> str:
|
||||||
"""Get latest version from cache"""
|
"""Get latest version from cache"""
|
||||||
@ -42,7 +42,7 @@ class VersionSerializer(PassiveSerializer):
|
|||||||
version_in_cache = cache.get(VERSION_CACHE_KEY)
|
version_in_cache = cache.get(VERSION_CACHE_KEY)
|
||||||
if not version_in_cache: # pragma: no cover
|
if not version_in_cache: # pragma: no cover
|
||||||
update_latest_version.delay()
|
update_latest_version.delay()
|
||||||
return authentik_version()
|
return __version__
|
||||||
return version_in_cache
|
return version_in_cache
|
||||||
|
|
||||||
def get_version_latest_valid(self, _) -> bool:
|
def get_version_latest_valid(self, _) -> bool:
|
||||||
|
|||||||
@ -10,7 +10,7 @@ from rest_framework.request import Request
|
|||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.views import APIView
|
from rest_framework.views import APIView
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.rbac.permissions import HasPermission
|
from authentik.rbac.permissions import HasPermission
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
|
|
||||||
@ -34,7 +34,7 @@ class WorkerView(APIView):
|
|||||||
def get(self, request: Request) -> Response:
|
def get(self, request: Request) -> Response:
|
||||||
"""Get currently connected worker count."""
|
"""Get currently connected worker count."""
|
||||||
raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
|
raw: list[dict[str, dict]] = CELERY_APP.control.ping(timeout=0.5)
|
||||||
our_version = parse(authentik_full_version())
|
our_version = parse(get_full_version())
|
||||||
response = []
|
response = []
|
||||||
for worker in raw:
|
for worker in raw:
|
||||||
key = list(worker.keys())[0]
|
key = list(worker.keys())[0]
|
||||||
@ -50,7 +50,7 @@ class WorkerView(APIView):
|
|||||||
response.append(
|
response.append(
|
||||||
{
|
{
|
||||||
"worker_id": f"authentik-debug@{gethostname()}",
|
"worker_id": f"authentik-debug@{gethostname()}",
|
||||||
"version": authentik_full_version(),
|
"version": get_full_version(),
|
||||||
"version_matching": True,
|
"version_matching": True,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|||||||
@ -4,7 +4,7 @@ from django.dispatch import receiver
|
|||||||
from packaging.version import parse
|
from packaging.version import parse
|
||||||
from prometheus_client import Gauge
|
from prometheus_client import Gauge
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.root.celery import CELERY_APP
|
from authentik.root.celery import CELERY_APP
|
||||||
from authentik.root.monitoring import monitoring_set
|
from authentik.root.monitoring import monitoring_set
|
||||||
|
|
||||||
@ -15,7 +15,7 @@ GAUGE_WORKERS = Gauge(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
_version = parse(authentik_full_version())
|
_version = parse(get_full_version())
|
||||||
|
|
||||||
|
|
||||||
@receiver(monitoring_set)
|
@receiver(monitoring_set)
|
||||||
|
|||||||
@ -6,7 +6,7 @@ from packaging.version import parse
|
|||||||
from requests import RequestException
|
from requests import RequestException
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_build_hash, authentik_version
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.admin.apps import PROM_INFO
|
from authentik.admin.apps import PROM_INFO
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
|
from authentik.events.system_tasks import SystemTask, TaskStatus, prefill_task
|
||||||
@ -18,16 +18,16 @@ LOGGER = get_logger()
|
|||||||
VERSION_NULL = "0.0.0"
|
VERSION_NULL = "0.0.0"
|
||||||
VERSION_CACHE_KEY = "authentik_latest_version"
|
VERSION_CACHE_KEY = "authentik_latest_version"
|
||||||
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
|
VERSION_CACHE_TIMEOUT = 8 * 60 * 60 # 8 hours
|
||||||
LOCAL_VERSION = parse(authentik_version())
|
LOCAL_VERSION = parse(__version__)
|
||||||
|
|
||||||
|
|
||||||
def _set_prom_info():
|
def _set_prom_info():
|
||||||
"""Set prometheus info for version"""
|
"""Set prometheus info for version"""
|
||||||
PROM_INFO.info(
|
PROM_INFO.info(
|
||||||
{
|
{
|
||||||
"version": authentik_version(),
|
"version": __version__,
|
||||||
"latest": cache.get(VERSION_CACHE_KEY, ""),
|
"latest": cache.get(VERSION_CACHE_KEY, ""),
|
||||||
"build_hash": authentik_build_hash(),
|
"build_hash": get_build_hash(),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@ from json import loads
|
|||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.blueprints.tests import reconcile_app
|
from authentik.blueprints.tests import reconcile_app
|
||||||
from authentik.core.models import Group, User
|
from authentik.core.models import Group, User
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
@ -27,7 +27,7 @@ class TestAdminAPI(TestCase):
|
|||||||
response = self.client.get(reverse("authentik_api:admin_version"))
|
response = self.client.get(reverse("authentik_api:admin_version"))
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
body = loads(response.content)
|
body = loads(response.content)
|
||||||
self.assertEqual(body["version_current"], authentik_version())
|
self.assertEqual(body["version_current"], __version__)
|
||||||
|
|
||||||
def test_workers(self):
|
def test_workers(self):
|
||||||
"""Test Workers API"""
|
"""Test Workers API"""
|
||||||
@ -36,11 +36,6 @@ class TestAdminAPI(TestCase):
|
|||||||
body = loads(response.content)
|
body = loads(response.content)
|
||||||
self.assertEqual(len(body), 0)
|
self.assertEqual(len(body), 0)
|
||||||
|
|
||||||
def test_metrics(self):
|
|
||||||
"""Test metrics API"""
|
|
||||||
response = self.client.get(reverse("authentik_api:admin_metrics"))
|
|
||||||
self.assertEqual(response.status_code, 200)
|
|
||||||
|
|
||||||
def test_apps(self):
|
def test_apps(self):
|
||||||
"""Test apps API"""
|
"""Test apps API"""
|
||||||
response = self.client.get(reverse("authentik_api:apps-list"))
|
response = self.client.get(reverse("authentik_api:apps-list"))
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
from authentik.admin.api.meta import AppsViewSet, ModelViewSet
|
from authentik.admin.api.meta import AppsViewSet, ModelViewSet
|
||||||
from authentik.admin.api.metrics import AdministrationMetricsViewSet
|
|
||||||
from authentik.admin.api.system import SystemView
|
from authentik.admin.api.system import SystemView
|
||||||
from authentik.admin.api.version import VersionView
|
from authentik.admin.api.version import VersionView
|
||||||
from authentik.admin.api.version_history import VersionHistoryViewSet
|
from authentik.admin.api.version_history import VersionHistoryViewSet
|
||||||
@ -12,11 +11,6 @@ from authentik.admin.api.workers import WorkerView
|
|||||||
api_urlpatterns = [
|
api_urlpatterns = [
|
||||||
("admin/apps", AppsViewSet, "apps"),
|
("admin/apps", AppsViewSet, "apps"),
|
||||||
("admin/models", ModelViewSet, "models"),
|
("admin/models", ModelViewSet, "models"),
|
||||||
path(
|
|
||||||
"admin/metrics/",
|
|
||||||
AdministrationMetricsViewSet.as_view(),
|
|
||||||
name="admin_metrics",
|
|
||||||
),
|
|
||||||
path("admin/version/", VersionView.as_view(), name="admin_version"),
|
path("admin/version/", VersionView.as_view(), name="admin_version"),
|
||||||
("admin/version/history", VersionHistoryViewSet, "version_history"),
|
("admin/version/history", VersionHistoryViewSet, "version_history"),
|
||||||
path("admin/workers/", WorkerView.as_view(), name="admin_workers"),
|
path("admin/workers/", WorkerView.as_view(), name="admin_workers"),
|
||||||
|
|||||||
@ -11,7 +11,7 @@ from rest_framework.relations import PrimaryKeyRelatedField
|
|||||||
from rest_framework.serializers import Serializer
|
from rest_framework.serializers import Serializer
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.blueprints.v1.common import BlueprintEntryDesiredState
|
from authentik.blueprints.v1.common import BlueprintEntryDesiredState
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, is_model_allowed
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT, is_model_allowed
|
||||||
from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
|
from authentik.blueprints.v1.meta.registry import BaseMetaModel, registry
|
||||||
@ -48,7 +48,7 @@ class Command(BaseCommand):
|
|||||||
"$schema": "http://json-schema.org/draft-07/schema",
|
"$schema": "http://json-schema.org/draft-07/schema",
|
||||||
"$id": "https://goauthentik.io/blueprints/schema.json",
|
"$id": "https://goauthentik.io/blueprints/schema.json",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"title": f"authentik {authentik_version()} Blueprint schema",
|
"title": f"authentik {__version__} Blueprint schema",
|
||||||
"required": ["version", "entries"],
|
"required": ["version", "entries"],
|
||||||
"properties": {
|
"properties": {
|
||||||
"version": {
|
"version": {
|
||||||
@ -72,20 +72,33 @@ class Command(BaseCommand):
|
|||||||
"additionalProperties": True,
|
"additionalProperties": True,
|
||||||
},
|
},
|
||||||
"entries": {
|
"entries": {
|
||||||
"type": "array",
|
"anyOf": [
|
||||||
"items": {
|
{
|
||||||
"oneOf": [],
|
"type": "array",
|
||||||
},
|
"items": {"$ref": "#/$defs/blueprint_entry"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {"$ref": "#/$defs/blueprint_entry"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"$defs": {},
|
"$defs": {"blueprint_entry": {"oneOf": []}},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument("--file", type=str)
|
||||||
|
|
||||||
@no_translations
|
@no_translations
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, file: str, **options):
|
||||||
"""Generate JSON Schema for blueprints"""
|
"""Generate JSON Schema for blueprints"""
|
||||||
self.build()
|
self.build()
|
||||||
self.stdout.write(dumps(self.schema, indent=4, default=Command.json_default))
|
with open(file, "w") as _schema:
|
||||||
|
_schema.write(dumps(self.schema, indent=4, default=Command.json_default))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def json_default(value: Any) -> Any:
|
def json_default(value: Any) -> Any:
|
||||||
@ -112,7 +125,7 @@ class Command(BaseCommand):
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
model_path = f"{model._meta.app_label}.{model._meta.model_name}"
|
model_path = f"{model._meta.app_label}.{model._meta.model_name}"
|
||||||
self.schema["properties"]["entries"]["items"]["oneOf"].append(
|
self.schema["$defs"]["blueprint_entry"]["oneOf"].append(
|
||||||
self.template_entry(model_path, model, serializer)
|
self.template_entry(model_path, model, serializer)
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -134,7 +147,7 @@ class Command(BaseCommand):
|
|||||||
"id": {"type": "string"},
|
"id": {"type": "string"},
|
||||||
"state": {
|
"state": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": [s.value for s in BlueprintEntryDesiredState],
|
"enum": sorted([s.value for s in BlueprintEntryDesiredState]),
|
||||||
"default": "present",
|
"default": "present",
|
||||||
},
|
},
|
||||||
"conditions": {"type": "array", "items": {"type": "boolean"}},
|
"conditions": {"type": "array", "items": {"type": "boolean"}},
|
||||||
@ -205,7 +218,7 @@ class Command(BaseCommand):
|
|||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["permission"],
|
"required": ["permission"],
|
||||||
"properties": {
|
"properties": {
|
||||||
"permission": {"type": "string", "enum": perms},
|
"permission": {"type": "string", "enum": sorted(perms)},
|
||||||
"user": {"type": "integer"},
|
"user": {"type": "integer"},
|
||||||
"role": {"type": "string"},
|
"role": {"type": "string"},
|
||||||
},
|
},
|
||||||
|
|||||||
@ -1,10 +1,11 @@
|
|||||||
version: 1
|
version: 1
|
||||||
entries:
|
entries:
|
||||||
- identifiers:
|
foo:
|
||||||
name: "%(id)s"
|
- identifiers:
|
||||||
slug: "%(id)s"
|
name: "%(id)s"
|
||||||
model: authentik_flows.flow
|
slug: "%(id)s"
|
||||||
state: present
|
model: authentik_flows.flow
|
||||||
attrs:
|
state: present
|
||||||
designation: stage_configuration
|
attrs:
|
||||||
title: foo
|
designation: stage_configuration
|
||||||
|
title: foo
|
||||||
|
|||||||
@ -191,11 +191,18 @@ class Blueprint:
|
|||||||
"""Dataclass used for a full export"""
|
"""Dataclass used for a full export"""
|
||||||
|
|
||||||
version: int = field(default=1)
|
version: int = field(default=1)
|
||||||
entries: list[BlueprintEntry] = field(default_factory=list)
|
entries: list[BlueprintEntry] | dict[str, list[BlueprintEntry]] = field(default_factory=list)
|
||||||
context: dict = field(default_factory=dict)
|
context: dict = field(default_factory=dict)
|
||||||
|
|
||||||
metadata: BlueprintMetadata | None = field(default=None)
|
metadata: BlueprintMetadata | None = field(default=None)
|
||||||
|
|
||||||
|
def iter_entries(self) -> Iterable[BlueprintEntry]:
|
||||||
|
if isinstance(self.entries, dict):
|
||||||
|
for _section, entries in self.entries.items():
|
||||||
|
yield from entries
|
||||||
|
else:
|
||||||
|
yield from self.entries
|
||||||
|
|
||||||
|
|
||||||
class YAMLTag:
|
class YAMLTag:
|
||||||
"""Base class for all YAML Tags"""
|
"""Base class for all YAML Tags"""
|
||||||
@ -226,7 +233,7 @@ class KeyOf(YAMLTag):
|
|||||||
self.id_from = node.value
|
self.id_from = node.value
|
||||||
|
|
||||||
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
def resolve(self, entry: BlueprintEntry, blueprint: Blueprint) -> Any:
|
||||||
for _entry in blueprint.entries:
|
for _entry in blueprint.iter_entries():
|
||||||
if _entry.id == self.id_from and _entry._state.instance:
|
if _entry.id == self.id_from and _entry._state.instance:
|
||||||
# Special handling for PolicyBindingModels, as they'll have a different PK
|
# Special handling for PolicyBindingModels, as they'll have a different PK
|
||||||
# which is used when creating policy bindings
|
# which is used when creating policy bindings
|
||||||
|
|||||||
@ -384,7 +384,7 @@ class Importer:
|
|||||||
def _apply_models(self, raise_errors=False) -> bool:
|
def _apply_models(self, raise_errors=False) -> bool:
|
||||||
"""Apply (create/update) models yaml"""
|
"""Apply (create/update) models yaml"""
|
||||||
self.__pk_map = {}
|
self.__pk_map = {}
|
||||||
for entry in self._import.entries:
|
for entry in self._import.iter_entries():
|
||||||
model_app_label, model_name = entry.get_model(self._import).split(".")
|
model_app_label, model_name = entry.get_model(self._import).split(".")
|
||||||
try:
|
try:
|
||||||
model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
|
model: type[SerializerModel] = registry.get_model(model_app_label, model_name)
|
||||||
|
|||||||
@ -47,7 +47,7 @@ class MetaModelRegistry:
|
|||||||
models = apps.get_models()
|
models = apps.get_models()
|
||||||
for _, value in self.models.items():
|
for _, value in self.models.items():
|
||||||
models.append(value)
|
models.append(value)
|
||||||
return models
|
return sorted(models, key=str)
|
||||||
|
|
||||||
def get_model(self, app_label: str, model_id: str) -> type[Model]:
|
def get_model(self, app_label: str, model_id: str) -> type[Model]:
|
||||||
"""Get model checks if any virtual models are registered, and falls back
|
"""Get model checks if any virtual models are registered, and falls back
|
||||||
|
|||||||
@ -148,3 +148,14 @@ class TestBrands(APITestCase):
|
|||||||
"default_locale": "",
|
"default_locale": "",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_custom_css(self):
|
||||||
|
"""Test custom_css"""
|
||||||
|
brand = create_test_brand()
|
||||||
|
brand.branding_custom_css = """* {
|
||||||
|
font-family: "Foo bar";
|
||||||
|
}"""
|
||||||
|
brand.save()
|
||||||
|
res = self.client.get(reverse("authentik_core:if-user"))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertIn(brand.branding_custom_css, res.content.decode())
|
||||||
|
|||||||
@ -5,8 +5,10 @@ from typing import Any
|
|||||||
from django.db.models import F, Q
|
from django.db.models import F, Q
|
||||||
from django.db.models import Value as V
|
from django.db.models import Value as V
|
||||||
from django.http.request import HttpRequest
|
from django.http.request import HttpRequest
|
||||||
|
from django.utils.html import _json_script_escapes
|
||||||
|
from django.utils.safestring import mark_safe
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.lib.sentry import get_http_meta
|
from authentik.lib.sentry import get_http_meta
|
||||||
from authentik.tenants.models import Tenant
|
from authentik.tenants.models import Tenant
|
||||||
@ -32,9 +34,14 @@ def context_processor(request: HttpRequest) -> dict[str, Any]:
|
|||||||
"""Context Processor that injects brand object into every template"""
|
"""Context Processor that injects brand object into every template"""
|
||||||
brand = getattr(request, "brand", DEFAULT_BRAND)
|
brand = getattr(request, "brand", DEFAULT_BRAND)
|
||||||
tenant = getattr(request, "tenant", Tenant())
|
tenant = getattr(request, "tenant", Tenant())
|
||||||
|
# similarly to `json_script` we escape everything HTML-related, however django
|
||||||
|
# only directly exposes this as a function that also wraps it in a <script> tag
|
||||||
|
# which we dont want for CSS
|
||||||
|
brand_css = mark_safe(str(brand.branding_custom_css).translate(_json_script_escapes)) # nosec
|
||||||
return {
|
return {
|
||||||
"brand": brand,
|
"brand": brand,
|
||||||
|
"brand_css": brand_css,
|
||||||
"footer_links": tenant.footer_links,
|
"footer_links": tenant.footer_links,
|
||||||
"html_meta": {**get_http_meta()},
|
"html_meta": {**get_http_meta()},
|
||||||
"version": authentik_full_version(),
|
"version": get_full_version(),
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,11 +2,9 @@
|
|||||||
|
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from copy import copy
|
from copy import copy
|
||||||
from datetime import timedelta
|
|
||||||
|
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.db.models import QuerySet
|
from django.db.models import QuerySet
|
||||||
from django.db.models.functions import ExtractHour
|
|
||||||
from django.shortcuts import get_object_or_404
|
from django.shortcuts import get_object_or_404
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
|
||||||
@ -20,7 +18,6 @@ from rest_framework.response import Response
|
|||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.admin.api.metrics import CoordinateSerializer
|
|
||||||
from authentik.api.pagination import Pagination
|
from authentik.api.pagination import Pagination
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.core.api.providers import ProviderSerializer
|
from authentik.core.api.providers import ProviderSerializer
|
||||||
@ -28,7 +25,6 @@ from authentik.core.api.used_by import UsedByMixin
|
|||||||
from authentik.core.api.utils import ModelSerializer
|
from authentik.core.api.utils import ModelSerializer
|
||||||
from authentik.core.models import Application, User
|
from authentik.core.models import Application, User
|
||||||
from authentik.events.logs import LogEventSerializer, capture_logs
|
from authentik.events.logs import LogEventSerializer, capture_logs
|
||||||
from authentik.events.models import EventAction
|
|
||||||
from authentik.lib.utils.file import (
|
from authentik.lib.utils.file import (
|
||||||
FilePathSerializer,
|
FilePathSerializer,
|
||||||
FileUploadSerializer,
|
FileUploadSerializer,
|
||||||
@ -321,18 +317,3 @@ class ApplicationViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"""Set application icon (as URL)"""
|
"""Set application icon (as URL)"""
|
||||||
app: Application = self.get_object()
|
app: Application = self.get_object()
|
||||||
return set_file_url(request, app, "meta_icon")
|
return set_file_url(request, app, "meta_icon")
|
||||||
|
|
||||||
@permission_required("authentik_core.view_application", ["authentik_events.view_event"])
|
|
||||||
@extend_schema(responses={200: CoordinateSerializer(many=True)})
|
|
||||||
@action(detail=True, pagination_class=None, filter_backends=[])
|
|
||||||
def metrics(self, request: Request, slug: str):
|
|
||||||
"""Metrics for application logins"""
|
|
||||||
app = self.get_object()
|
|
||||||
return Response(
|
|
||||||
get_objects_for_user(request.user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.AUTHORIZE_APPLICATION,
|
|
||||||
context__authorized_application__pk=app.pk.hex,
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|||||||
@ -6,7 +6,6 @@ from typing import Any
|
|||||||
|
|
||||||
from django.contrib.auth import update_session_auth_hash
|
from django.contrib.auth import update_session_auth_hash
|
||||||
from django.contrib.auth.models import Permission
|
from django.contrib.auth.models import Permission
|
||||||
from django.db.models.functions import ExtractHour
|
|
||||||
from django.db.transaction import atomic
|
from django.db.transaction import atomic
|
||||||
from django.db.utils import IntegrityError
|
from django.db.utils import IntegrityError
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
@ -52,7 +51,6 @@ from rest_framework.validators import UniqueValidator
|
|||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.admin.api.metrics import CoordinateSerializer
|
|
||||||
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
from authentik.blueprints.v1.importer import SERIALIZER_CONTEXT_BLUEPRINT
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
@ -317,53 +315,6 @@ class SessionUserSerializer(PassiveSerializer):
|
|||||||
original = UserSelfSerializer(required=False)
|
original = UserSelfSerializer(required=False)
|
||||||
|
|
||||||
|
|
||||||
class UserMetricsSerializer(PassiveSerializer):
|
|
||||||
"""User Metrics"""
|
|
||||||
|
|
||||||
logins = SerializerMethodField()
|
|
||||||
logins_failed = SerializerMethodField()
|
|
||||||
authorizations = SerializerMethodField()
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_logins(self, _):
|
|
||||||
"""Get successful logins per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
request = self.context["request"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(request.user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.LOGIN, user__pk=user.pk
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_logins_failed(self, _):
|
|
||||||
"""Get failed logins per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
request = self.context["request"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(request.user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.LOGIN_FAILED, context__username=user.username
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
@extend_schema_field(CoordinateSerializer(many=True))
|
|
||||||
def get_authorizations(self, _):
|
|
||||||
"""Get failed logins per 8 hours for the last 7 days"""
|
|
||||||
user = self.context["user"]
|
|
||||||
request = self.context["request"]
|
|
||||||
return (
|
|
||||||
get_objects_for_user(request.user, "authentik_events.view_event").filter(
|
|
||||||
action=EventAction.AUTHORIZE_APPLICATION, user__pk=user.pk
|
|
||||||
)
|
|
||||||
# 3 data points per day, so 8 hour spans
|
|
||||||
.get_events_per(timedelta(days=7), ExtractHour, 7 * 3)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class UsersFilter(FilterSet):
|
class UsersFilter(FilterSet):
|
||||||
"""Filter for users"""
|
"""Filter for users"""
|
||||||
|
|
||||||
@ -607,17 +558,6 @@ class UserViewSet(UsedByMixin, ModelViewSet):
|
|||||||
update_session_auth_hash(self.request, user)
|
update_session_auth_hash(self.request, user)
|
||||||
return Response(status=204)
|
return Response(status=204)
|
||||||
|
|
||||||
@permission_required("authentik_core.view_user", ["authentik_events.view_event"])
|
|
||||||
@extend_schema(responses={200: UserMetricsSerializer(many=False)})
|
|
||||||
@action(detail=True, pagination_class=None, filter_backends=[])
|
|
||||||
def metrics(self, request: Request, pk: int) -> Response:
|
|
||||||
"""User metrics per 1h"""
|
|
||||||
user: User = self.get_object()
|
|
||||||
serializer = UserMetricsSerializer(instance={})
|
|
||||||
serializer.context["user"] = user
|
|
||||||
serializer.context["request"] = request
|
|
||||||
return Response(serializer.data)
|
|
||||||
|
|
||||||
@permission_required("authentik_core.reset_user_password")
|
@permission_required("authentik_core.reset_user_password")
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
responses={
|
responses={
|
||||||
|
|||||||
@ -11,7 +11,7 @@ from django.core.management.base import BaseCommand
|
|||||||
from django.db.models import Model
|
from django.db.models import Model
|
||||||
from django.db.models.signals import post_save, pre_delete
|
from django.db.models.signals import post_save, pre_delete
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.core.models import User
|
from authentik.core.models import User
|
||||||
from authentik.events.middleware import should_log_model
|
from authentik.events.middleware import should_log_model
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
@ -19,7 +19,7 @@ from authentik.events.utils import model_to_dict
|
|||||||
|
|
||||||
|
|
||||||
def get_banner_text(shell_type="shell") -> str:
|
def get_banner_text(shell_type="shell") -> str:
|
||||||
return f"""### authentik {shell_type} ({authentik_full_version()})
|
return f"""### authentik {shell_type} ({get_full_version()})
|
||||||
### Node {platform.node()} | Arch {platform.machine()} | Python {platform.python_version()} """
|
### Node {platform.node()} | Arch {platform.machine()} | Python {platform.python_version()} """
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -16,7 +16,7 @@
|
|||||||
{% block head_before %}
|
{% block head_before %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
<link rel="stylesheet" type="text/css" href="{% static 'dist/authentik.css' %}">
|
<link rel="stylesheet" type="text/css" href="{% static 'dist/authentik.css' %}">
|
||||||
<style>{{ brand.branding_custom_css }}</style>
|
<style>{{ brand_css }}</style>
|
||||||
<script src="{% versioned_script 'dist/poly-%v.js' %}" type="module"></script>
|
<script src="{% versioned_script 'dist/poly-%v.js' %}" type="module"></script>
|
||||||
<script src="{% versioned_script 'dist/standalone/loading/index-%v.js' %}" type="module"></script>
|
<script src="{% versioned_script 'dist/standalone/loading/index-%v.js' %}" type="module"></script>
|
||||||
{% block head %}
|
{% block head %}
|
||||||
|
|||||||
@ -10,7 +10,7 @@
|
|||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block body %}
|
{% block body %}
|
||||||
<ak-message-container></ak-message-container>
|
<ak-message-container alignment="bottom"></ak-message-container>
|
||||||
<ak-interface-admin>
|
<ak-interface-admin>
|
||||||
<ak-loading></ak-loading>
|
<ak-loading></ak-loading>
|
||||||
</ak-interface-admin>
|
</ak-interface-admin>
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
from django import template
|
from django import template
|
||||||
from django.templatetags.static import static as static_loader
|
from django.templatetags.static import static as static_loader
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
|
|
||||||
register = template.Library()
|
register = template.Library()
|
||||||
|
|
||||||
@ -11,4 +11,4 @@ register = template.Library()
|
|||||||
@register.simple_tag()
|
@register.simple_tag()
|
||||||
def versioned_script(path: str) -> str:
|
def versioned_script(path: str) -> str:
|
||||||
"""Wrapper around {% static %} tag that supports setting the version"""
|
"""Wrapper around {% static %} tag that supports setting the version"""
|
||||||
return static_loader(path.replace("%v", authentik_full_version()))
|
return static_loader(path.replace("%v", get_full_version()))
|
||||||
|
|||||||
@ -81,22 +81,6 @@ class TestUsersAPI(APITestCase):
|
|||||||
response = self.client.get(reverse("authentik_api:user-list"), {"include_groups": "true"})
|
response = self.client.get(reverse("authentik_api:user-list"), {"include_groups": "true"})
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
def test_metrics(self):
|
|
||||||
"""Test user's metrics"""
|
|
||||||
self.client.force_login(self.admin)
|
|
||||||
response = self.client.get(
|
|
||||||
reverse("authentik_api:user-metrics", kwargs={"pk": self.user.pk})
|
|
||||||
)
|
|
||||||
self.assertEqual(response.status_code, 200)
|
|
||||||
|
|
||||||
def test_metrics_denied(self):
|
|
||||||
"""Test user's metrics (non-superuser)"""
|
|
||||||
self.client.force_login(self.user)
|
|
||||||
response = self.client.get(
|
|
||||||
reverse("authentik_api:user-metrics", kwargs={"pk": self.user.pk})
|
|
||||||
)
|
|
||||||
self.assertEqual(response.status_code, 403)
|
|
||||||
|
|
||||||
def test_recovery_no_flow(self):
|
def test_recovery_no_flow(self):
|
||||||
"""Test user recovery link (no recovery flow set)"""
|
"""Test user recovery link (no recovery flow set)"""
|
||||||
self.client.force_login(self.admin)
|
self.client.force_login(self.admin)
|
||||||
|
|||||||
@ -10,7 +10,7 @@ from django.utils.translation import gettext as _
|
|||||||
from django.views.generic.base import RedirectView, TemplateView
|
from django.views.generic.base import RedirectView, TemplateView
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
|
|
||||||
from authentik import authentik_build_hash
|
from authentik import get_build_hash
|
||||||
from authentik.admin.tasks import LOCAL_VERSION
|
from authentik.admin.tasks import LOCAL_VERSION
|
||||||
from authentik.api.v3.config import ConfigView
|
from authentik.api.v3.config import ConfigView
|
||||||
from authentik.brands.api import CurrentBrandSerializer
|
from authentik.brands.api import CurrentBrandSerializer
|
||||||
@ -50,7 +50,7 @@ class InterfaceView(TemplateView):
|
|||||||
kwargs["brand_json"] = dumps(CurrentBrandSerializer(self.request.brand).data)
|
kwargs["brand_json"] = dumps(CurrentBrandSerializer(self.request.brand).data)
|
||||||
kwargs["version_family"] = f"{LOCAL_VERSION.major}.{LOCAL_VERSION.minor}"
|
kwargs["version_family"] = f"{LOCAL_VERSION.major}.{LOCAL_VERSION.minor}"
|
||||||
kwargs["version_subdomain"] = f"version-{LOCAL_VERSION.major}-{LOCAL_VERSION.minor}"
|
kwargs["version_subdomain"] = f"version-{LOCAL_VERSION.major}-{LOCAL_VERSION.minor}"
|
||||||
kwargs["build"] = authentik_build_hash()
|
kwargs["build"] = get_build_hash()
|
||||||
kwargs["url_kwargs"] = self.kwargs
|
kwargs["url_kwargs"] = self.kwargs
|
||||||
kwargs["base_url"] = self.request.build_absolute_uri(CONFIG.get("web.path", "/"))
|
kwargs["base_url"] = self.request.build_absolute_uri(CONFIG.get("web.path", "/"))
|
||||||
kwargs["base_url_rel"] = CONFIG.get("web.path", "/")
|
kwargs["base_url_rel"] = CONFIG.get("web.path", "/")
|
||||||
|
|||||||
@ -12,7 +12,7 @@ from cryptography.x509.oid import NameOID
|
|||||||
from django.db import models
|
from django.db import models
|
||||||
from django.utils.translation import gettext_lazy as _
|
from django.utils.translation import gettext_lazy as _
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
|
|
||||||
|
|
||||||
@ -85,7 +85,7 @@ class CertificateBuilder:
|
|||||||
.issuer_name(
|
.issuer_name(
|
||||||
x509.Name(
|
x509.Name(
|
||||||
[
|
[
|
||||||
x509.NameAttribute(NameOID.COMMON_NAME, f"authentik {authentik_version()}"),
|
x509.NameAttribute(NameOID.COMMON_NAME, f"authentik {__version__}"),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,28 +1,36 @@
|
|||||||
"""Events API Views"""
|
"""Events API Views"""
|
||||||
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from json import loads
|
|
||||||
|
|
||||||
import django_filters
|
import django_filters
|
||||||
from django.db.models.aggregates import Count
|
from django.db.models import Count, ExpressionWrapper, F, QuerySet
|
||||||
|
from django.db.models import DateTimeField as DjangoDateTimeField
|
||||||
from django.db.models.fields.json import KeyTextTransform, KeyTransform
|
from django.db.models.fields.json import KeyTextTransform, KeyTransform
|
||||||
from django.db.models.functions import ExtractDay, ExtractHour
|
from django.db.models.functions import TruncHour
|
||||||
from django.db.models.query_utils import Q
|
from django.db.models.query_utils import Q
|
||||||
|
from django.utils.timezone import now
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import OpenApiParameter, extend_schema
|
from drf_spectacular.utils import OpenApiParameter, extend_schema
|
||||||
from guardian.shortcuts import get_objects_for_user
|
from guardian.shortcuts import get_objects_for_user
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
from rest_framework.fields import DictField, IntegerField
|
from rest_framework.fields import ChoiceField, DateTimeField, DictField, IntegerField
|
||||||
from rest_framework.request import Request
|
from rest_framework.request import Request
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.admin.api.metrics import CoordinateSerializer
|
|
||||||
from authentik.core.api.object_types import TypeCreateSerializer
|
from authentik.core.api.object_types import TypeCreateSerializer
|
||||||
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
from authentik.core.api.utils import ModelSerializer, PassiveSerializer
|
||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
|
|
||||||
|
|
||||||
|
class EventVolumeSerializer(PassiveSerializer):
|
||||||
|
"""Count of events of action created on day"""
|
||||||
|
|
||||||
|
action = ChoiceField(choices=EventAction.choices)
|
||||||
|
time = DateTimeField()
|
||||||
|
count = IntegerField()
|
||||||
|
|
||||||
|
|
||||||
class EventSerializer(ModelSerializer):
|
class EventSerializer(ModelSerializer):
|
||||||
"""Event Serializer"""
|
"""Event Serializer"""
|
||||||
|
|
||||||
@ -53,7 +61,7 @@ class EventsFilter(django_filters.FilterSet):
|
|||||||
"""Filter for events"""
|
"""Filter for events"""
|
||||||
|
|
||||||
username = django_filters.CharFilter(
|
username = django_filters.CharFilter(
|
||||||
field_name="user", lookup_expr="username", label="Username"
|
field_name="user", label="Username", method="filter_username"
|
||||||
)
|
)
|
||||||
context_model_pk = django_filters.CharFilter(
|
context_model_pk = django_filters.CharFilter(
|
||||||
field_name="context",
|
field_name="context",
|
||||||
@ -78,12 +86,19 @@ class EventsFilter(django_filters.FilterSet):
|
|||||||
field_name="action",
|
field_name="action",
|
||||||
lookup_expr="icontains",
|
lookup_expr="icontains",
|
||||||
)
|
)
|
||||||
|
actions = django_filters.MultipleChoiceFilter(
|
||||||
|
field_name="action",
|
||||||
|
choices=EventAction.choices,
|
||||||
|
)
|
||||||
brand_name = django_filters.CharFilter(
|
brand_name = django_filters.CharFilter(
|
||||||
field_name="brand",
|
field_name="brand",
|
||||||
lookup_expr="name",
|
lookup_expr="name",
|
||||||
label="Brand name",
|
label="Brand name",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def filter_username(self, queryset, name, value):
|
||||||
|
return queryset.filter(Q(user__username=value) | Q(context__username=value))
|
||||||
|
|
||||||
def filter_context_model_pk(self, queryset, name, value):
|
def filter_context_model_pk(self, queryset, name, value):
|
||||||
"""Because we store the PK as UUID.hex,
|
"""Because we store the PK as UUID.hex,
|
||||||
we need to remove the dashes that a client may send. We can't use a
|
we need to remove the dashes that a client may send. We can't use a
|
||||||
@ -156,45 +171,37 @@ class EventViewSet(ModelViewSet):
|
|||||||
return Response(EventTopPerUserSerializer(instance=events, many=True).data)
|
return Response(EventTopPerUserSerializer(instance=events, many=True).data)
|
||||||
|
|
||||||
@extend_schema(
|
@extend_schema(
|
||||||
responses={200: CoordinateSerializer(many=True)},
|
responses={200: EventVolumeSerializer(many=True)},
|
||||||
)
|
|
||||||
@action(detail=False, methods=["GET"], pagination_class=None)
|
|
||||||
def volume(self, request: Request) -> Response:
|
|
||||||
"""Get event volume for specified filters and timeframe"""
|
|
||||||
queryset = self.filter_queryset(self.get_queryset())
|
|
||||||
return Response(queryset.get_events_per(timedelta(days=7), ExtractHour, 7 * 3))
|
|
||||||
|
|
||||||
@extend_schema(
|
|
||||||
responses={200: CoordinateSerializer(many=True)},
|
|
||||||
filters=[],
|
|
||||||
parameters=[
|
parameters=[
|
||||||
OpenApiParameter(
|
OpenApiParameter(
|
||||||
"action",
|
"history_days",
|
||||||
type=OpenApiTypes.STR,
|
type=OpenApiTypes.NUMBER,
|
||||||
location=OpenApiParameter.QUERY,
|
|
||||||
required=False,
|
|
||||||
),
|
|
||||||
OpenApiParameter(
|
|
||||||
"query",
|
|
||||||
type=OpenApiTypes.STR,
|
|
||||||
location=OpenApiParameter.QUERY,
|
location=OpenApiParameter.QUERY,
|
||||||
required=False,
|
required=False,
|
||||||
|
default=7,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
@action(detail=False, methods=["GET"], pagination_class=None)
|
@action(detail=False, methods=["GET"], pagination_class=None)
|
||||||
def per_month(self, request: Request):
|
def volume(self, request: Request) -> Response:
|
||||||
"""Get the count of events per month"""
|
"""Get event volume for specified filters and timeframe"""
|
||||||
filtered_action = request.query_params.get("action", EventAction.LOGIN)
|
queryset: QuerySet[Event] = self.filter_queryset(self.get_queryset())
|
||||||
try:
|
delta = timedelta(days=7)
|
||||||
query = loads(request.query_params.get("query", "{}"))
|
time_delta = request.query_params.get("history_days", 7)
|
||||||
except ValueError:
|
if time_delta:
|
||||||
return Response(status=400)
|
delta = timedelta(days=min(int(time_delta), 60))
|
||||||
return Response(
|
return Response(
|
||||||
get_objects_for_user(request.user, "authentik_events.view_event")
|
queryset.filter(created__gte=now() - delta)
|
||||||
.filter(action=filtered_action)
|
.annotate(hour=TruncHour("created"))
|
||||||
.filter(**query)
|
.annotate(
|
||||||
.get_events_per(timedelta(weeks=4), ExtractDay, 30)
|
time=ExpressionWrapper(
|
||||||
|
F("hour") - (F("hour__hour") % 6) * timedelta(hours=1),
|
||||||
|
output_field=DjangoDateTimeField(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.values("time", "action")
|
||||||
|
.annotate(count=Count("pk"))
|
||||||
|
.order_by("time", "action")
|
||||||
)
|
)
|
||||||
|
|
||||||
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
@extend_schema(responses={200: TypeCreateSerializer(many=True)})
|
||||||
|
|||||||
@ -1,7 +1,5 @@
|
|||||||
"""authentik events models"""
|
"""authentik events models"""
|
||||||
|
|
||||||
import time
|
|
||||||
from collections import Counter
|
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from difflib import get_close_matches
|
from difflib import get_close_matches
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
@ -11,11 +9,6 @@ from uuid import uuid4
|
|||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.db import connection, models
|
from django.db import connection, models
|
||||||
from django.db.models import Count, ExpressionWrapper, F
|
|
||||||
from django.db.models.fields import DurationField
|
|
||||||
from django.db.models.functions import Extract
|
|
||||||
from django.db.models.manager import Manager
|
|
||||||
from django.db.models.query import QuerySet
|
|
||||||
from django.http import HttpRequest
|
from django.http import HttpRequest
|
||||||
from django.http.request import QueryDict
|
from django.http.request import QueryDict
|
||||||
from django.utils.timezone import now
|
from django.utils.timezone import now
|
||||||
@ -24,7 +17,7 @@ from requests import RequestException
|
|||||||
from rest_framework.serializers import Serializer
|
from rest_framework.serializers import Serializer
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.brands.utils import DEFAULT_BRAND
|
from authentik.brands.utils import DEFAULT_BRAND
|
||||||
from authentik.core.middleware import (
|
from authentik.core.middleware import (
|
||||||
@ -124,60 +117,6 @@ class EventAction(models.TextChoices):
|
|||||||
CUSTOM_PREFIX = "custom_"
|
CUSTOM_PREFIX = "custom_"
|
||||||
|
|
||||||
|
|
||||||
class EventQuerySet(QuerySet):
|
|
||||||
"""Custom events query set with helper functions"""
|
|
||||||
|
|
||||||
def get_events_per(
|
|
||||||
self,
|
|
||||||
time_since: timedelta,
|
|
||||||
extract: Extract,
|
|
||||||
data_points: int,
|
|
||||||
) -> list[dict[str, int]]:
|
|
||||||
"""Get event count by hour in the last day, fill with zeros"""
|
|
||||||
_now = now()
|
|
||||||
max_since = timedelta(days=60)
|
|
||||||
# Allow maximum of 60 days to limit load
|
|
||||||
if time_since.total_seconds() > max_since.total_seconds():
|
|
||||||
time_since = max_since
|
|
||||||
date_from = _now - time_since
|
|
||||||
result = (
|
|
||||||
self.filter(created__gte=date_from)
|
|
||||||
.annotate(age=ExpressionWrapper(_now - F("created"), output_field=DurationField()))
|
|
||||||
.annotate(age_interval=extract("age"))
|
|
||||||
.values("age_interval")
|
|
||||||
.annotate(count=Count("pk"))
|
|
||||||
.order_by("age_interval")
|
|
||||||
)
|
|
||||||
data = Counter({int(d["age_interval"]): d["count"] for d in result})
|
|
||||||
results = []
|
|
||||||
interval_delta = time_since / data_points
|
|
||||||
for interval in range(1, -data_points, -1):
|
|
||||||
results.append(
|
|
||||||
{
|
|
||||||
"x_cord": time.mktime((_now + (interval_delta * interval)).timetuple()) * 1000,
|
|
||||||
"y_cord": data[interval * -1],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return results
|
|
||||||
|
|
||||||
|
|
||||||
class EventManager(Manager):
|
|
||||||
"""Custom helper methods for Events"""
|
|
||||||
|
|
||||||
def get_queryset(self) -> QuerySet:
|
|
||||||
"""use custom queryset"""
|
|
||||||
return EventQuerySet(self.model, using=self._db)
|
|
||||||
|
|
||||||
def get_events_per(
|
|
||||||
self,
|
|
||||||
time_since: timedelta,
|
|
||||||
extract: Extract,
|
|
||||||
data_points: int,
|
|
||||||
) -> list[dict[str, int]]:
|
|
||||||
"""Wrap method from queryset"""
|
|
||||||
return self.get_queryset().get_events_per(time_since, extract, data_points)
|
|
||||||
|
|
||||||
|
|
||||||
class Event(SerializerModel, ExpiringModel):
|
class Event(SerializerModel, ExpiringModel):
|
||||||
"""An individual Audit/Metrics/Notification/Error Event"""
|
"""An individual Audit/Metrics/Notification/Error Event"""
|
||||||
|
|
||||||
@ -193,8 +132,6 @@ class Event(SerializerModel, ExpiringModel):
|
|||||||
# Shadow the expires attribute from ExpiringModel to override the default duration
|
# Shadow the expires attribute from ExpiringModel to override the default duration
|
||||||
expires = models.DateTimeField(default=default_event_duration)
|
expires = models.DateTimeField(default=default_event_duration)
|
||||||
|
|
||||||
objects = EventManager()
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _get_app_from_request(request: HttpRequest) -> str:
|
def _get_app_from_request(request: HttpRequest) -> str:
|
||||||
if not isinstance(request, HttpRequest):
|
if not isinstance(request, HttpRequest):
|
||||||
@ -473,7 +410,7 @@ class NotificationTransport(SerializerModel):
|
|||||||
"title": notification.body,
|
"title": notification.body,
|
||||||
"color": "#fd4b2d",
|
"color": "#fd4b2d",
|
||||||
"fields": fields,
|
"fields": fields,
|
||||||
"footer": f"authentik {authentik_full_version()}",
|
"footer": f"authentik {get_full_version()}",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,7 +7,7 @@ from django.core.mail.backends.locmem import EmailBackend
|
|||||||
from django.test import TestCase
|
from django.test import TestCase
|
||||||
from requests_mock import Mocker
|
from requests_mock import Mocker
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
from authentik.events.models import (
|
from authentik.events.models import (
|
||||||
Event,
|
Event,
|
||||||
@ -118,7 +118,7 @@ class TestEventTransports(TestCase):
|
|||||||
{"short": True, "title": "Event user", "value": self.user.username},
|
{"short": True, "title": "Event user", "value": self.user.username},
|
||||||
{"title": "foo", "value": "bar,"},
|
{"title": "foo", "value": "bar,"},
|
||||||
],
|
],
|
||||||
"footer": f"authentik {authentik_full_version()}",
|
"footer": f"authentik {get_full_version()}",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@ -10,7 +10,7 @@ from django.core.management.base import BaseCommand
|
|||||||
from django.test import RequestFactory
|
from django.test import RequestFactory
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.core.tests.utils import create_test_admin_user
|
from authentik.core.tests.utils import create_test_admin_user
|
||||||
from authentik.flows.models import Flow
|
from authentik.flows.models import Flow
|
||||||
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner
|
from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlanner
|
||||||
@ -99,7 +99,7 @@ class Command(BaseCommand):
|
|||||||
total_min: int = min(min(inner) for inner in values)
|
total_min: int = min(min(inner) for inner in values)
|
||||||
total_avg = sum(sum(inner) for inner in values) / sum(len(inner) for inner in values)
|
total_avg = sum(sum(inner) for inner in values) / sum(len(inner) for inner in values)
|
||||||
|
|
||||||
print(f"Version: {authentik_version()}")
|
print(f"Version: {__version__}")
|
||||||
print(f"Processes: {len(values)}")
|
print(f"Processes: {len(values)}")
|
||||||
print(f"\tMax: {total_max * 100}ms")
|
print(f"\tMax: {total_max * 100}ms")
|
||||||
print(f"\tMin: {total_min * 100}ms")
|
print(f"\tMin: {total_min * 100}ms")
|
||||||
|
|||||||
@ -31,7 +31,7 @@ from sentry_sdk.tracing import BAGGAGE_HEADER_NAME, SENTRY_TRACE_HEADER_NAME
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from websockets.exceptions import WebSocketException
|
from websockets.exceptions import WebSocketException
|
||||||
|
|
||||||
from authentik import authentik_build_hash, authentik_version
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.lib.utils.http import authentik_user_agent
|
from authentik.lib.utils.http import authentik_user_agent
|
||||||
from authentik.lib.utils.reflection import get_env
|
from authentik.lib.utils.reflection import get_env
|
||||||
@ -78,11 +78,11 @@ def sentry_init(**sentry_init_kwargs):
|
|||||||
],
|
],
|
||||||
before_send=before_send,
|
before_send=before_send,
|
||||||
traces_sampler=traces_sampler,
|
traces_sampler=traces_sampler,
|
||||||
release=f"authentik@{authentik_version()}",
|
release=f"authentik@{__version__}",
|
||||||
transport=SentryTransport,
|
transport=SentryTransport,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
set_tag("authentik.build_hash", authentik_build_hash("tagged"))
|
set_tag("authentik.build_hash", get_build_hash("tagged"))
|
||||||
set_tag("authentik.env", get_env())
|
set_tag("authentik.env", get_env())
|
||||||
set_tag("authentik.component", "backend")
|
set_tag("authentik.component", "backend")
|
||||||
|
|
||||||
|
|||||||
@ -5,7 +5,7 @@ from uuid import uuid4
|
|||||||
from requests.sessions import PreparedRequest, Session
|
from requests.sessions import PreparedRequest, Session
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
@ -13,7 +13,7 @@ LOGGER = get_logger()
|
|||||||
|
|
||||||
def authentik_user_agent() -> str:
|
def authentik_user_agent() -> str:
|
||||||
"""Get a common user agent"""
|
"""Get a common user agent"""
|
||||||
return f"authentik@{authentik_full_version()}"
|
return f"authentik@{get_full_version()}"
|
||||||
|
|
||||||
|
|
||||||
class TimeoutSession(Session):
|
class TimeoutSession(Session):
|
||||||
|
|||||||
@ -13,7 +13,7 @@ from rest_framework.request import Request
|
|||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik import authentik_build_hash
|
from authentik import get_build_hash
|
||||||
from authentik.core.api.providers import ProviderSerializer
|
from authentik.core.api.providers import ProviderSerializer
|
||||||
from authentik.core.api.used_by import UsedByMixin
|
from authentik.core.api.used_by import UsedByMixin
|
||||||
from authentik.core.api.utils import JSONDictField, ModelSerializer, PassiveSerializer
|
from authentik.core.api.utils import JSONDictField, ModelSerializer, PassiveSerializer
|
||||||
@ -194,7 +194,7 @@ class OutpostViewSet(UsedByMixin, ModelViewSet):
|
|||||||
"openssl_version": state.openssl_version,
|
"openssl_version": state.openssl_version,
|
||||||
"fips_enabled": state.fips_enabled,
|
"fips_enabled": state.fips_enabled,
|
||||||
"hostname": state.hostname,
|
"hostname": state.hostname,
|
||||||
"build_hash_should": authentik_build_hash(),
|
"build_hash_should": get_build_hash(),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
return Response(OutpostHealthSerializer(states, many=True).data)
|
return Response(OutpostHealthSerializer(states, many=True).data)
|
||||||
|
|||||||
@ -37,6 +37,9 @@ class WebsocketMessageInstruction(IntEnum):
|
|||||||
# Provider specific message
|
# Provider specific message
|
||||||
PROVIDER_SPECIFIC = 3
|
PROVIDER_SPECIFIC = 3
|
||||||
|
|
||||||
|
# Session ended
|
||||||
|
SESSION_END = 4
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
@dataclass(slots=True)
|
||||||
class WebsocketMessage:
|
class WebsocketMessage:
|
||||||
@ -145,6 +148,14 @@ class OutpostConsumer(JsonWebsocketConsumer):
|
|||||||
asdict(WebsocketMessage(instruction=WebsocketMessageInstruction.TRIGGER_UPDATE))
|
asdict(WebsocketMessage(instruction=WebsocketMessageInstruction.TRIGGER_UPDATE))
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def event_session_end(self, event):
|
||||||
|
"""Event handler which is called when a session is ended"""
|
||||||
|
self.send_json(
|
||||||
|
asdict(
|
||||||
|
WebsocketMessage(instruction=WebsocketMessageInstruction.SESSION_END, args=event)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def event_provider_specific(self, event):
|
def event_provider_specific(self, event):
|
||||||
"""Event handler which can be called by provider-specific
|
"""Event handler which can be called by provider-specific
|
||||||
implementations to send specific messages to the outpost"""
|
implementations to send specific messages to the outpost"""
|
||||||
|
|||||||
@ -4,7 +4,7 @@ from dataclasses import dataclass
|
|||||||
|
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_build_hash, authentik_version
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.events.logs import LogEvent, capture_logs
|
from authentik.events.logs import LogEvent, capture_logs
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.lib.sentry import SentryIgnoredException
|
from authentik.lib.sentry import SentryIgnoredException
|
||||||
@ -99,6 +99,6 @@ class BaseController:
|
|||||||
image_name_template: str = CONFIG.get("outposts.container_image_base")
|
image_name_template: str = CONFIG.get("outposts.container_image_base")
|
||||||
return image_name_template % {
|
return image_name_template % {
|
||||||
"type": self.outpost.type,
|
"type": self.outpost.type,
|
||||||
"version": authentik_version(),
|
"version": __version__,
|
||||||
"build_hash": authentik_build_hash(),
|
"build_hash": get_build_hash(),
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,7 +13,7 @@ from paramiko.ssh_exception import SSHException
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from yaml import safe_dump
|
from yaml import safe_dump
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
from authentik.outposts.controllers.base import BaseClient, BaseController, ControllerException
|
from authentik.outposts.controllers.base import BaseClient, BaseController, ControllerException
|
||||||
from authentik.outposts.docker_ssh import DockerInlineSSH, SSHManagedExternallyException
|
from authentik.outposts.docker_ssh import DockerInlineSSH, SSHManagedExternallyException
|
||||||
@ -185,7 +185,7 @@ class DockerController(BaseController):
|
|||||||
try:
|
try:
|
||||||
self.client.images.pull(image)
|
self.client.images.pull(image)
|
||||||
except DockerException: # pragma: no cover
|
except DockerException: # pragma: no cover
|
||||||
image = f"ghcr.io/goauthentik/{self.outpost.type}:{authentik_version()}"
|
image = f"ghcr.io/goauthentik/{self.outpost.type}:{__version__}"
|
||||||
self.client.images.pull(image)
|
self.client.images.pull(image)
|
||||||
return image
|
return image
|
||||||
|
|
||||||
|
|||||||
@ -17,7 +17,7 @@ from requests import Response
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from urllib3.exceptions import HTTPError
|
from urllib3.exceptions import HTTPError
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.outposts.apps import MANAGED_OUTPOST
|
from authentik.outposts.apps import MANAGED_OUTPOST
|
||||||
from authentik.outposts.controllers.base import ControllerException
|
from authentik.outposts.controllers.base import ControllerException
|
||||||
from authentik.outposts.controllers.k8s.triggers import NeedsRecreate, NeedsUpdate
|
from authentik.outposts.controllers.k8s.triggers import NeedsRecreate, NeedsUpdate
|
||||||
@ -29,8 +29,8 @@ T = TypeVar("T", V1Pod, V1Deployment)
|
|||||||
|
|
||||||
|
|
||||||
def get_version() -> str:
|
def get_version() -> str:
|
||||||
"""Wrapper for authentik_version() to make testing easier"""
|
"""Wrapper for __version__ to make testing easier"""
|
||||||
return authentik_version()
|
return __version__
|
||||||
|
|
||||||
|
|
||||||
class KubernetesObjectReconciler(Generic[T]):
|
class KubernetesObjectReconciler(Generic[T]):
|
||||||
|
|||||||
@ -23,7 +23,7 @@ from kubernetes.client import (
|
|||||||
V1SecurityContext,
|
V1SecurityContext,
|
||||||
)
|
)
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.outposts.controllers.base import FIELD_MANAGER
|
from authentik.outposts.controllers.base import FIELD_MANAGER
|
||||||
from authentik.outposts.controllers.k8s.base import KubernetesObjectReconciler
|
from authentik.outposts.controllers.k8s.base import KubernetesObjectReconciler
|
||||||
from authentik.outposts.controllers.k8s.triggers import NeedsUpdate
|
from authentik.outposts.controllers.k8s.triggers import NeedsUpdate
|
||||||
@ -94,7 +94,7 @@ class DeploymentReconciler(KubernetesObjectReconciler[V1Deployment]):
|
|||||||
meta = self.get_object_meta(name=self.name)
|
meta = self.get_object_meta(name=self.name)
|
||||||
image_name = self.controller.get_container_image()
|
image_name = self.controller.get_container_image()
|
||||||
image_pull_secrets = self.outpost.config.kubernetes_image_pull_secrets
|
image_pull_secrets = self.outpost.config.kubernetes_image_pull_secrets
|
||||||
version = authentik_full_version().replace("+", "-")
|
version = get_full_version().replace("+", "-")
|
||||||
return V1Deployment(
|
return V1Deployment(
|
||||||
metadata=meta,
|
metadata=meta,
|
||||||
spec=V1DeploymentSpec(
|
spec=V1DeploymentSpec(
|
||||||
|
|||||||
@ -19,7 +19,7 @@ from packaging.version import Version, parse
|
|||||||
from rest_framework.serializers import Serializer
|
from rest_framework.serializers import Serializer
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_build_hash, authentik_version
|
from authentik import __version__, get_build_hash
|
||||||
from authentik.blueprints.models import ManagedModel
|
from authentik.blueprints.models import ManagedModel
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.models import (
|
from authentik.core.models import (
|
||||||
@ -38,7 +38,7 @@ from authentik.lib.sentry import SentryIgnoredException
|
|||||||
from authentik.lib.utils.errors import exception_to_string
|
from authentik.lib.utils.errors import exception_to_string
|
||||||
from authentik.outposts.controllers.k8s.utils import get_namespace
|
from authentik.outposts.controllers.k8s.utils import get_namespace
|
||||||
|
|
||||||
OUR_VERSION = parse(authentik_version())
|
OUR_VERSION = parse(__version__)
|
||||||
OUTPOST_HELLO_INTERVAL = 10
|
OUTPOST_HELLO_INTERVAL = 10
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
|
|
||||||
@ -451,7 +451,7 @@ class OutpostState:
|
|||||||
"""Check if outpost version matches our version"""
|
"""Check if outpost version matches our version"""
|
||||||
if not self.version:
|
if not self.version:
|
||||||
return False
|
return False
|
||||||
if self.build_hash != authentik_build_hash():
|
if self.build_hash != get_build_hash():
|
||||||
return False
|
return False
|
||||||
return parse(self.version) != OUR_VERSION
|
return parse(self.version) != OUR_VERSION
|
||||||
|
|
||||||
|
|||||||
@ -1,17 +1,24 @@
|
|||||||
"""authentik outpost signals"""
|
"""authentik outpost signals"""
|
||||||
|
|
||||||
|
from django.contrib.auth.signals import user_logged_out
|
||||||
from django.core.cache import cache
|
from django.core.cache import cache
|
||||||
from django.db.models import Model
|
from django.db.models import Model
|
||||||
from django.db.models.signals import m2m_changed, post_save, pre_delete, pre_save
|
from django.db.models.signals import m2m_changed, post_save, pre_delete, pre_save
|
||||||
from django.dispatch import receiver
|
from django.dispatch import receiver
|
||||||
|
from django.http import HttpRequest
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.brands.models import Brand
|
from authentik.brands.models import Brand
|
||||||
from authentik.core.models import Provider
|
from authentik.core.models import AuthenticatedSession, Provider, User
|
||||||
from authentik.crypto.models import CertificateKeyPair
|
from authentik.crypto.models import CertificateKeyPair
|
||||||
from authentik.lib.utils.reflection import class_to_path
|
from authentik.lib.utils.reflection import class_to_path
|
||||||
from authentik.outposts.models import Outpost, OutpostServiceConnection
|
from authentik.outposts.models import Outpost, OutpostServiceConnection
|
||||||
from authentik.outposts.tasks import CACHE_KEY_OUTPOST_DOWN, outpost_controller, outpost_post_save
|
from authentik.outposts.tasks import (
|
||||||
|
CACHE_KEY_OUTPOST_DOWN,
|
||||||
|
outpost_controller,
|
||||||
|
outpost_post_save,
|
||||||
|
outpost_session_end,
|
||||||
|
)
|
||||||
|
|
||||||
LOGGER = get_logger()
|
LOGGER = get_logger()
|
||||||
UPDATE_TRIGGERING_MODELS = (
|
UPDATE_TRIGGERING_MODELS = (
|
||||||
@ -73,3 +80,17 @@ def pre_delete_cleanup(sender, instance: Outpost, **_):
|
|||||||
instance.user.delete()
|
instance.user.delete()
|
||||||
cache.set(CACHE_KEY_OUTPOST_DOWN % instance.pk.hex, instance)
|
cache.set(CACHE_KEY_OUTPOST_DOWN % instance.pk.hex, instance)
|
||||||
outpost_controller.delay(instance.pk.hex, action="down", from_cache=True)
|
outpost_controller.delay(instance.pk.hex, action="down", from_cache=True)
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(user_logged_out)
|
||||||
|
def logout_revoke_direct(sender: type[User], request: HttpRequest, **_):
|
||||||
|
"""Catch logout by direct logout and forward to providers"""
|
||||||
|
if not request.session or not request.session.session_key:
|
||||||
|
return
|
||||||
|
outpost_session_end.delay(request.session.session_key)
|
||||||
|
|
||||||
|
|
||||||
|
@receiver(pre_delete, sender=AuthenticatedSession)
|
||||||
|
def logout_revoke(sender: type[AuthenticatedSession], instance: AuthenticatedSession, **_):
|
||||||
|
"""Catch logout by expiring sessions being deleted"""
|
||||||
|
outpost_session_end.delay(instance.session.session_key)
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
"""outpost tasks"""
|
"""outpost tasks"""
|
||||||
|
|
||||||
|
from hashlib import sha256
|
||||||
from os import R_OK, access
|
from os import R_OK, access
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from socket import gethostname
|
from socket import gethostname
|
||||||
@ -49,6 +50,11 @@ LOGGER = get_logger()
|
|||||||
CACHE_KEY_OUTPOST_DOWN = "goauthentik.io/outposts/teardown/%s"
|
CACHE_KEY_OUTPOST_DOWN = "goauthentik.io/outposts/teardown/%s"
|
||||||
|
|
||||||
|
|
||||||
|
def hash_session_key(session_key: str) -> str:
|
||||||
|
"""Hash the session key for sending session end signals"""
|
||||||
|
return sha256(session_key.encode("ascii")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
def controller_for_outpost(outpost: Outpost) -> type[BaseController] | None:
|
def controller_for_outpost(outpost: Outpost) -> type[BaseController] | None:
|
||||||
"""Get a controller for the outpost, when a service connection is defined"""
|
"""Get a controller for the outpost, when a service connection is defined"""
|
||||||
if not outpost.service_connection:
|
if not outpost.service_connection:
|
||||||
@ -289,3 +295,20 @@ def outpost_connection_discovery(self: SystemTask):
|
|||||||
url=unix_socket_path,
|
url=unix_socket_path,
|
||||||
)
|
)
|
||||||
self.set_status(TaskStatus.SUCCESSFUL, *messages)
|
self.set_status(TaskStatus.SUCCESSFUL, *messages)
|
||||||
|
|
||||||
|
|
||||||
|
@CELERY_APP.task()
|
||||||
|
def outpost_session_end(session_id: str):
|
||||||
|
"""Update outpost instances connected to a single outpost"""
|
||||||
|
layer = get_channel_layer()
|
||||||
|
hashed_session_id = hash_session_key(session_id)
|
||||||
|
for outpost in Outpost.objects.all():
|
||||||
|
LOGGER.info("Sending session end signal to outpost", outpost=outpost)
|
||||||
|
group = OUTPOST_GROUP % {"outpost_pk": str(outpost.pk)}
|
||||||
|
async_to_sync(layer.group_send)(
|
||||||
|
group,
|
||||||
|
{
|
||||||
|
"type": "event.session.end",
|
||||||
|
"session_id": hashed_session_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|||||||
@ -1,14 +1,12 @@
|
|||||||
"""Websocket tests"""
|
"""Websocket tests"""
|
||||||
|
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
from channels.routing import URLRouter
|
from channels.routing import URLRouter
|
||||||
from channels.testing import WebsocketCommunicator
|
from channels.testing import WebsocketCommunicator
|
||||||
from django.contrib.contenttypes.models import ContentType
|
|
||||||
from django.test import TransactionTestCase
|
from django.test import TransactionTestCase
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.core.tests.utils import create_test_flow
|
from authentik.core.tests.utils import create_test_flow
|
||||||
from authentik.outposts.consumer import WebsocketMessage, WebsocketMessageInstruction
|
from authentik.outposts.consumer import WebsocketMessage, WebsocketMessageInstruction
|
||||||
from authentik.outposts.models import Outpost, OutpostType
|
from authentik.outposts.models import Outpost, OutpostType
|
||||||
@ -16,12 +14,6 @@ from authentik.providers.proxy.models import ProxyProvider
|
|||||||
from authentik.root import websocket
|
from authentik.root import websocket
|
||||||
|
|
||||||
|
|
||||||
def patched__get_ct_cached(app_label, codename):
|
|
||||||
"""Caches `ContentType` instances like its `QuerySet` does."""
|
|
||||||
return ContentType.objects.get(app_label=app_label, permission__codename=codename)
|
|
||||||
|
|
||||||
|
|
||||||
@patch("guardian.shortcuts._get_ct_cached", patched__get_ct_cached)
|
|
||||||
class TestOutpostWS(TransactionTestCase):
|
class TestOutpostWS(TransactionTestCase):
|
||||||
"""Websocket tests"""
|
"""Websocket tests"""
|
||||||
|
|
||||||
@ -73,7 +65,7 @@ class TestOutpostWS(TransactionTestCase):
|
|||||||
WebsocketMessage(
|
WebsocketMessage(
|
||||||
instruction=WebsocketMessageInstruction.HELLO,
|
instruction=WebsocketMessageInstruction.HELLO,
|
||||||
args={
|
args={
|
||||||
"version": authentik_version(),
|
"version": __version__,
|
||||||
"buildHash": "foo",
|
"buildHash": "foo",
|
||||||
"uuid": "123",
|
"uuid": "123",
|
||||||
},
|
},
|
||||||
|
|||||||
@ -15,6 +15,7 @@ class OAuth2Error(SentryIgnoredException):
|
|||||||
|
|
||||||
error: str
|
error: str
|
||||||
description: str
|
description: str
|
||||||
|
cause: str | None = None
|
||||||
|
|
||||||
def create_dict(self):
|
def create_dict(self):
|
||||||
"""Return error as dict for JSON Rendering"""
|
"""Return error as dict for JSON Rendering"""
|
||||||
@ -34,6 +35,10 @@ class OAuth2Error(SentryIgnoredException):
|
|||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def with_cause(self, cause: str):
|
||||||
|
self.cause = cause
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
class RedirectUriError(OAuth2Error):
|
class RedirectUriError(OAuth2Error):
|
||||||
"""The request fails due to a missing, invalid, or mismatching
|
"""The request fails due to a missing, invalid, or mismatching
|
||||||
|
|||||||
@ -12,7 +12,7 @@ from authentik.core.tests.utils import create_test_admin_user, create_test_flow
|
|||||||
from authentik.events.models import Event, EventAction
|
from authentik.events.models import Event, EventAction
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
from authentik.lib.utils.time import timedelta_from_string
|
from authentik.lib.utils.time import timedelta_from_string
|
||||||
from authentik.providers.oauth2.constants import TOKEN_TYPE
|
from authentik.providers.oauth2.constants import SCOPE_OFFLINE_ACCESS, SCOPE_OPENID, TOKEN_TYPE
|
||||||
from authentik.providers.oauth2.errors import AuthorizeError, ClientIdError, RedirectUriError
|
from authentik.providers.oauth2.errors import AuthorizeError, ClientIdError, RedirectUriError
|
||||||
from authentik.providers.oauth2.models import (
|
from authentik.providers.oauth2.models import (
|
||||||
AccessToken,
|
AccessToken,
|
||||||
@ -43,7 +43,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/Foo")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/Foo")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(AuthorizeError):
|
with self.assertRaises(AuthorizeError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -53,6 +53,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.error, "unsupported_response_type")
|
||||||
|
|
||||||
def test_invalid_client_id(self):
|
def test_invalid_client_id(self):
|
||||||
"""Test invalid client ID"""
|
"""Test invalid client ID"""
|
||||||
@ -68,7 +69,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/Foo")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid/Foo")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(AuthorizeError):
|
with self.assertRaises(AuthorizeError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -79,19 +80,30 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.error, "request_not_supported")
|
||||||
|
|
||||||
def test_invalid_redirect_uri(self):
|
def test_invalid_redirect_uri_missing(self):
|
||||||
"""test missing/invalid redirect URI"""
|
"""test missing redirect URI"""
|
||||||
OAuth2Provider.objects.create(
|
OAuth2Provider.objects.create(
|
||||||
name=generate_id(),
|
name=generate_id(),
|
||||||
client_id="test",
|
client_id="test",
|
||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
with self.assertRaises(RedirectUriError) as cm:
|
||||||
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
with self.assertRaises(RedirectUriError):
|
self.assertEqual(cm.exception.cause, "redirect_uri_missing")
|
||||||
|
|
||||||
|
def test_invalid_redirect_uri(self):
|
||||||
|
"""test invalid redirect URI"""
|
||||||
|
OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
client_id="test",
|
||||||
|
authorization_flow=create_test_flow(),
|
||||||
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid")],
|
||||||
|
)
|
||||||
|
with self.assertRaises(RedirectUriError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -101,6 +113,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.cause, "redirect_uri_no_match")
|
||||||
|
|
||||||
def test_blocked_redirect_uri(self):
|
def test_blocked_redirect_uri(self):
|
||||||
"""test missing/invalid redirect URI"""
|
"""test missing/invalid redirect URI"""
|
||||||
@ -108,9 +121,9 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
name=generate_id(),
|
name=generate_id(),
|
||||||
client_id="test",
|
client_id="test",
|
||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "data:local.invalid")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "data:localhost")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
with self.assertRaises(RedirectUriError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -120,6 +133,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.cause, "redirect_uri_forbidden_scheme")
|
||||||
|
|
||||||
def test_invalid_redirect_uri_empty(self):
|
def test_invalid_redirect_uri_empty(self):
|
||||||
"""test missing/invalid redirect URI"""
|
"""test missing/invalid redirect URI"""
|
||||||
@ -129,9 +143,6 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[],
|
redirect_uris=[],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
|
||||||
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
|
||||||
OAuthAuthorizationParams.from_request(request)
|
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -150,12 +161,9 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
name=generate_id(),
|
name=generate_id(),
|
||||||
client_id="test",
|
client_id="test",
|
||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://local.invalid?")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.REGEX, "http://local.invalid?")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
with self.assertRaises(RedirectUriError) as cm:
|
||||||
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
|
||||||
OAuthAuthorizationParams.from_request(request)
|
|
||||||
with self.assertRaises(RedirectUriError):
|
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -165,6 +173,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.cause, "redirect_uri_no_match")
|
||||||
|
|
||||||
def test_redirect_uri_invalid_regex(self):
|
def test_redirect_uri_invalid_regex(self):
|
||||||
"""test missing/invalid redirect URI (invalid regex)"""
|
"""test missing/invalid redirect URI (invalid regex)"""
|
||||||
@ -172,12 +181,9 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
name=generate_id(),
|
name=generate_id(),
|
||||||
client_id="test",
|
client_id="test",
|
||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "+")],
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.REGEX, "+")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
with self.assertRaises(RedirectUriError) as cm:
|
||||||
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
|
||||||
OAuthAuthorizationParams.from_request(request)
|
|
||||||
with self.assertRaises(RedirectUriError):
|
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -187,23 +193,22 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.cause, "redirect_uri_no_match")
|
||||||
|
|
||||||
def test_empty_redirect_uri(self):
|
def test_redirect_uri_regex(self):
|
||||||
"""test empty redirect URI (configure in provider)"""
|
"""test valid redirect URI (regex)"""
|
||||||
OAuth2Provider.objects.create(
|
OAuth2Provider.objects.create(
|
||||||
name=generate_id(),
|
name=generate_id(),
|
||||||
client_id="test",
|
client_id="test",
|
||||||
authorization_flow=create_test_flow(),
|
authorization_flow=create_test_flow(),
|
||||||
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.REGEX, ".+")],
|
||||||
)
|
)
|
||||||
with self.assertRaises(RedirectUriError):
|
|
||||||
request = self.factory.get("/", data={"response_type": "code", "client_id": "test"})
|
|
||||||
OAuthAuthorizationParams.from_request(request)
|
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
"response_type": "code",
|
"response_type": "code",
|
||||||
"client_id": "test",
|
"client_id": "test",
|
||||||
"redirect_uri": "http://localhost",
|
"redirect_uri": "http://foo.bar.baz",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
@ -258,7 +263,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
GrantTypes.IMPLICIT,
|
GrantTypes.IMPLICIT,
|
||||||
)
|
)
|
||||||
# Implicit without openid scope
|
# Implicit without openid scope
|
||||||
with self.assertRaises(AuthorizeError):
|
with self.assertRaises(AuthorizeError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -285,7 +290,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
OAuthAuthorizationParams.from_request(request).grant_type, GrantTypes.HYBRID
|
OAuthAuthorizationParams.from_request(request).grant_type, GrantTypes.HYBRID
|
||||||
)
|
)
|
||||||
with self.assertRaises(AuthorizeError):
|
with self.assertRaises(AuthorizeError) as cm:
|
||||||
request = self.factory.get(
|
request = self.factory.get(
|
||||||
"/",
|
"/",
|
||||||
data={
|
data={
|
||||||
@ -295,6 +300,7 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
OAuthAuthorizationParams.from_request(request)
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.error, "unsupported_response_type")
|
||||||
|
|
||||||
def test_full_code(self):
|
def test_full_code(self):
|
||||||
"""Test full authorization"""
|
"""Test full authorization"""
|
||||||
@ -615,3 +621,54 @@ class TestAuthorize(OAuthTestCase):
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_openid_missing_invalid(self):
|
||||||
|
"""test request requiring an OpenID scope to be set"""
|
||||||
|
OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
client_id="test",
|
||||||
|
authorization_flow=create_test_flow(),
|
||||||
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://localhost")],
|
||||||
|
)
|
||||||
|
request = self.factory.get(
|
||||||
|
"/",
|
||||||
|
data={
|
||||||
|
"response_type": "id_token",
|
||||||
|
"client_id": "test",
|
||||||
|
"redirect_uri": "http://localhost",
|
||||||
|
"scope": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
with self.assertRaises(AuthorizeError) as cm:
|
||||||
|
OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertEqual(cm.exception.cause, "scope_openid_missing")
|
||||||
|
|
||||||
|
@apply_blueprint("system/providers-oauth2.yaml")
|
||||||
|
def test_offline_access_invalid(self):
|
||||||
|
"""test request for offline_access with invalid response type"""
|
||||||
|
provider = OAuth2Provider.objects.create(
|
||||||
|
name=generate_id(),
|
||||||
|
client_id="test",
|
||||||
|
authorization_flow=create_test_flow(),
|
||||||
|
redirect_uris=[RedirectURI(RedirectURIMatchingMode.STRICT, "http://localhost")],
|
||||||
|
)
|
||||||
|
provider.property_mappings.set(
|
||||||
|
ScopeMapping.objects.filter(
|
||||||
|
managed__in=[
|
||||||
|
"goauthentik.io/providers/oauth2/scope-openid",
|
||||||
|
"goauthentik.io/providers/oauth2/scope-offline_access",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
request = self.factory.get(
|
||||||
|
"/",
|
||||||
|
data={
|
||||||
|
"response_type": "id_token",
|
||||||
|
"client_id": "test",
|
||||||
|
"redirect_uri": "http://localhost",
|
||||||
|
"scope": f"{SCOPE_OPENID} {SCOPE_OFFLINE_ACCESS}",
|
||||||
|
"nonce": generate_id(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
parsed = OAuthAuthorizationParams.from_request(request)
|
||||||
|
self.assertNotIn(SCOPE_OFFLINE_ACCESS, parsed.scope)
|
||||||
|
|||||||
@ -190,7 +190,7 @@ class OAuthAuthorizationParams:
|
|||||||
allowed_redirect_urls = self.provider.redirect_uris
|
allowed_redirect_urls = self.provider.redirect_uris
|
||||||
if not self.redirect_uri:
|
if not self.redirect_uri:
|
||||||
LOGGER.warning("Missing redirect uri.")
|
LOGGER.warning("Missing redirect uri.")
|
||||||
raise RedirectUriError("", allowed_redirect_urls)
|
raise RedirectUriError("", allowed_redirect_urls).with_cause("redirect_uri_missing")
|
||||||
|
|
||||||
if len(allowed_redirect_urls) < 1:
|
if len(allowed_redirect_urls) < 1:
|
||||||
LOGGER.info("Setting redirect for blank redirect_uris", redirect=self.redirect_uri)
|
LOGGER.info("Setting redirect for blank redirect_uris", redirect=self.redirect_uri)
|
||||||
@ -219,10 +219,14 @@ class OAuthAuthorizationParams:
|
|||||||
provider=self.provider,
|
provider=self.provider,
|
||||||
)
|
)
|
||||||
if not match_found:
|
if not match_found:
|
||||||
raise RedirectUriError(self.redirect_uri, allowed_redirect_urls)
|
raise RedirectUriError(self.redirect_uri, allowed_redirect_urls).with_cause(
|
||||||
|
"redirect_uri_no_match"
|
||||||
|
)
|
||||||
# Check against forbidden schemes
|
# Check against forbidden schemes
|
||||||
if urlparse(self.redirect_uri).scheme in FORBIDDEN_URI_SCHEMES:
|
if urlparse(self.redirect_uri).scheme in FORBIDDEN_URI_SCHEMES:
|
||||||
raise RedirectUriError(self.redirect_uri, allowed_redirect_urls)
|
raise RedirectUriError(self.redirect_uri, allowed_redirect_urls).with_cause(
|
||||||
|
"redirect_uri_forbidden_scheme"
|
||||||
|
)
|
||||||
|
|
||||||
def check_scope(self, github_compat=False):
|
def check_scope(self, github_compat=False):
|
||||||
"""Ensure openid scope is set in Hybrid flows, or when requesting an id_token"""
|
"""Ensure openid scope is set in Hybrid flows, or when requesting an id_token"""
|
||||||
@ -251,7 +255,9 @@ class OAuthAuthorizationParams:
|
|||||||
or self.response_type in [ResponseTypes.ID_TOKEN, ResponseTypes.ID_TOKEN_TOKEN]
|
or self.response_type in [ResponseTypes.ID_TOKEN, ResponseTypes.ID_TOKEN_TOKEN]
|
||||||
):
|
):
|
||||||
LOGGER.warning("Missing 'openid' scope.")
|
LOGGER.warning("Missing 'openid' scope.")
|
||||||
raise AuthorizeError(self.redirect_uri, "invalid_scope", self.grant_type, self.state)
|
raise AuthorizeError(
|
||||||
|
self.redirect_uri, "invalid_scope", self.grant_type, self.state
|
||||||
|
).with_cause("scope_openid_missing")
|
||||||
if SCOPE_OFFLINE_ACCESS in self.scope:
|
if SCOPE_OFFLINE_ACCESS in self.scope:
|
||||||
# https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
|
# https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
|
||||||
# Don't explicitly request consent with offline_access, as the spec allows for
|
# Don't explicitly request consent with offline_access, as the spec allows for
|
||||||
@ -286,7 +292,9 @@ class OAuthAuthorizationParams:
|
|||||||
return
|
return
|
||||||
if not self.nonce:
|
if not self.nonce:
|
||||||
LOGGER.warning("Missing nonce for OpenID Request")
|
LOGGER.warning("Missing nonce for OpenID Request")
|
||||||
raise AuthorizeError(self.redirect_uri, "invalid_request", self.grant_type, self.state)
|
raise AuthorizeError(
|
||||||
|
self.redirect_uri, "invalid_request", self.grant_type, self.state
|
||||||
|
).with_cause("none_missing")
|
||||||
|
|
||||||
def check_code_challenge(self):
|
def check_code_challenge(self):
|
||||||
"""PKCE validation of the transformation method."""
|
"""PKCE validation of the transformation method."""
|
||||||
@ -345,10 +353,10 @@ class AuthorizationFlowInitView(PolicyAccessView):
|
|||||||
self.request, github_compat=self.github_compat
|
self.request, github_compat=self.github_compat
|
||||||
)
|
)
|
||||||
except AuthorizeError as error:
|
except AuthorizeError as error:
|
||||||
LOGGER.warning(error.description, redirect_uri=error.redirect_uri)
|
LOGGER.warning(error.description, redirect_uri=error.redirect_uri, cause=error.cause)
|
||||||
raise RequestValidationError(error.get_response(self.request)) from None
|
raise RequestValidationError(error.get_response(self.request)) from None
|
||||||
except OAuth2Error as error:
|
except OAuth2Error as error:
|
||||||
LOGGER.warning(error.description)
|
LOGGER.warning(error.description, cause=error.cause)
|
||||||
raise RequestValidationError(
|
raise RequestValidationError(
|
||||||
bad_request_message(self.request, error.description, title=error.error)
|
bad_request_message(self.request, error.description, title=error.error)
|
||||||
) from None
|
) from None
|
||||||
|
|||||||
@ -1,23 +0,0 @@
|
|||||||
"""Proxy provider signals"""
|
|
||||||
|
|
||||||
from django.contrib.auth.signals import user_logged_out
|
|
||||||
from django.db.models.signals import pre_delete
|
|
||||||
from django.dispatch import receiver
|
|
||||||
from django.http import HttpRequest
|
|
||||||
|
|
||||||
from authentik.core.models import AuthenticatedSession, User
|
|
||||||
from authentik.providers.proxy.tasks import proxy_on_logout
|
|
||||||
|
|
||||||
|
|
||||||
@receiver(user_logged_out)
|
|
||||||
def logout_proxy_revoke_direct(sender: type[User], request: HttpRequest, **_):
|
|
||||||
"""Catch logout by direct logout and forward to proxy providers"""
|
|
||||||
if not request.session or not request.session.session_key:
|
|
||||||
return
|
|
||||||
proxy_on_logout.delay(request.session.session_key)
|
|
||||||
|
|
||||||
|
|
||||||
@receiver(pre_delete, sender=AuthenticatedSession)
|
|
||||||
def logout_proxy_revoke(sender: type[AuthenticatedSession], instance: AuthenticatedSession, **_):
|
|
||||||
"""Catch logout by expiring sessions being deleted"""
|
|
||||||
proxy_on_logout.delay(instance.session.session_key)
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
"""proxy provider tasks"""
|
|
||||||
|
|
||||||
from asgiref.sync import async_to_sync
|
|
||||||
from channels.layers import get_channel_layer
|
|
||||||
|
|
||||||
from authentik.outposts.consumer import OUTPOST_GROUP
|
|
||||||
from authentik.outposts.models import Outpost, OutpostType
|
|
||||||
from authentik.providers.oauth2.id_token import hash_session_key
|
|
||||||
from authentik.root.celery import CELERY_APP
|
|
||||||
|
|
||||||
|
|
||||||
@CELERY_APP.task()
|
|
||||||
def proxy_on_logout(session_id: str):
|
|
||||||
"""Update outpost instances connected to a single outpost"""
|
|
||||||
layer = get_channel_layer()
|
|
||||||
hashed_session_id = hash_session_key(session_id)
|
|
||||||
for outpost in Outpost.objects.filter(type=OutpostType.PROXY):
|
|
||||||
group = OUTPOST_GROUP % {"outpost_pk": str(outpost.pk)}
|
|
||||||
async_to_sync(layer.group_send)(
|
|
||||||
group,
|
|
||||||
{
|
|
||||||
"type": "event.provider.specific",
|
|
||||||
"sub_type": "logout",
|
|
||||||
"session_id": hashed_session_id,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
@ -20,6 +20,9 @@ from authentik.lib.utils.time import timedelta_from_string
|
|||||||
from authentik.policies.engine import PolicyEngine
|
from authentik.policies.engine import PolicyEngine
|
||||||
from authentik.policies.views import PolicyAccessView
|
from authentik.policies.views import PolicyAccessView
|
||||||
from authentik.providers.rac.models import ConnectionToken, Endpoint, RACProvider
|
from authentik.providers.rac.models import ConnectionToken, Endpoint, RACProvider
|
||||||
|
from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
|
||||||
|
|
||||||
|
PLAN_CONNECTION_SETTINGS = "connection_settings"
|
||||||
|
|
||||||
|
|
||||||
class RACStartView(PolicyAccessView):
|
class RACStartView(PolicyAccessView):
|
||||||
@ -109,10 +112,15 @@ class RACFinalStage(RedirectStage):
|
|||||||
return super().dispatch(request, *args, **kwargs)
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
def get_challenge(self, *args, **kwargs) -> RedirectChallenge:
|
def get_challenge(self, *args, **kwargs) -> RedirectChallenge:
|
||||||
|
settings = self.executor.plan.context.get(PLAN_CONNECTION_SETTINGS)
|
||||||
|
if not settings:
|
||||||
|
settings = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).get(
|
||||||
|
PLAN_CONNECTION_SETTINGS
|
||||||
|
)
|
||||||
token = ConnectionToken.objects.create(
|
token = ConnectionToken.objects.create(
|
||||||
provider=self.provider,
|
provider=self.provider,
|
||||||
endpoint=self.endpoint,
|
endpoint=self.endpoint,
|
||||||
settings=self.executor.plan.context.get("connection_settings", {}),
|
settings=settings or {},
|
||||||
session=self.request.session["authenticatedsession"],
|
session=self.request.session["authenticatedsession"],
|
||||||
expires=now() + timedelta_from_string(self.provider.connection_expiry),
|
expires=now() + timedelta_from_string(self.provider.connection_expiry),
|
||||||
expiring=True,
|
expiring=True,
|
||||||
|
|||||||
@ -1,12 +1,29 @@
|
|||||||
"""test decorators api"""
|
"""test decorators api"""
|
||||||
|
|
||||||
from django.urls import reverse
|
|
||||||
from guardian.shortcuts import assign_perm
|
from guardian.shortcuts import assign_perm
|
||||||
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.request import Request
|
||||||
|
from rest_framework.response import Response
|
||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from authentik.core.models import Application
|
from authentik.core.models import Application
|
||||||
from authentik.core.tests.utils import create_test_user
|
from authentik.core.tests.utils import create_test_user
|
||||||
from authentik.lib.generators import generate_id
|
from authentik.lib.generators import generate_id
|
||||||
|
from authentik.lib.tests.utils import get_request
|
||||||
|
from authentik.rbac.decorators import permission_required
|
||||||
|
|
||||||
|
|
||||||
|
class MVS(ModelViewSet):
|
||||||
|
|
||||||
|
queryset = Application.objects.all()
|
||||||
|
lookup_field = "slug"
|
||||||
|
|
||||||
|
@permission_required("authentik_core.view_application", ["authentik_events.view_event"])
|
||||||
|
@action(detail=True, pagination_class=None, filter_backends=[])
|
||||||
|
def test(self, request: Request, slug: str):
|
||||||
|
self.get_object()
|
||||||
|
return Response(status=200)
|
||||||
|
|
||||||
|
|
||||||
class TestAPIDecorators(APITestCase):
|
class TestAPIDecorators(APITestCase):
|
||||||
@ -18,41 +35,33 @@ class TestAPIDecorators(APITestCase):
|
|||||||
|
|
||||||
def test_obj_perm_denied(self):
|
def test_obj_perm_denied(self):
|
||||||
"""Test object perm denied"""
|
"""Test object perm denied"""
|
||||||
self.client.force_login(self.user)
|
request = get_request("", user=self.user)
|
||||||
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
||||||
response = self.client.get(
|
response = MVS.as_view({"get": "test"})(request, slug=app.slug)
|
||||||
reverse("authentik_api:application-metrics", kwargs={"slug": app.slug})
|
|
||||||
)
|
|
||||||
self.assertEqual(response.status_code, 403)
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
def test_obj_perm_global(self):
|
def test_obj_perm_global(self):
|
||||||
"""Test object perm successful (global)"""
|
"""Test object perm successful (global)"""
|
||||||
assign_perm("authentik_core.view_application", self.user)
|
assign_perm("authentik_core.view_application", self.user)
|
||||||
assign_perm("authentik_events.view_event", self.user)
|
assign_perm("authentik_events.view_event", self.user)
|
||||||
self.client.force_login(self.user)
|
|
||||||
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
||||||
response = self.client.get(
|
request = get_request("", user=self.user)
|
||||||
reverse("authentik_api:application-metrics", kwargs={"slug": app.slug})
|
response = MVS.as_view({"get": "test"})(request, slug=app.slug)
|
||||||
)
|
self.assertEqual(response.status_code, 200, response.data)
|
||||||
self.assertEqual(response.status_code, 200)
|
|
||||||
|
|
||||||
def test_obj_perm_scoped(self):
|
def test_obj_perm_scoped(self):
|
||||||
"""Test object perm successful (scoped)"""
|
"""Test object perm successful (scoped)"""
|
||||||
assign_perm("authentik_events.view_event", self.user)
|
assign_perm("authentik_events.view_event", self.user)
|
||||||
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
||||||
assign_perm("authentik_core.view_application", self.user, app)
|
assign_perm("authentik_core.view_application", self.user, app)
|
||||||
self.client.force_login(self.user)
|
request = get_request("", user=self.user)
|
||||||
response = self.client.get(
|
response = MVS.as_view({"get": "test"})(request, slug=app.slug)
|
||||||
reverse("authentik_api:application-metrics", kwargs={"slug": app.slug})
|
|
||||||
)
|
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
def test_other_perm_denied(self):
|
def test_other_perm_denied(self):
|
||||||
"""Test other perm denied"""
|
"""Test other perm denied"""
|
||||||
self.client.force_login(self.user)
|
|
||||||
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
app = Application.objects.create(name=generate_id(), slug=generate_id())
|
||||||
assign_perm("authentik_core.view_application", self.user, app)
|
assign_perm("authentik_core.view_application", self.user, app)
|
||||||
response = self.client.get(
|
request = get_request("", user=self.user)
|
||||||
reverse("authentik_api:application-metrics", kwargs={"slug": app.slug})
|
response = MVS.as_view({"get": "test"})(request, slug=app.slug)
|
||||||
)
|
|
||||||
self.assertEqual(response.status_code, 403)
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|||||||
@ -26,7 +26,7 @@ from structlog.contextvars import STRUCTLOG_KEY_PREFIX
|
|||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp
|
from tenant_schemas_celery.app import CeleryApp as TenantAwareCeleryApp
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
from authentik.lib.sentry import before_send
|
from authentik.lib.sentry import before_send
|
||||||
from authentik.lib.utils.errors import exception_to_string
|
from authentik.lib.utils.errors import exception_to_string
|
||||||
|
|
||||||
@ -158,7 +158,7 @@ class LivenessProbe(bootsteps.StartStopStep):
|
|||||||
@inspect_command(default_timeout=0.2)
|
@inspect_command(default_timeout=0.2)
|
||||||
def ping(state, **kwargs):
|
def ping(state, **kwargs):
|
||||||
"""Ping worker(s)."""
|
"""Ping worker(s)."""
|
||||||
return {"ok": "pong", "version": authentik_full_version()}
|
return {"ok": "pong", "version": get_full_version()}
|
||||||
|
|
||||||
|
|
||||||
CELERY_APP.config_from_object(settings.CELERY)
|
CELERY_APP.config_from_object(settings.CELERY)
|
||||||
|
|||||||
@ -10,7 +10,7 @@ from celery.schedules import crontab
|
|||||||
from sentry_sdk import set_tag
|
from sentry_sdk import set_tag
|
||||||
from xmlsec import enable_debug_trace
|
from xmlsec import enable_debug_trace
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.lib.config import CONFIG, django_db_config, redis_url
|
from authentik.lib.config import CONFIG, django_db_config, redis_url
|
||||||
from authentik.lib.logging import get_logger_config, structlog_configure
|
from authentik.lib.logging import get_logger_config, structlog_configure
|
||||||
from authentik.lib.sentry import sentry_init
|
from authentik.lib.sentry import sentry_init
|
||||||
@ -137,7 +137,7 @@ GUARDIAN_MONKEY_PATCH_USER = False
|
|||||||
SPECTACULAR_SETTINGS = {
|
SPECTACULAR_SETTINGS = {
|
||||||
"TITLE": "authentik",
|
"TITLE": "authentik",
|
||||||
"DESCRIPTION": "Making authentication simple.",
|
"DESCRIPTION": "Making authentication simple.",
|
||||||
"VERSION": authentik_version(),
|
"VERSION": __version__,
|
||||||
"COMPONENT_SPLIT_REQUEST": True,
|
"COMPONENT_SPLIT_REQUEST": True,
|
||||||
"SCHEMA_PATH_PREFIX": "/api/v([0-9]+(beta)?)",
|
"SCHEMA_PATH_PREFIX": "/api/v([0-9]+(beta)?)",
|
||||||
"SCHEMA_PATH_PREFIX_TRIM": True,
|
"SCHEMA_PATH_PREFIX_TRIM": True,
|
||||||
@ -486,7 +486,7 @@ if DEBUG:
|
|||||||
|
|
||||||
TENANT_APPS.append("authentik.core")
|
TENANT_APPS.append("authentik.core")
|
||||||
|
|
||||||
CONFIG.log("info", "Booting authentik", version=authentik_version())
|
CONFIG.log("info", "Booting authentik", version=__version__)
|
||||||
|
|
||||||
# Attempt to load enterprise app, if available
|
# Attempt to load enterprise app, if available
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -5,7 +5,7 @@ from ssl import OPENSSL_VERSION
|
|||||||
import pytest
|
import pytest
|
||||||
from cryptography.hazmat.backends.openssl.backend import backend
|
from cryptography.hazmat.backends.openssl.backend import backend
|
||||||
|
|
||||||
from authentik import authentik_full_version
|
from authentik import get_full_version
|
||||||
|
|
||||||
IS_CI = "CI" in environ
|
IS_CI = "CI" in environ
|
||||||
|
|
||||||
@ -22,7 +22,7 @@ def pytest_sessionstart(*_, **__):
|
|||||||
def pytest_report_header(*_, **__):
|
def pytest_report_header(*_, **__):
|
||||||
"""Add authentik version to pytest output"""
|
"""Add authentik version to pytest output"""
|
||||||
return [
|
return [
|
||||||
f"authentik version: {authentik_full_version()}",
|
f"authentik version: {get_full_version()}",
|
||||||
f"OpenSSL version: {OPENSSL_VERSION}, FIPS: {backend._fips_enabled}",
|
f"OpenSSL version: {OPENSSL_VERSION}, FIPS: {backend._fips_enabled}",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@ -3,25 +3,44 @@
|
|||||||
import os
|
import os
|
||||||
from argparse import ArgumentParser
|
from argparse import ArgumentParser
|
||||||
from unittest import TestCase
|
from unittest import TestCase
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
from django.contrib.contenttypes.models import ContentType
|
||||||
from django.test.runner import DiscoverRunner
|
from django.test.runner import DiscoverRunner
|
||||||
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik.lib.config import CONFIG
|
from authentik.lib.config import CONFIG
|
||||||
from authentik.lib.sentry import sentry_init
|
from authentik.lib.sentry import sentry_init
|
||||||
from authentik.root.signals import post_startup, pre_startup, startup
|
from authentik.root.signals import post_startup, pre_startup, startup
|
||||||
from tests.e2e.utils import get_docker_tag
|
|
||||||
|
|
||||||
# globally set maxDiff to none to show full assert error
|
# globally set maxDiff to none to show full assert error
|
||||||
TestCase.maxDiff = None
|
TestCase.maxDiff = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_docker_tag() -> str:
|
||||||
|
"""Get docker-tag based off of CI variables"""
|
||||||
|
env_pr_branch = "GITHUB_HEAD_REF"
|
||||||
|
default_branch = "GITHUB_REF"
|
||||||
|
branch_name = os.environ.get(default_branch, "main")
|
||||||
|
if os.environ.get(env_pr_branch, "") != "":
|
||||||
|
branch_name = os.environ[env_pr_branch]
|
||||||
|
branch_name = branch_name.replace("refs/heads/", "").replace("/", "-")
|
||||||
|
return f"gh-{branch_name}"
|
||||||
|
|
||||||
|
|
||||||
|
def patched__get_ct_cached(app_label, codename):
|
||||||
|
"""Caches `ContentType` instances like its `QuerySet` does."""
|
||||||
|
return ContentType.objects.get(app_label=app_label, permission__codename=codename)
|
||||||
|
|
||||||
|
|
||||||
class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
||||||
"""Runs pytest to discover and run tests."""
|
"""Runs pytest to discover and run tests."""
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
self.logger = get_logger().bind(runner="pytest")
|
||||||
|
|
||||||
self.args = []
|
self.args = []
|
||||||
if self.failfast:
|
if self.failfast:
|
||||||
@ -34,22 +53,33 @@ class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
|||||||
if kwargs.get("no_capture", False):
|
if kwargs.get("no_capture", False):
|
||||||
self.args.append("--capture=no")
|
self.args.append("--capture=no")
|
||||||
|
|
||||||
|
self._setup_test_environment()
|
||||||
|
|
||||||
|
def _setup_test_environment(self):
|
||||||
|
"""Configure test environment settings"""
|
||||||
settings.TEST = True
|
settings.TEST = True
|
||||||
settings.CELERY["task_always_eager"] = True
|
settings.CELERY["task_always_eager"] = True
|
||||||
CONFIG.set("events.context_processors.geoip", "tests/GeoLite2-City-Test.mmdb")
|
|
||||||
CONFIG.set("events.context_processors.asn", "tests/GeoLite2-ASN-Test.mmdb")
|
|
||||||
CONFIG.set("blueprints_dir", "./blueprints")
|
|
||||||
CONFIG.set(
|
|
||||||
"outposts.container_image_base",
|
|
||||||
f"ghcr.io/goauthentik/dev-%(type)s:{get_docker_tag()}",
|
|
||||||
)
|
|
||||||
CONFIG.set("tenants.enabled", False)
|
|
||||||
CONFIG.set("outposts.disable_embedded_outpost", False)
|
|
||||||
CONFIG.set("error_reporting.sample_rate", 0)
|
|
||||||
CONFIG.set("error_reporting.environment", "testing")
|
|
||||||
CONFIG.set("error_reporting.send_pii", True)
|
|
||||||
sentry_init()
|
|
||||||
|
|
||||||
|
# Test-specific configuration
|
||||||
|
test_config = {
|
||||||
|
"events.context_processors.geoip": "tests/GeoLite2-City-Test.mmdb",
|
||||||
|
"events.context_processors.asn": "tests/GeoLite2-ASN-Test.mmdb",
|
||||||
|
"blueprints_dir": "./blueprints",
|
||||||
|
"outposts.container_image_base": f"ghcr.io/goauthentik/dev-%(type)s:{get_docker_tag()}",
|
||||||
|
"tenants.enabled": False,
|
||||||
|
"outposts.disable_embedded_outpost": False,
|
||||||
|
"error_reporting.sample_rate": 0,
|
||||||
|
"error_reporting.environment": "testing",
|
||||||
|
"error_reporting.send_pii": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, value in test_config.items():
|
||||||
|
CONFIG.set(key, value)
|
||||||
|
|
||||||
|
sentry_init()
|
||||||
|
self.logger.debug("Test environment configured")
|
||||||
|
|
||||||
|
# Send startup signals
|
||||||
pre_startup.send(sender=self, mode="test")
|
pre_startup.send(sender=self, mode="test")
|
||||||
startup.send(sender=self, mode="test")
|
startup.send(sender=self, mode="test")
|
||||||
post_startup.send(sender=self, mode="test")
|
post_startup.send(sender=self, mode="test")
|
||||||
@ -72,7 +102,21 @@ class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
|||||||
help="Disable any capturing of stdout/stderr during tests.",
|
help="Disable any capturing of stdout/stderr during tests.",
|
||||||
)
|
)
|
||||||
|
|
||||||
def run_tests(self, test_labels, extra_tests=None, **kwargs):
|
def _validate_test_label(self, label: str) -> bool:
|
||||||
|
"""Validate test label format"""
|
||||||
|
if not label:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Check for invalid characters, but allow forward slashes and colons
|
||||||
|
# for paths and pytest markers
|
||||||
|
invalid_chars = set('\\*?"<>|')
|
||||||
|
if any(c in label for c in invalid_chars):
|
||||||
|
self.logger.error("Invalid characters in test label", label=label)
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def run_tests(self, test_labels: list[str], extra_tests=None, **kwargs):
|
||||||
"""Run pytest and return the exitcode.
|
"""Run pytest and return the exitcode.
|
||||||
|
|
||||||
It translates some of Django's test command option to pytest's.
|
It translates some of Django's test command option to pytest's.
|
||||||
@ -82,10 +126,17 @@ class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
|||||||
The extra_tests argument has been deprecated since Django 5.x
|
The extra_tests argument has been deprecated since Django 5.x
|
||||||
It is kept for compatibility with PyCharm's Django test runner.
|
It is kept for compatibility with PyCharm's Django test runner.
|
||||||
"""
|
"""
|
||||||
|
if not test_labels:
|
||||||
|
self.logger.error("No test files specified")
|
||||||
|
return 1
|
||||||
|
|
||||||
for label in test_labels:
|
for label in test_labels:
|
||||||
|
if not self._validate_test_label(label):
|
||||||
|
return 1
|
||||||
|
|
||||||
valid_label_found = False
|
valid_label_found = False
|
||||||
label_as_path = os.path.abspath(label)
|
label_as_path = os.path.abspath(label)
|
||||||
|
|
||||||
# File path has been specified
|
# File path has been specified
|
||||||
if os.path.exists(label_as_path):
|
if os.path.exists(label_as_path):
|
||||||
self.args.append(label_as_path)
|
self.args.append(label_as_path)
|
||||||
@ -93,24 +144,31 @@ class PytestTestRunner(DiscoverRunner): # pragma: no cover
|
|||||||
elif "::" in label:
|
elif "::" in label:
|
||||||
self.args.append(label)
|
self.args.append(label)
|
||||||
valid_label_found = True
|
valid_label_found = True
|
||||||
# Convert dotted module path to file_path::class::method
|
|
||||||
else:
|
else:
|
||||||
|
# Check if the label is a dotted module path
|
||||||
path_pieces = label.split(".")
|
path_pieces = label.split(".")
|
||||||
# Check whether only class or class and method are specified
|
|
||||||
for i in range(-1, -3, -1):
|
for i in range(-1, -3, -1):
|
||||||
path = os.path.join(*path_pieces[:i]) + ".py"
|
try:
|
||||||
label_as_path = os.path.abspath(path)
|
path = os.path.join(*path_pieces[:i]) + ".py"
|
||||||
if os.path.exists(label_as_path):
|
if os.path.exists(path):
|
||||||
path_method = label_as_path + "::" + "::".join(path_pieces[i:])
|
if i < -1:
|
||||||
self.args.append(path_method)
|
path_method = path + "::" + "::".join(path_pieces[i:])
|
||||||
valid_label_found = True
|
self.args.append(path_method)
|
||||||
break
|
else:
|
||||||
|
self.args.append(path)
|
||||||
|
valid_label_found = True
|
||||||
|
break
|
||||||
|
except (TypeError, IndexError):
|
||||||
|
continue
|
||||||
|
|
||||||
if not valid_label_found:
|
if not valid_label_found:
|
||||||
raise RuntimeError(
|
self.logger.error("Test file not found", label=label)
|
||||||
f"One of the test labels: {label!r}, "
|
return 1
|
||||||
f"is not supported. Use a dotted module name or "
|
|
||||||
f"path instead."
|
|
||||||
)
|
|
||||||
|
|
||||||
return pytest.main(self.args)
|
self.logger.info("Running tests", test_files=self.args)
|
||||||
|
with patch("guardian.shortcuts._get_ct_cached", patched__get_ct_cached):
|
||||||
|
try:
|
||||||
|
return pytest.main(self.args)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.error("Error running tests", error=str(e), test_files=self.args)
|
||||||
|
return 1
|
||||||
|
|||||||
@ -6,7 +6,7 @@ from django.http.response import Http404
|
|||||||
from requests.exceptions import RequestException
|
from requests.exceptions import RequestException
|
||||||
from structlog.stdlib import get_logger
|
from structlog.stdlib import get_logger
|
||||||
|
|
||||||
from authentik import authentik_version
|
from authentik import __version__
|
||||||
from authentik.core.sources.flow_manager import SourceFlowManager
|
from authentik.core.sources.flow_manager import SourceFlowManager
|
||||||
from authentik.lib.utils.http import get_http_session
|
from authentik.lib.utils.http import get_http_session
|
||||||
from authentik.sources.plex.models import PlexSource, UserPlexSourceConnection
|
from authentik.sources.plex.models import PlexSource, UserPlexSourceConnection
|
||||||
@ -34,7 +34,7 @@ class PlexAuth:
|
|||||||
"""Get common headers"""
|
"""Get common headers"""
|
||||||
return {
|
return {
|
||||||
"X-Plex-Product": "authentik",
|
"X-Plex-Product": "authentik",
|
||||||
"X-Plex-Version": authentik_version(),
|
"X-Plex-Version": __version__,
|
||||||
"X-Plex-Device-Vendor": "goauthentik.io",
|
"X-Plex-Device-Vendor": "goauthentik.io",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@ -100,9 +100,11 @@ def send_mail(
|
|||||||
# Because we use the Message-ID as UID for the task, manually assign it
|
# Because we use the Message-ID as UID for the task, manually assign it
|
||||||
message_object.extra_headers["Message-ID"] = message_id
|
message_object.extra_headers["Message-ID"] = message_id
|
||||||
|
|
||||||
# Add the logo (we can't add it in the previous message since MIMEImage
|
# Add the logo if it is used in the email body (we can't add it in the
|
||||||
# can't be converted to json)
|
# previous message since MIMEImage can't be converted to json)
|
||||||
message_object.attach(logo_data())
|
body = get_email_body(message_object)
|
||||||
|
if "cid:logo" in body:
|
||||||
|
message_object.attach(logo_data())
|
||||||
|
|
||||||
if (
|
if (
|
||||||
message_object.to
|
message_object.to
|
||||||
|
|||||||
@ -96,7 +96,7 @@
|
|||||||
<table width="100%" style="background-color: #FFFFFF; border-spacing: 0; margin-top: 15px;">
|
<table width="100%" style="background-color: #FFFFFF; border-spacing: 0; margin-top: 15px;">
|
||||||
<tr height="80">
|
<tr height="80">
|
||||||
<td align="center" style="padding: 20px 0;">
|
<td align="center" style="padding: 20px 0;">
|
||||||
<img src="{% block logo_url %}cid:logo.png{% endblock %}" border="0=" alt="authentik logo" class="flexibleImage logo">
|
<img src="{% block logo_url %}cid:logo{% endblock %}" border="0=" alt="authentik logo" class="flexibleImage logo">
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|||||||
@ -19,7 +19,8 @@ def logo_data() -> MIMEImage:
|
|||||||
path = Path("web/dist/assets/icons/icon_left_brand.png")
|
path = Path("web/dist/assets/icons/icon_left_brand.png")
|
||||||
with open(path, "rb") as _logo_file:
|
with open(path, "rb") as _logo_file:
|
||||||
logo = MIMEImage(_logo_file.read())
|
logo = MIMEImage(_logo_file.read())
|
||||||
logo.add_header("Content-ID", "logo.png")
|
logo.add_header("Content-ID", "<logo>")
|
||||||
|
logo.add_header("Content-Disposition", "inline", filename="logo.png")
|
||||||
return logo
|
return logo
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
14156
blueprints/schema.json
14156
blueprints/schema.json
File diff suppressed because it is too large
Load Diff
@ -2,17 +2,13 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"goauthentik.io/internal/common"
|
"goauthentik.io/internal/common"
|
||||||
"goauthentik.io/internal/config"
|
|
||||||
"goauthentik.io/internal/constants"
|
"goauthentik.io/internal/constants"
|
||||||
"goauthentik.io/internal/debug"
|
"goauthentik.io/internal/outpost/ak/entrypoint"
|
||||||
"goauthentik.io/internal/outpost/ak"
|
|
||||||
"goauthentik.io/internal/outpost/ak/healthcheck"
|
"goauthentik.io/internal/outpost/ak/healthcheck"
|
||||||
"goauthentik.io/internal/outpost/ldap"
|
"goauthentik.io/internal/outpost/ldap"
|
||||||
)
|
)
|
||||||
@ -25,65 +21,15 @@ Required environment variables:
|
|||||||
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Long: helpMessage,
|
Long: helpMessage,
|
||||||
Version: constants.FullVersion(),
|
Version: constants.FullVersion(),
|
||||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
PersistentPreRun: common.PreRun,
|
||||||
log.SetLevel(log.DebugLevel)
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
log.SetFormatter(&log.JSONFormatter{
|
err := entrypoint.OutpostMain("authentik.outpost.ldap", ldap.NewServer)
|
||||||
FieldMap: log.FieldMap{
|
|
||||||
log.FieldKeyMsg: "event",
|
|
||||||
log.FieldKeyTime: "timestamp",
|
|
||||||
},
|
|
||||||
DisableHTMLEscape: true,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
debug.EnableDebugServer()
|
|
||||||
akURL := config.Get().AuthentikHost
|
|
||||||
if akURL == "" {
|
|
||||||
fmt.Println("env AUTHENTIK_HOST not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
akToken := config.Get().AuthentikToken
|
|
||||||
if akToken == "" {
|
|
||||||
fmt.Println("env AUTHENTIK_TOKEN not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
akURLActual, err := url.Parse(akURL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
|
||||||
fmt.Println(helpMessage)
|
fmt.Println(helpMessage)
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ex := common.Init()
|
|
||||||
defer common.Defer()
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
ac := ak.NewAPIController(*akURLActual, akToken)
|
|
||||||
if ac == nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer ac.Shutdown()
|
|
||||||
|
|
||||||
ac.Server = ldap.NewServer(ac)
|
|
||||||
|
|
||||||
err = ac.Start()
|
|
||||||
if err != nil {
|
|
||||||
log.WithError(err).Panic("Failed to run server")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
}
|
}
|
||||||
|
return err
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,17 +2,13 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"goauthentik.io/internal/common"
|
"goauthentik.io/internal/common"
|
||||||
"goauthentik.io/internal/config"
|
|
||||||
"goauthentik.io/internal/constants"
|
"goauthentik.io/internal/constants"
|
||||||
"goauthentik.io/internal/debug"
|
"goauthentik.io/internal/outpost/ak/entrypoint"
|
||||||
"goauthentik.io/internal/outpost/ak"
|
|
||||||
"goauthentik.io/internal/outpost/ak/healthcheck"
|
"goauthentik.io/internal/outpost/ak/healthcheck"
|
||||||
"goauthentik.io/internal/outpost/proxyv2"
|
"goauthentik.io/internal/outpost/proxyv2"
|
||||||
)
|
)
|
||||||
@ -28,65 +24,15 @@ Optionally, you can set these:
|
|||||||
- AUTHENTIK_HOST_BROWSER: URL to use in the browser, when it differs from AUTHENTIK_HOST`
|
- AUTHENTIK_HOST_BROWSER: URL to use in the browser, when it differs from AUTHENTIK_HOST`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Long: helpMessage,
|
Long: helpMessage,
|
||||||
Version: constants.FullVersion(),
|
Version: constants.FullVersion(),
|
||||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
PersistentPreRun: common.PreRun,
|
||||||
log.SetLevel(log.DebugLevel)
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
log.SetFormatter(&log.JSONFormatter{
|
err := entrypoint.OutpostMain("authentik.outpost.proxy", proxyv2.NewProxyServer)
|
||||||
FieldMap: log.FieldMap{
|
|
||||||
log.FieldKeyMsg: "event",
|
|
||||||
log.FieldKeyTime: "timestamp",
|
|
||||||
},
|
|
||||||
DisableHTMLEscape: true,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
debug.EnableDebugServer()
|
|
||||||
akURL := config.Get().AuthentikHost
|
|
||||||
if akURL == "" {
|
|
||||||
fmt.Println("env AUTHENTIK_HOST not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
akToken := config.Get().AuthentikToken
|
|
||||||
if akToken == "" {
|
|
||||||
fmt.Println("env AUTHENTIK_TOKEN not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
akURLActual, err := url.Parse(akURL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
|
||||||
fmt.Println(helpMessage)
|
fmt.Println(helpMessage)
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ex := common.Init()
|
|
||||||
defer common.Defer()
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
ac := ak.NewAPIController(*akURLActual, akToken)
|
|
||||||
if ac == nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer ac.Shutdown()
|
|
||||||
|
|
||||||
ac.Server = proxyv2.NewProxyServer(ac)
|
|
||||||
|
|
||||||
err = ac.Start()
|
|
||||||
if err != nil {
|
|
||||||
log.WithError(err).Panic("Failed to run server")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
}
|
}
|
||||||
|
return err
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,16 +2,13 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"goauthentik.io/internal/common"
|
"goauthentik.io/internal/common"
|
||||||
"goauthentik.io/internal/constants"
|
"goauthentik.io/internal/constants"
|
||||||
"goauthentik.io/internal/debug"
|
"goauthentik.io/internal/outpost/ak/entrypoint"
|
||||||
"goauthentik.io/internal/outpost/ak"
|
|
||||||
"goauthentik.io/internal/outpost/ak/healthcheck"
|
"goauthentik.io/internal/outpost/ak/healthcheck"
|
||||||
"goauthentik.io/internal/outpost/rac"
|
"goauthentik.io/internal/outpost/rac"
|
||||||
)
|
)
|
||||||
@ -24,65 +21,15 @@ Required environment variables:
|
|||||||
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Long: helpMessage,
|
Long: helpMessage,
|
||||||
Version: constants.FullVersion(),
|
Version: constants.FullVersion(),
|
||||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
PersistentPreRun: common.PreRun,
|
||||||
log.SetLevel(log.DebugLevel)
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
log.SetFormatter(&log.JSONFormatter{
|
err := entrypoint.OutpostMain("authentik.outpost.rac", rac.NewServer)
|
||||||
FieldMap: log.FieldMap{
|
|
||||||
log.FieldKeyMsg: "event",
|
|
||||||
log.FieldKeyTime: "timestamp",
|
|
||||||
},
|
|
||||||
DisableHTMLEscape: true,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
debug.EnableDebugServer()
|
|
||||||
akURL, found := os.LookupEnv("AUTHENTIK_HOST")
|
|
||||||
if !found {
|
|
||||||
fmt.Println("env AUTHENTIK_HOST not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
akToken, found := os.LookupEnv("AUTHENTIK_TOKEN")
|
|
||||||
if !found {
|
|
||||||
fmt.Println("env AUTHENTIK_TOKEN not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
akURLActual, err := url.Parse(akURL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
|
||||||
fmt.Println(helpMessage)
|
fmt.Println(helpMessage)
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ex := common.Init()
|
|
||||||
defer common.Defer()
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
ac := ak.NewAPIController(*akURLActual, akToken)
|
|
||||||
if ac == nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer ac.Shutdown()
|
|
||||||
|
|
||||||
ac.Server = rac.NewServer(ac)
|
|
||||||
|
|
||||||
err = ac.Start()
|
|
||||||
if err != nil {
|
|
||||||
log.WithError(err).Panic("Failed to run server")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
}
|
}
|
||||||
|
return err
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,16 +2,13 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"goauthentik.io/internal/common"
|
"goauthentik.io/internal/common"
|
||||||
"goauthentik.io/internal/constants"
|
"goauthentik.io/internal/constants"
|
||||||
"goauthentik.io/internal/debug"
|
"goauthentik.io/internal/outpost/ak/entrypoint"
|
||||||
"goauthentik.io/internal/outpost/ak"
|
|
||||||
"goauthentik.io/internal/outpost/ak/healthcheck"
|
"goauthentik.io/internal/outpost/ak/healthcheck"
|
||||||
"goauthentik.io/internal/outpost/radius"
|
"goauthentik.io/internal/outpost/radius"
|
||||||
)
|
)
|
||||||
@ -24,65 +21,15 @@ Required environment variables:
|
|||||||
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
- AUTHENTIK_INSECURE: Skip SSL Certificate verification`
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Long: helpMessage,
|
Long: helpMessage,
|
||||||
Version: constants.FullVersion(),
|
Version: constants.FullVersion(),
|
||||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
PersistentPreRun: common.PreRun,
|
||||||
log.SetLevel(log.DebugLevel)
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
log.SetFormatter(&log.JSONFormatter{
|
err := entrypoint.OutpostMain("authentik.outpost.radius", radius.NewServer)
|
||||||
FieldMap: log.FieldMap{
|
|
||||||
log.FieldKeyMsg: "event",
|
|
||||||
log.FieldKeyTime: "timestamp",
|
|
||||||
},
|
|
||||||
DisableHTMLEscape: true,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
debug.EnableDebugServer()
|
|
||||||
akURL, found := os.LookupEnv("AUTHENTIK_HOST")
|
|
||||||
if !found {
|
|
||||||
fmt.Println("env AUTHENTIK_HOST not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
akToken, found := os.LookupEnv("AUTHENTIK_TOKEN")
|
|
||||||
if !found {
|
|
||||||
fmt.Println("env AUTHENTIK_TOKEN not set!")
|
|
||||||
fmt.Println(helpMessage)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
akURLActual, err := url.Parse(akURL)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
|
||||||
fmt.Println(helpMessage)
|
fmt.Println(helpMessage)
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
ex := common.Init()
|
|
||||||
defer common.Defer()
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
ac := ak.NewAPIController(*akURLActual, akToken)
|
|
||||||
if ac == nil {
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
defer ac.Shutdown()
|
|
||||||
|
|
||||||
ac.Server = radius.NewServer(ac)
|
|
||||||
|
|
||||||
err = ac.Start()
|
|
||||||
if err != nil {
|
|
||||||
log.WithError(err).Panic("Failed to run server")
|
|
||||||
}
|
|
||||||
|
|
||||||
for {
|
|
||||||
<-ex
|
|
||||||
}
|
}
|
||||||
|
return err
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -22,21 +22,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
Use: "authentik",
|
Use: "authentik",
|
||||||
Short: "Start authentik instance",
|
Short: "Start authentik instance",
|
||||||
Version: constants.FullVersion(),
|
Version: constants.FullVersion(),
|
||||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
PersistentPreRun: common.PreRun,
|
||||||
log.SetLevel(log.DebugLevel)
|
|
||||||
log.SetFormatter(&log.JSONFormatter{
|
|
||||||
FieldMap: log.FieldMap{
|
|
||||||
log.FieldKeyMsg: "event",
|
|
||||||
log.FieldKeyTime: "timestamp",
|
|
||||||
},
|
|
||||||
DisableHTMLEscape: true,
|
|
||||||
})
|
|
||||||
},
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
debug.EnableDebugServer()
|
debug.EnableDebugServer("authentik.core")
|
||||||
l := log.WithField("logger", "authentik.root")
|
l := log.WithField("logger", "authentik.root")
|
||||||
|
|
||||||
if config.Get().ErrorReporting.Enabled {
|
if config.Get().ErrorReporting.Enabled {
|
||||||
@ -45,7 +36,7 @@ var rootCmd = &cobra.Command{
|
|||||||
AttachStacktrace: true,
|
AttachStacktrace: true,
|
||||||
EnableTracing: true,
|
EnableTracing: true,
|
||||||
TracesSampler: sentryutils.SamplerFunc(config.Get().ErrorReporting.SampleRate),
|
TracesSampler: sentryutils.SamplerFunc(config.Get().ErrorReporting.SampleRate),
|
||||||
Release: fmt.Sprintf("authentik@%s", constants.VERSION()),
|
Release: fmt.Sprintf("authentik@%s", constants.VERSION),
|
||||||
Environment: config.Get().ErrorReporting.Environment,
|
Environment: config.Get().ErrorReporting.Environment,
|
||||||
HTTPTransport: webutils.NewUserAgentTransport(constants.UserAgent(), http.DefaultTransport),
|
HTTPTransport: webutils.NewUserAgentTransport(constants.UserAgent(), http.DefaultTransport),
|
||||||
IgnoreErrors: []string{
|
IgnoreErrors: []string{
|
||||||
@ -99,7 +90,7 @@ func attemptProxyStart(ws *web.WebServer, u *url.URL) {
|
|||||||
})
|
})
|
||||||
|
|
||||||
srv := proxyv2.NewProxyServer(ac)
|
srv := proxyv2.NewProxyServer(ac)
|
||||||
ws.ProxyServer = srv
|
ws.ProxyServer = srv.(*proxyv2.ProxyServer)
|
||||||
ac.Server = srv
|
ac.Server = srv
|
||||||
l.Debug("attempting to start outpost")
|
l.Debug("attempting to start outpost")
|
||||||
err := ac.StartBackgroundTasks()
|
err := ac.StartBackgroundTasks()
|
||||||
|
|||||||
@ -1,85 +1,90 @@
|
|||||||
|
---
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgresql:
|
postgresql:
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
environment:
|
|
||||||
POSTGRES_DB: ${PG_DB:-authentik}
|
|
||||||
POSTGRES_PASSWORD: ${PG_PASS:?database password required}
|
|
||||||
POSTGRES_USER: ${PG_USER:-authentik}
|
|
||||||
healthcheck:
|
|
||||||
interval: 30s
|
|
||||||
retries: 5
|
|
||||||
start_period: 20s
|
|
||||||
test:
|
|
||||||
- CMD-SHELL
|
|
||||||
- pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}
|
|
||||||
timeout: 5s
|
|
||||||
image: docker.io/library/postgres:16-alpine
|
image: docker.io/library/postgres:16-alpine
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
volumes:
|
|
||||||
- database:/var/lib/postgresql/data
|
|
||||||
redis:
|
|
||||||
command: --save 60 1 --loglevel warning
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -d $${POSTGRES_DB} -U $${POSTGRES_USER}"]
|
||||||
|
start_period: 20s
|
||||||
interval: 30s
|
interval: 30s
|
||||||
retries: 5
|
retries: 5
|
||||||
start_period: 20s
|
timeout: 5s
|
||||||
test:
|
volumes:
|
||||||
- CMD-SHELL
|
- database:/var/lib/postgresql/data
|
||||||
- redis-cli ping | grep PONG
|
environment:
|
||||||
timeout: 3s
|
POSTGRES_PASSWORD: ${PG_PASS:?database password required}
|
||||||
|
POSTGRES_USER: ${PG_USER:-authentik}
|
||||||
|
POSTGRES_DB: ${PG_DB:-authentik}
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
redis:
|
||||||
image: docker.io/library/redis:alpine
|
image: docker.io/library/redis:alpine
|
||||||
|
command: --save 60 1 --loglevel warning
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "redis-cli ping | grep PONG"]
|
||||||
|
start_period: 20s
|
||||||
|
interval: 30s
|
||||||
|
retries: 5
|
||||||
|
timeout: 3s
|
||||||
volumes:
|
volumes:
|
||||||
- redis:/data
|
- redis:/data
|
||||||
server:
|
server:
|
||||||
|
image: ${AUTHENTIK_IMAGE:-ghcr.io/goauthentik/server}:${AUTHENTIK_TAG:-2025.6.1}
|
||||||
|
restart: unless-stopped
|
||||||
command: server
|
command: server
|
||||||
depends_on:
|
|
||||||
postgresql:
|
|
||||||
condition: service_healthy
|
|
||||||
redis:
|
|
||||||
condition: service_healthy
|
|
||||||
env_file:
|
|
||||||
- .env
|
|
||||||
environment:
|
environment:
|
||||||
|
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:?secret key required}
|
||||||
|
AUTHENTIK_REDIS__HOST: redis
|
||||||
AUTHENTIK_POSTGRESQL__HOST: postgresql
|
AUTHENTIK_POSTGRESQL__HOST: postgresql
|
||||||
|
AUTHENTIK_POSTGRESQL__USER: ${PG_USER:-authentik}
|
||||||
AUTHENTIK_POSTGRESQL__NAME: ${PG_DB:-authentik}
|
AUTHENTIK_POSTGRESQL__NAME: ${PG_DB:-authentik}
|
||||||
AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
|
AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
|
||||||
AUTHENTIK_POSTGRESQL__USER: ${PG_USER:-authentik}
|
|
||||||
AUTHENTIK_REDIS__HOST: redis
|
|
||||||
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:?secret key required}
|
|
||||||
image: ${AUTHENTIK_IMAGE:-ghcr.io/goauthentik/server}:${AUTHENTIK_TAG:-2025.6.0}
|
|
||||||
ports:
|
|
||||||
- ${COMPOSE_PORT_HTTP:-9000}:9000
|
|
||||||
- ${COMPOSE_PORT_HTTPS:-9443}:9443
|
|
||||||
restart: unless-stopped
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./media:/media
|
- ./media:/media
|
||||||
- ./custom-templates:/templates
|
- ./custom-templates:/templates
|
||||||
worker:
|
env_file:
|
||||||
command: worker
|
- .env
|
||||||
|
ports:
|
||||||
|
- "${COMPOSE_PORT_HTTP:-9000}:9000"
|
||||||
|
- "${COMPOSE_PORT_HTTPS:-9443}:9443"
|
||||||
depends_on:
|
depends_on:
|
||||||
postgresql:
|
postgresql:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
redis:
|
redis:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
env_file:
|
worker:
|
||||||
- .env
|
image: ${AUTHENTIK_IMAGE:-ghcr.io/goauthentik/server}:${AUTHENTIK_TAG:-2025.6.1}
|
||||||
|
restart: unless-stopped
|
||||||
|
command: worker
|
||||||
environment:
|
environment:
|
||||||
|
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:?secret key required}
|
||||||
|
AUTHENTIK_REDIS__HOST: redis
|
||||||
AUTHENTIK_POSTGRESQL__HOST: postgresql
|
AUTHENTIK_POSTGRESQL__HOST: postgresql
|
||||||
|
AUTHENTIK_POSTGRESQL__USER: ${PG_USER:-authentik}
|
||||||
AUTHENTIK_POSTGRESQL__NAME: ${PG_DB:-authentik}
|
AUTHENTIK_POSTGRESQL__NAME: ${PG_DB:-authentik}
|
||||||
AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
|
AUTHENTIK_POSTGRESQL__PASSWORD: ${PG_PASS}
|
||||||
AUTHENTIK_POSTGRESQL__USER: ${PG_USER:-authentik}
|
# `user: root` and the docker socket volume are optional.
|
||||||
AUTHENTIK_REDIS__HOST: redis
|
# See more for the docker socket integration here:
|
||||||
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY:?secret key required}
|
# https://goauthentik.io/docs/outposts/integrations/docker
|
||||||
image: ${AUTHENTIK_IMAGE:-ghcr.io/goauthentik/server}:${AUTHENTIK_TAG:-2025.6.0}
|
# Removing `user: root` also prevents the worker from fixing the permissions
|
||||||
restart: unless-stopped
|
# on the mounted folders, so when removing this make sure the folders have the correct UID/GID
|
||||||
|
# (1000:1000 by default)
|
||||||
user: root
|
user: root
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
- ./media:/media
|
- ./media:/media
|
||||||
- ./certs:/certs
|
- ./certs:/certs
|
||||||
- ./custom-templates:/templates
|
- ./custom-templates:/templates
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
postgresql:
|
||||||
|
condition: service_healthy
|
||||||
|
redis:
|
||||||
|
condition: service_healthy
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
database:
|
database:
|
||||||
driver: local
|
driver: local
|
||||||
|
|||||||
10
go.mod
10
go.mod
@ -4,6 +4,7 @@ go 1.24.0
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
beryju.io/ldap v0.1.0
|
beryju.io/ldap v0.1.0
|
||||||
|
github.com/avast/retry-go/v4 v4.6.1
|
||||||
github.com/coreos/go-oidc/v3 v3.14.1
|
github.com/coreos/go-oidc/v3 v3.14.1
|
||||||
github.com/getsentry/sentry-go v0.33.0
|
github.com/getsentry/sentry-go v0.33.0
|
||||||
github.com/go-http-utils/etag v0.0.0-20161124023236-513ea8f21eb1
|
github.com/go-http-utils/etag v0.0.0-20161124023236-513ea8f21eb1
|
||||||
@ -16,21 +17,22 @@ require (
|
|||||||
github.com/gorilla/securecookie v1.1.2
|
github.com/gorilla/securecookie v1.1.2
|
||||||
github.com/gorilla/sessions v1.4.0
|
github.com/gorilla/sessions v1.4.0
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
|
github.com/grafana/pyroscope-go v1.2.2
|
||||||
github.com/jellydator/ttlcache/v3 v3.3.0
|
github.com/jellydator/ttlcache/v3 v3.3.0
|
||||||
github.com/mitchellh/mapstructure v1.5.0
|
github.com/mitchellh/mapstructure v1.5.0
|
||||||
github.com/nmcclain/asn1-ber v0.0.0-20170104154839-2661553a0484
|
github.com/nmcclain/asn1-ber v0.0.0-20170104154839-2661553a0484
|
||||||
github.com/pires/go-proxyproto v0.8.1
|
github.com/pires/go-proxyproto v0.8.1
|
||||||
github.com/prometheus/client_golang v1.22.0
|
github.com/prometheus/client_golang v1.22.0
|
||||||
github.com/redis/go-redis/v9 v9.9.0
|
github.com/redis/go-redis/v9 v9.10.0
|
||||||
github.com/sethvargo/go-envconfig v1.3.0
|
github.com/sethvargo/go-envconfig v1.3.0
|
||||||
github.com/sirupsen/logrus v1.9.3
|
github.com/sirupsen/logrus v1.9.3
|
||||||
github.com/spf13/cobra v1.9.1
|
github.com/spf13/cobra v1.9.1
|
||||||
github.com/stretchr/testify v1.10.0
|
github.com/stretchr/testify v1.10.0
|
||||||
github.com/wwt/guac v1.3.2
|
github.com/wwt/guac v1.3.2
|
||||||
goauthentik.io/api/v3 v3.2025060.1
|
goauthentik.io/api/v3 v3.2025061.2
|
||||||
golang.org/x/exp v0.0.0-20230210204819-062eb4c674ab
|
golang.org/x/exp v0.0.0-20230210204819-062eb4c674ab
|
||||||
golang.org/x/oauth2 v0.30.0
|
golang.org/x/oauth2 v0.30.0
|
||||||
golang.org/x/sync v0.14.0
|
golang.org/x/sync v0.15.0
|
||||||
gopkg.in/yaml.v2 v2.4.0
|
gopkg.in/yaml.v2 v2.4.0
|
||||||
layeh.com/radius v0.0.0-20210819152912-ad72663a72ab
|
layeh.com/radius v0.0.0-20210819152912-ad72663a72ab
|
||||||
)
|
)
|
||||||
@ -58,8 +60,10 @@ require (
|
|||||||
github.com/go-openapi/strfmt v0.23.0 // indirect
|
github.com/go-openapi/strfmt v0.23.0 // indirect
|
||||||
github.com/go-openapi/swag v0.23.0 // indirect
|
github.com/go-openapi/swag v0.23.0 // indirect
|
||||||
github.com/go-openapi/validate v0.24.0 // indirect
|
github.com/go-openapi/validate v0.24.0 // indirect
|
||||||
|
github.com/grafana/pyroscope-go/godeltaprof v0.1.8 // indirect
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
github.com/josharian/intern v1.0.0 // indirect
|
github.com/josharian/intern v1.0.0 // indirect
|
||||||
|
github.com/klauspost/compress v1.18.0 // indirect
|
||||||
github.com/mailru/easyjson v0.7.7 // indirect
|
github.com/mailru/easyjson v0.7.7 // indirect
|
||||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||||
github.com/oklog/ulid v1.3.1 // indirect
|
github.com/oklog/ulid v1.3.1 // indirect
|
||||||
|
|||||||
20
go.sum
20
go.sum
@ -41,6 +41,8 @@ github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7V
|
|||||||
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||||
|
github.com/avast/retry-go/v4 v4.6.1 h1:VkOLRubHdisGrHnTu89g08aQEWEgRU7LVEop3GbIcMk=
|
||||||
|
github.com/avast/retry-go/v4 v4.6.1/go.mod h1:V6oF8njAwxJ5gRo1Q7Cxab24xs5NCWZBeaHHBklR8mA=
|
||||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
@ -178,6 +180,10 @@ github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2e
|
|||||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
github.com/grafana/pyroscope-go v1.2.2 h1:uvKCyZMD724RkaCEMrSTC38Yn7AnFe8S2wiAIYdDPCE=
|
||||||
|
github.com/grafana/pyroscope-go v1.2.2/go.mod h1:zzT9QXQAp2Iz2ZdS216UiV8y9uXJYQiGE1q8v1FyhqU=
|
||||||
|
github.com/grafana/pyroscope-go/godeltaprof v0.1.8 h1:iwOtYXeeVSAeYefJNaxDytgjKtUuKQbJqgAIjlnicKg=
|
||||||
|
github.com/grafana/pyroscope-go/godeltaprof v0.1.8/go.mod h1:2+l7K7twW49Ct4wFluZD3tZ6e0SjanjcUUBPVD/UuGU=
|
||||||
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||||
@ -245,8 +251,8 @@ github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ
|
|||||||
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
|
github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I=
|
||||||
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
|
||||||
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
|
||||||
github.com/redis/go-redis/v9 v9.9.0 h1:URbPQ4xVQSQhZ27WMQVmZSo3uT3pL+4IdHVcYq2nVfM=
|
github.com/redis/go-redis/v9 v9.10.0 h1:FxwK3eV8p/CQa0Ch276C7u2d0eNC9kCmAYQ7mCXCzVs=
|
||||||
github.com/redis/go-redis/v9 v9.9.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
|
github.com/redis/go-redis/v9 v9.10.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
|
||||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
|
||||||
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
|
||||||
@ -262,6 +268,8 @@ github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
|||||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
@ -290,8 +298,8 @@ go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y
|
|||||||
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
|
go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU=
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
goauthentik.io/api/v3 v3.2025060.1 h1:H/TDuroJlQicuxrWEnLcO3lzQaHuR28xrUb1L2362Vo=
|
goauthentik.io/api/v3 v3.2025061.2 h1:bKmrl82Gz6J8lz3f+QIH9g+MEkl3MvkMXF34GktesA0=
|
||||||
goauthentik.io/api/v3 v3.2025060.1/go.mod h1:zz+mEZg8rY/7eEjkMGWJ2DnGqk+zqxuybGCGrR2O4Kw=
|
goauthentik.io/api/v3 v3.2025061.2/go.mod h1:zz+mEZg8rY/7eEjkMGWJ2DnGqk+zqxuybGCGrR2O4Kw=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
@ -376,8 +384,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
|
|||||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
|
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||||
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
|||||||
17
internal/common/prerun.go
Normal file
17
internal/common/prerun.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
func PreRun(cmd *cobra.Command, args []string) {
|
||||||
|
log.SetLevel(log.DebugLevel)
|
||||||
|
log.SetFormatter(&log.JSONFormatter{
|
||||||
|
FieldMap: log.FieldMap{
|
||||||
|
log.FieldKeyMsg: "event",
|
||||||
|
log.FieldKeyTime: "timestamp",
|
||||||
|
},
|
||||||
|
DisableHTMLEscape: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
@ -1 +0,0 @@
|
|||||||
2025.4.1
|
|
||||||
@ -1,14 +1,10 @@
|
|||||||
package constants
|
package constants
|
||||||
|
|
||||||
import (
|
import (
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed VERSION
|
|
||||||
var version string
|
|
||||||
|
|
||||||
func BUILD(def string) string {
|
func BUILD(def string) string {
|
||||||
build := os.Getenv("GIT_BUILD_HASH")
|
build := os.Getenv("GIT_BUILD_HASH")
|
||||||
if build == "" {
|
if build == "" {
|
||||||
@ -17,15 +13,12 @@ func BUILD(def string) string {
|
|||||||
return build
|
return build
|
||||||
}
|
}
|
||||||
|
|
||||||
func VERSION() string {
|
|
||||||
return version
|
|
||||||
}
|
|
||||||
|
|
||||||
func FullVersion() string {
|
func FullVersion() string {
|
||||||
|
ver := VERSION
|
||||||
if b := BUILD(""); b != "" {
|
if b := BUILD(""); b != "" {
|
||||||
return fmt.Sprintf("%s+%s", version, b)
|
return fmt.Sprintf("%s+%s", ver, b)
|
||||||
}
|
}
|
||||||
return version
|
return ver
|
||||||
}
|
}
|
||||||
|
|
||||||
func UserAgentOutpost() string {
|
func UserAgentOutpost() string {
|
||||||
@ -39,3 +32,5 @@ func UserAgentIPC() string {
|
|||||||
func UserAgent() string {
|
func UserAgent() string {
|
||||||
return fmt.Sprintf("authentik@%s", FullVersion())
|
return fmt.Sprintf("authentik@%s", FullVersion())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const VERSION = "2025.6.1"
|
||||||
|
|||||||
@ -5,19 +5,24 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/pprof"
|
"net/http/pprof"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
"github.com/grafana/pyroscope-go"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
"goauthentik.io/internal/config"
|
"goauthentik.io/internal/config"
|
||||||
"goauthentik.io/internal/utils/web"
|
"goauthentik.io/internal/utils/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
func EnableDebugServer() {
|
var l = log.WithField("logger", "authentik.debugger.go")
|
||||||
l := log.WithField("logger", "authentik.go_debugger")
|
|
||||||
|
func EnableDebugServer(appName string) {
|
||||||
if !config.Get().Debug {
|
if !config.Get().Debug {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h := mux.NewRouter()
|
h := mux.NewRouter()
|
||||||
|
enablePyroscope(appName)
|
||||||
h.HandleFunc("/debug/pprof/", pprof.Index)
|
h.HandleFunc("/debug/pprof/", pprof.Index)
|
||||||
h.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
h.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||||
h.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
h.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||||
@ -54,3 +59,38 @@ func EnableDebugServer() {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func enablePyroscope(appName string) {
|
||||||
|
p, pok := os.LookupEnv("AUTHENTIK_PYROSCOPE_HOST")
|
||||||
|
if !pok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.Debug("Enabling pyroscope")
|
||||||
|
runtime.SetMutexProfileFraction(5)
|
||||||
|
runtime.SetBlockProfileRate(5)
|
||||||
|
hostname, err := os.Hostname()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
_, err = pyroscope.Start(pyroscope.Config{
|
||||||
|
ApplicationName: appName,
|
||||||
|
ServerAddress: p,
|
||||||
|
Logger: pyroscope.StandardLogger,
|
||||||
|
Tags: map[string]string{"hostname": hostname},
|
||||||
|
ProfileTypes: []pyroscope.ProfileType{
|
||||||
|
pyroscope.ProfileCPU,
|
||||||
|
pyroscope.ProfileAllocObjects,
|
||||||
|
pyroscope.ProfileAllocSpace,
|
||||||
|
pyroscope.ProfileInuseObjects,
|
||||||
|
pyroscope.ProfileInuseSpace,
|
||||||
|
pyroscope.ProfileGoroutines,
|
||||||
|
pyroscope.ProfileMutexCount,
|
||||||
|
pyroscope.ProfileMutexDuration,
|
||||||
|
pyroscope.ProfileBlockCount,
|
||||||
|
pyroscope.ProfileBlockDuration,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -13,6 +13,7 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/avast/retry-go/v4"
|
||||||
"github.com/getsentry/sentry-go"
|
"github.com/getsentry/sentry-go"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
@ -25,8 +26,6 @@ import (
|
|||||||
"goauthentik.io/internal/utils/web"
|
"goauthentik.io/internal/utils/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
type WSHandler func(ctx context.Context, args map[string]interface{})
|
|
||||||
|
|
||||||
const ConfigLogLevel = "log_level"
|
const ConfigLogLevel = "log_level"
|
||||||
|
|
||||||
// APIController main controller which connects to the authentik api via http and ws
|
// APIController main controller which connects to the authentik api via http and ws
|
||||||
@ -43,12 +42,11 @@ type APIController struct {
|
|||||||
|
|
||||||
reloadOffset time.Duration
|
reloadOffset time.Duration
|
||||||
|
|
||||||
wsConn *websocket.Conn
|
eventConn *websocket.Conn
|
||||||
lastWsReconnect time.Time
|
lastWsReconnect time.Time
|
||||||
wsIsReconnecting bool
|
wsIsReconnecting bool
|
||||||
wsBackoffMultiplier int
|
eventHandlers []EventHandler
|
||||||
wsHandlers []WSHandler
|
refreshHandlers []func()
|
||||||
refreshHandlers []func()
|
|
||||||
|
|
||||||
instanceUUID uuid.UUID
|
instanceUUID uuid.UUID
|
||||||
}
|
}
|
||||||
@ -83,20 +81,19 @@ func NewAPIController(akURL url.URL, token string) *APIController {
|
|||||||
|
|
||||||
// Because we don't know the outpost UUID, we simply do a list and pick the first
|
// Because we don't know the outpost UUID, we simply do a list and pick the first
|
||||||
// The service account this token belongs to should only have access to a single outpost
|
// The service account this token belongs to should only have access to a single outpost
|
||||||
var outposts *api.PaginatedOutpostList
|
outposts, _ := retry.DoWithData[*api.PaginatedOutpostList](
|
||||||
var err error
|
func() (*api.PaginatedOutpostList, error) {
|
||||||
for {
|
outposts, _, err := apiClient.OutpostsApi.OutpostsInstancesList(context.Background()).Execute()
|
||||||
outposts, _, err = apiClient.OutpostsApi.OutpostsInstancesList(context.Background()).Execute()
|
return outposts, err
|
||||||
|
},
|
||||||
if err == nil {
|
retry.Attempts(0),
|
||||||
break
|
retry.Delay(time.Second*3),
|
||||||
}
|
retry.OnRetry(func(attempt uint, err error) {
|
||||||
|
log.WithError(err).Error("Failed to fetch outpost configuration, retrying in 3 seconds")
|
||||||
log.WithError(err).Error("Failed to fetch outpost configuration, retrying in 3 seconds")
|
}),
|
||||||
time.Sleep(time.Second * 3)
|
)
|
||||||
}
|
|
||||||
if len(outposts.Results) < 1 {
|
if len(outposts.Results) < 1 {
|
||||||
panic("No outposts found with given token, ensure the given token corresponds to an authenitk Outpost")
|
log.Panic("No outposts found with given token, ensure the given token corresponds to an authenitk Outpost")
|
||||||
}
|
}
|
||||||
outpost := outposts.Results[0]
|
outpost := outposts.Results[0]
|
||||||
|
|
||||||
@ -119,22 +116,25 @@ func NewAPIController(akURL url.URL, token string) *APIController {
|
|||||||
token: token,
|
token: token,
|
||||||
logger: log,
|
logger: log,
|
||||||
|
|
||||||
reloadOffset: time.Duration(rand.Intn(10)) * time.Second,
|
reloadOffset: time.Duration(rand.Intn(10)) * time.Second,
|
||||||
instanceUUID: uuid.New(),
|
instanceUUID: uuid.New(),
|
||||||
Outpost: outpost,
|
Outpost: outpost,
|
||||||
wsHandlers: []WSHandler{},
|
eventHandlers: []EventHandler{},
|
||||||
wsBackoffMultiplier: 1,
|
refreshHandlers: make([]func(), 0),
|
||||||
refreshHandlers: make([]func(), 0),
|
|
||||||
}
|
}
|
||||||
ac.logger.WithField("offset", ac.reloadOffset.String()).Debug("HA Reload offset")
|
ac.logger.WithField("offset", ac.reloadOffset.String()).Debug("HA Reload offset")
|
||||||
err = ac.initWS(akURL, outpost.Pk)
|
err = ac.initEvent(akURL, outpost.Pk)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
go ac.reconnectWS()
|
go ac.recentEvents()
|
||||||
}
|
}
|
||||||
ac.configureRefreshSignal()
|
ac.configureRefreshSignal()
|
||||||
return ac
|
return ac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *APIController) Log() *log.Entry {
|
||||||
|
return a.logger
|
||||||
|
}
|
||||||
|
|
||||||
// Start Starts all handlers, non-blocking
|
// Start Starts all handlers, non-blocking
|
||||||
func (a *APIController) Start() error {
|
func (a *APIController) Start() error {
|
||||||
err := a.Server.Refresh()
|
err := a.Server.Refresh()
|
||||||
@ -196,9 +196,9 @@ func (a *APIController) OnRefresh() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *APIController) getWebsocketPingArgs() map[string]interface{} {
|
func (a *APIController) getEventPingArgs() map[string]interface{} {
|
||||||
args := map[string]interface{}{
|
args := map[string]interface{}{
|
||||||
"version": constants.VERSION(),
|
"version": constants.VERSION,
|
||||||
"buildHash": constants.BUILD(""),
|
"buildHash": constants.BUILD(""),
|
||||||
"uuid": a.instanceUUID.String(),
|
"uuid": a.instanceUUID.String(),
|
||||||
"golangVersion": runtime.Version(),
|
"golangVersion": runtime.Version(),
|
||||||
@ -218,16 +218,16 @@ func (a *APIController) StartBackgroundTasks() error {
|
|||||||
"outpost_name": a.Outpost.Name,
|
"outpost_name": a.Outpost.Name,
|
||||||
"outpost_type": a.Server.Type(),
|
"outpost_type": a.Server.Type(),
|
||||||
"uuid": a.instanceUUID.String(),
|
"uuid": a.instanceUUID.String(),
|
||||||
"version": constants.VERSION(),
|
"version": constants.VERSION,
|
||||||
"build": constants.BUILD(""),
|
"build": constants.BUILD(""),
|
||||||
}).Set(1)
|
}).Set(1)
|
||||||
go func() {
|
go func() {
|
||||||
a.logger.Debug("Starting WS Handler...")
|
a.logger.Debug("Starting Event Handler...")
|
||||||
a.startWSHandler()
|
a.startEventHandler()
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
a.logger.Debug("Starting WS Health notifier...")
|
a.logger.Debug("Starting Event health notifier...")
|
||||||
a.startWSHealth()
|
a.startEventHealth()
|
||||||
}()
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
a.logger.Debug("Starting Interval updater...")
|
a.logger.Debug("Starting Interval updater...")
|
||||||
|
|||||||
@ -11,6 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/avast/retry-go/v4"
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
"goauthentik.io/internal/config"
|
"goauthentik.io/internal/config"
|
||||||
@ -30,7 +31,7 @@ func (ac *APIController) getWebsocketURL(akURL url.URL, outpostUUID string, quer
|
|||||||
return wsUrl
|
return wsUrl
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ac *APIController) initWS(akURL url.URL, outpostUUID string) error {
|
func (ac *APIController) initEvent(akURL url.URL, outpostUUID string) error {
|
||||||
query := akURL.Query()
|
query := akURL.Query()
|
||||||
query.Set("instance_uuid", ac.instanceUUID.String())
|
query.Set("instance_uuid", ac.instanceUUID.String())
|
||||||
|
|
||||||
@ -57,19 +58,19 @@ func (ac *APIController) initWS(akURL url.URL, outpostUUID string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
ac.wsConn = ws
|
ac.eventConn = ws
|
||||||
// Send hello message with our version
|
// Send hello message with our version
|
||||||
msg := websocketMessage{
|
msg := Event{
|
||||||
Instruction: WebsocketInstructionHello,
|
Instruction: EventKindHello,
|
||||||
Args: ac.getWebsocketPingArgs(),
|
Args: ac.getEventPingArgs(),
|
||||||
}
|
}
|
||||||
err = ws.WriteJSON(msg)
|
err = ws.WriteJSON(msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ac.logger.WithField("logger", "authentik.outpost.ak-ws").WithError(err).Warning("Failed to hello to authentik")
|
ac.logger.WithField("logger", "authentik.outpost.events").WithError(err).Warning("Failed to hello to authentik")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ac.lastWsReconnect = time.Now()
|
ac.lastWsReconnect = time.Now()
|
||||||
ac.logger.WithField("logger", "authentik.outpost.ak-ws").WithField("outpost", outpostUUID).Info("Successfully connected websocket")
|
ac.logger.WithField("logger", "authentik.outpost.events").WithField("outpost", outpostUUID).Info("Successfully connected websocket")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,19 +78,19 @@ func (ac *APIController) initWS(akURL url.URL, outpostUUID string) error {
|
|||||||
func (ac *APIController) Shutdown() {
|
func (ac *APIController) Shutdown() {
|
||||||
// Cleanly close the connection by sending a close message and then
|
// Cleanly close the connection by sending a close message and then
|
||||||
// waiting (with timeout) for the server to close the connection.
|
// waiting (with timeout) for the server to close the connection.
|
||||||
err := ac.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
err := ac.eventConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ac.logger.WithError(err).Warning("failed to write close message")
|
ac.logger.WithError(err).Warning("failed to write close message")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = ac.wsConn.Close()
|
err = ac.eventConn.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ac.logger.WithError(err).Warning("failed to close websocket")
|
ac.logger.WithError(err).Warning("failed to close websocket")
|
||||||
}
|
}
|
||||||
ac.logger.Info("finished shutdown")
|
ac.logger.Info("finished shutdown")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ac *APIController) reconnectWS() {
|
func (ac *APIController) recentEvents() {
|
||||||
if ac.wsIsReconnecting {
|
if ac.wsIsReconnecting {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@ -100,46 +101,47 @@ func (ac *APIController) reconnectWS() {
|
|||||||
Path: strings.ReplaceAll(ac.Client.GetConfig().Servers[0].URL, "api/v3", ""),
|
Path: strings.ReplaceAll(ac.Client.GetConfig().Servers[0].URL, "api/v3", ""),
|
||||||
}
|
}
|
||||||
attempt := 1
|
attempt := 1
|
||||||
for {
|
_ = retry.Do(
|
||||||
q := u.Query()
|
func() error {
|
||||||
q.Set("attempt", strconv.Itoa(attempt))
|
q := u.Query()
|
||||||
u.RawQuery = q.Encode()
|
q.Set("attempt", strconv.Itoa(attempt))
|
||||||
err := ac.initWS(u, ac.Outpost.Pk)
|
u.RawQuery = q.Encode()
|
||||||
attempt += 1
|
err := ac.initEvent(u, ac.Outpost.Pk)
|
||||||
if err != nil {
|
attempt += 1
|
||||||
ac.logger.Infof("waiting %d seconds to reconnect", ac.wsBackoffMultiplier)
|
if err != nil {
|
||||||
time.Sleep(time.Duration(ac.wsBackoffMultiplier) * time.Second)
|
return err
|
||||||
ac.wsBackoffMultiplier = ac.wsBackoffMultiplier * 2
|
|
||||||
// Limit to 300 seconds (5m)
|
|
||||||
if ac.wsBackoffMultiplier >= 300 {
|
|
||||||
ac.wsBackoffMultiplier = 300
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
ac.wsIsReconnecting = false
|
ac.wsIsReconnecting = false
|
||||||
ac.wsBackoffMultiplier = 1
|
return nil
|
||||||
return
|
},
|
||||||
}
|
retry.Delay(1*time.Second),
|
||||||
}
|
retry.MaxDelay(5*time.Minute),
|
||||||
|
retry.DelayType(retry.BackOffDelay),
|
||||||
|
retry.Attempts(0),
|
||||||
|
retry.OnRetry(func(attempt uint, err error) {
|
||||||
|
ac.logger.Infof("waiting %d seconds to reconnect", attempt)
|
||||||
|
}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ac *APIController) startWSHandler() {
|
func (ac *APIController) startEventHandler() {
|
||||||
logger := ac.logger.WithField("loop", "ws-handler")
|
logger := ac.logger.WithField("loop", "event-handler")
|
||||||
for {
|
for {
|
||||||
var wsMsg websocketMessage
|
var wsMsg Event
|
||||||
if ac.wsConn == nil {
|
if ac.eventConn == nil {
|
||||||
go ac.reconnectWS()
|
go ac.recentEvents()
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err := ac.wsConn.ReadJSON(&wsMsg)
|
err := ac.eventConn.ReadJSON(&wsMsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ConnectionStatus.With(prometheus.Labels{
|
ConnectionStatus.With(prometheus.Labels{
|
||||||
"outpost_name": ac.Outpost.Name,
|
"outpost_name": ac.Outpost.Name,
|
||||||
"outpost_type": ac.Server.Type(),
|
"outpost_type": ac.Server.Type(),
|
||||||
"uuid": ac.instanceUUID.String(),
|
"uuid": ac.instanceUUID.String(),
|
||||||
}).Set(0)
|
}).Set(0)
|
||||||
logger.WithError(err).Warning("ws read error")
|
logger.WithError(err).Warning("event read error")
|
||||||
go ac.reconnectWS()
|
go ac.recentEvents()
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -149,7 +151,8 @@ func (ac *APIController) startWSHandler() {
|
|||||||
"uuid": ac.instanceUUID.String(),
|
"uuid": ac.instanceUUID.String(),
|
||||||
}).Set(1)
|
}).Set(1)
|
||||||
switch wsMsg.Instruction {
|
switch wsMsg.Instruction {
|
||||||
case WebsocketInstructionTriggerUpdate:
|
case EventKindAck:
|
||||||
|
case EventKindTriggerUpdate:
|
||||||
time.Sleep(ac.reloadOffset)
|
time.Sleep(ac.reloadOffset)
|
||||||
logger.Debug("Got update trigger...")
|
logger.Debug("Got update trigger...")
|
||||||
err := ac.OnRefresh()
|
err := ac.OnRefresh()
|
||||||
@ -160,34 +163,37 @@ func (ac *APIController) startWSHandler() {
|
|||||||
"outpost_name": ac.Outpost.Name,
|
"outpost_name": ac.Outpost.Name,
|
||||||
"outpost_type": ac.Server.Type(),
|
"outpost_type": ac.Server.Type(),
|
||||||
"uuid": ac.instanceUUID.String(),
|
"uuid": ac.instanceUUID.String(),
|
||||||
"version": constants.VERSION(),
|
"version": constants.VERSION,
|
||||||
"build": constants.BUILD(""),
|
"build": constants.BUILD(""),
|
||||||
}).SetToCurrentTime()
|
}).SetToCurrentTime()
|
||||||
}
|
}
|
||||||
case WebsocketInstructionProviderSpecific:
|
default:
|
||||||
for _, h := range ac.wsHandlers {
|
for _, h := range ac.eventHandlers {
|
||||||
h(context.Background(), wsMsg.Args)
|
err := h(context.Background(), wsMsg)
|
||||||
|
if err != nil {
|
||||||
|
ac.logger.WithError(err).Warning("failed to run event handler")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ac *APIController) startWSHealth() {
|
func (ac *APIController) startEventHealth() {
|
||||||
ticker := time.NewTicker(time.Second * 10)
|
ticker := time.NewTicker(time.Second * 10)
|
||||||
for ; true; <-ticker.C {
|
for ; true; <-ticker.C {
|
||||||
if ac.wsConn == nil {
|
if ac.eventConn == nil {
|
||||||
go ac.reconnectWS()
|
go ac.recentEvents()
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err := ac.SendWSHello(map[string]interface{}{})
|
err := ac.SendEventHello(map[string]interface{}{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ac.logger.WithField("loop", "ws-health").WithError(err).Warning("ws write error")
|
ac.logger.WithField("loop", "event-health").WithError(err).Warning("event write error")
|
||||||
go ac.reconnectWS()
|
go ac.recentEvents()
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
ac.logger.WithField("loop", "ws-health").Trace("hello'd")
|
ac.logger.WithField("loop", "event-health").Trace("hello'd")
|
||||||
ConnectionStatus.With(prometheus.Labels{
|
ConnectionStatus.With(prometheus.Labels{
|
||||||
"outpost_name": ac.Outpost.Name,
|
"outpost_name": ac.Outpost.Name,
|
||||||
"outpost_type": ac.Server.Type(),
|
"outpost_type": ac.Server.Type(),
|
||||||
@ -222,7 +228,7 @@ func (ac *APIController) startIntervalUpdater() {
|
|||||||
"outpost_name": ac.Outpost.Name,
|
"outpost_name": ac.Outpost.Name,
|
||||||
"outpost_type": ac.Server.Type(),
|
"outpost_type": ac.Server.Type(),
|
||||||
"uuid": ac.instanceUUID.String(),
|
"uuid": ac.instanceUUID.String(),
|
||||||
"version": constants.VERSION(),
|
"version": constants.VERSION,
|
||||||
"build": constants.BUILD(""),
|
"build": constants.BUILD(""),
|
||||||
}).SetToCurrentTime()
|
}).SetToCurrentTime()
|
||||||
}
|
}
|
||||||
@ -230,19 +236,19 @@ func (ac *APIController) startIntervalUpdater() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *APIController) AddWSHandler(handler WSHandler) {
|
func (a *APIController) AddEventHandler(handler EventHandler) {
|
||||||
a.wsHandlers = append(a.wsHandlers, handler)
|
a.eventHandlers = append(a.eventHandlers, handler)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *APIController) SendWSHello(args map[string]interface{}) error {
|
func (a *APIController) SendEventHello(args map[string]interface{}) error {
|
||||||
allArgs := a.getWebsocketPingArgs()
|
allArgs := a.getEventPingArgs()
|
||||||
for key, value := range args {
|
for key, value := range args {
|
||||||
allArgs[key] = value
|
allArgs[key] = value
|
||||||
}
|
}
|
||||||
aliveMsg := websocketMessage{
|
aliveMsg := Event{
|
||||||
Instruction: WebsocketInstructionHello,
|
Instruction: EventKindHello,
|
||||||
Args: allArgs,
|
Args: allArgs,
|
||||||
}
|
}
|
||||||
err := a.wsConn.WriteJSON(aliveMsg)
|
err := a.eventConn.WriteJSON(aliveMsg)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
37
internal/outpost/ak/api_event_msg.go
Normal file
37
internal/outpost/ak/api_event_msg.go
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
package ak
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/mitchellh/mapstructure"
|
||||||
|
)
|
||||||
|
|
||||||
|
type EventKind int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Code used to acknowledge a previous message
|
||||||
|
EventKindAck EventKind = 0
|
||||||
|
// Code used to send a healthcheck keepalive
|
||||||
|
EventKindHello EventKind = 1
|
||||||
|
// Code received to trigger a config update
|
||||||
|
EventKindTriggerUpdate EventKind = 2
|
||||||
|
// Code received to trigger some provider specific function
|
||||||
|
EventKindProviderSpecific EventKind = 3
|
||||||
|
// Code received to identify the end of a session
|
||||||
|
EventKindSessionEnd EventKind = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
type EventHandler func(ctx context.Context, msg Event) error
|
||||||
|
|
||||||
|
type Event struct {
|
||||||
|
Instruction EventKind `json:"instruction"`
|
||||||
|
Args interface{} `json:"args"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wm Event) ArgsAs(out interface{}) error {
|
||||||
|
return mapstructure.Decode(wm.Args, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
type EventArgsSessionEnd struct {
|
||||||
|
SessionID string `mapstructure:"session_id"`
|
||||||
|
}
|
||||||
@ -15,7 +15,7 @@ func URLMustParse(u string) *url.URL {
|
|||||||
return ur
|
return ur
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWebsocketURL(t *testing.T) {
|
func TestEventWebsocketURL(t *testing.T) {
|
||||||
u := URLMustParse("http://localhost:9000?foo=bar")
|
u := URLMustParse("http://localhost:9000?foo=bar")
|
||||||
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
||||||
ac := &APIController{}
|
ac := &APIController{}
|
||||||
@ -23,7 +23,7 @@ func TestWebsocketURL(t *testing.T) {
|
|||||||
assert.Equal(t, "ws://localhost:9000/ws/outpost/23470845-7263-4fe3-bd79-ec1d7bf77d77/?foo=bar", nu.String())
|
assert.Equal(t, "ws://localhost:9000/ws/outpost/23470845-7263-4fe3-bd79-ec1d7bf77d77/?foo=bar", nu.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWebsocketURL_Query(t *testing.T) {
|
func TestEventWebsocketURL_Query(t *testing.T) {
|
||||||
u := URLMustParse("http://localhost:9000?foo=bar")
|
u := URLMustParse("http://localhost:9000?foo=bar")
|
||||||
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
||||||
ac := &APIController{}
|
ac := &APIController{}
|
||||||
@ -33,7 +33,7 @@ func TestWebsocketURL_Query(t *testing.T) {
|
|||||||
assert.Equal(t, "ws://localhost:9000/ws/outpost/23470845-7263-4fe3-bd79-ec1d7bf77d77/?bar=baz&foo=bar", nu.String())
|
assert.Equal(t, "ws://localhost:9000/ws/outpost/23470845-7263-4fe3-bd79-ec1d7bf77d77/?bar=baz&foo=bar", nu.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestWebsocketURL_Subpath(t *testing.T) {
|
func TestEventWebsocketURL_Subpath(t *testing.T) {
|
||||||
u := URLMustParse("http://localhost:9000/foo/bar/")
|
u := URLMustParse("http://localhost:9000/foo/bar/")
|
||||||
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
uuid := "23470845-7263-4fe3-bd79-ec1d7bf77d77"
|
||||||
ac := &APIController{}
|
ac := &APIController{}
|
||||||
@ -1,19 +0,0 @@
|
|||||||
package ak
|
|
||||||
|
|
||||||
type websocketInstruction int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// WebsocketInstructionAck Code used to acknowledge a previous message
|
|
||||||
WebsocketInstructionAck websocketInstruction = 0
|
|
||||||
// WebsocketInstructionHello Code used to send a healthcheck keepalive
|
|
||||||
WebsocketInstructionHello websocketInstruction = 1
|
|
||||||
// WebsocketInstructionTriggerUpdate Code received to trigger a config update
|
|
||||||
WebsocketInstructionTriggerUpdate websocketInstruction = 2
|
|
||||||
// WebsocketInstructionProviderSpecific Code received to trigger some provider specific function
|
|
||||||
WebsocketInstructionProviderSpecific websocketInstruction = 3
|
|
||||||
)
|
|
||||||
|
|
||||||
type websocketMessage struct {
|
|
||||||
Instruction websocketInstruction `json:"instruction"`
|
|
||||||
Args map[string]interface{} `json:"args"`
|
|
||||||
}
|
|
||||||
51
internal/outpost/ak/entrypoint/entrypoint.go
Normal file
51
internal/outpost/ak/entrypoint/entrypoint.go
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
package entrypoint
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"goauthentik.io/internal/common"
|
||||||
|
"goauthentik.io/internal/config"
|
||||||
|
"goauthentik.io/internal/debug"
|
||||||
|
"goauthentik.io/internal/outpost/ak"
|
||||||
|
)
|
||||||
|
|
||||||
|
func OutpostMain(appName string, server func(ac *ak.APIController) ak.Outpost) error {
|
||||||
|
debug.EnableDebugServer(appName)
|
||||||
|
akURL := config.Get().AuthentikHost
|
||||||
|
if akURL == "" {
|
||||||
|
return errors.New("environment variable `AUTHENTIK_HOST` not set")
|
||||||
|
}
|
||||||
|
akToken := config.Get().AuthentikToken
|
||||||
|
if akToken == "" {
|
||||||
|
return errors.New("environment variable `AUTHENTIK_TOKEN` not set")
|
||||||
|
}
|
||||||
|
|
||||||
|
akURLActual, err := url.Parse(akURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ex := common.Init()
|
||||||
|
defer common.Defer()
|
||||||
|
|
||||||
|
ac := ak.NewAPIController(*akURLActual, akToken)
|
||||||
|
if ac == nil {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
defer ac.Shutdown()
|
||||||
|
|
||||||
|
ac.Server = server(ac)
|
||||||
|
|
||||||
|
err = ac.Start()
|
||||||
|
if err != nil {
|
||||||
|
ac.Log().WithError(err).Panic("Failed to run server")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
<-ex
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -48,25 +48,25 @@ func doGlobalSetup(outpost api.Outpost, globalConfig *api.Config) {
|
|||||||
if globalConfig.ErrorReporting.Enabled {
|
if globalConfig.ErrorReporting.Enabled {
|
||||||
if !initialSetup {
|
if !initialSetup {
|
||||||
l.WithField("env", globalConfig.ErrorReporting.Environment).Debug("Error reporting enabled")
|
l.WithField("env", globalConfig.ErrorReporting.Environment).Debug("Error reporting enabled")
|
||||||
}
|
err := sentry.Init(sentry.ClientOptions{
|
||||||
err := sentry.Init(sentry.ClientOptions{
|
Dsn: globalConfig.ErrorReporting.SentryDsn,
|
||||||
Dsn: globalConfig.ErrorReporting.SentryDsn,
|
Environment: globalConfig.ErrorReporting.Environment,
|
||||||
Environment: globalConfig.ErrorReporting.Environment,
|
EnableTracing: true,
|
||||||
EnableTracing: true,
|
TracesSampler: sentryutils.SamplerFunc(float64(globalConfig.ErrorReporting.TracesSampleRate)),
|
||||||
TracesSampler: sentryutils.SamplerFunc(float64(globalConfig.ErrorReporting.TracesSampleRate)),
|
Release: fmt.Sprintf("authentik@%s", constants.VERSION),
|
||||||
Release: fmt.Sprintf("authentik@%s", constants.VERSION()),
|
HTTPTransport: webutils.NewUserAgentTransport(constants.UserAgentOutpost(), http.DefaultTransport),
|
||||||
HTTPTransport: webutils.NewUserAgentTransport(constants.UserAgentOutpost(), http.DefaultTransport),
|
IgnoreErrors: []string{
|
||||||
IgnoreErrors: []string{
|
http.ErrAbortHandler.Error(),
|
||||||
http.ErrAbortHandler.Error(),
|
},
|
||||||
},
|
})
|
||||||
})
|
if err != nil {
|
||||||
if err != nil {
|
l.WithField("env", globalConfig.ErrorReporting.Environment).WithError(err).Warning("Failed to initialise sentry")
|
||||||
l.WithField("env", globalConfig.ErrorReporting.Environment).WithError(err).Warning("Failed to initialise sentry")
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if !initialSetup {
|
if !initialSetup {
|
||||||
l.WithField("hash", constants.BUILD("tagged")).WithField("version", constants.VERSION()).Info("Starting authentik outpost")
|
l.WithField("hash", constants.BUILD("tagged")).WithField("version", constants.VERSION).Info("Starting authentik outpost")
|
||||||
initialSetup = true
|
initialSetup = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -55,11 +55,10 @@ func MockAK(outpost api.Outpost, globalConfig api.Config) *APIController {
|
|||||||
token: token,
|
token: token,
|
||||||
logger: log,
|
logger: log,
|
||||||
|
|
||||||
reloadOffset: time.Duration(rand.Intn(10)) * time.Second,
|
reloadOffset: time.Duration(rand.Intn(10)) * time.Second,
|
||||||
instanceUUID: uuid.New(),
|
instanceUUID: uuid.New(),
|
||||||
Outpost: outpost,
|
Outpost: outpost,
|
||||||
wsBackoffMultiplier: 1,
|
refreshHandlers: make([]func(), 0),
|
||||||
refreshHandlers: make([]func(), 0),
|
|
||||||
}
|
}
|
||||||
ac.logger.WithField("offset", ac.reloadOffset.String()).Debug("HA Reload offset")
|
ac.logger.WithField("offset", ac.reloadOffset.String()).Debug("HA Reload offset")
|
||||||
return ac
|
return ac
|
||||||
|
|||||||
@ -127,7 +127,7 @@ func (fe *FlowExecutor) getAnswer(stage StageComponent) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fe *FlowExecutor) GetSession() *http.Cookie {
|
func (fe *FlowExecutor) SessionCookie() *http.Cookie {
|
||||||
return fe.session
|
return fe.session
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
19
internal/outpost/flow/session.go
Normal file
19
internal/outpost/flow/session.go
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
package flow
|
||||||
|
|
||||||
|
import "github.com/golang-jwt/jwt/v5"
|
||||||
|
|
||||||
|
type SessionCookieClaims struct {
|
||||||
|
jwt.Claims
|
||||||
|
|
||||||
|
SessionID string `json:"sid"`
|
||||||
|
Authenticated bool `json:"authenticated"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe *FlowExecutor) Session() *jwt.Token {
|
||||||
|
sc := fe.SessionCookie()
|
||||||
|
if sc == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
t, _, _ := jwt.NewParser().ParseUnverified(sc.Value, &SessionCookieClaims{})
|
||||||
|
return t
|
||||||
|
}
|
||||||
@ -38,7 +38,14 @@ func (ls *LDAPServer) Bind(bindDN string, bindPW string, conn net.Conn) (ldap.LD
|
|||||||
username, err := instance.binder.GetUsername(bindDN)
|
username, err := instance.binder.GetUsername(bindDN)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
selectedApp = instance.GetAppSlug()
|
selectedApp = instance.GetAppSlug()
|
||||||
return instance.binder.Bind(username, req)
|
c, err := instance.binder.Bind(username, req)
|
||||||
|
if c == ldap.LDAPResultSuccess {
|
||||||
|
f := instance.GetFlags(req.BindDN)
|
||||||
|
ls.connectionsSync.Lock()
|
||||||
|
ls.connections[f.SessionID()] = conn
|
||||||
|
ls.connectionsSync.Unlock()
|
||||||
|
}
|
||||||
|
return c, err
|
||||||
} else {
|
} else {
|
||||||
req.Log().WithError(err).Debug("Username not for instance")
|
req.Log().WithError(err).Debug("Username not for instance")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -27,8 +27,9 @@ func (db *DirectBinder) Bind(username string, req *bind.Request) (ldap.LDAPResul
|
|||||||
|
|
||||||
passed, err := fe.Execute()
|
passed, err := fe.Execute()
|
||||||
flags := flags.UserFlags{
|
flags := flags.UserFlags{
|
||||||
Session: fe.GetSession(),
|
Session: fe.SessionCookie(),
|
||||||
UserPk: flags.InvalidUserPK,
|
SessionJWT: fe.Session(),
|
||||||
|
UserPk: flags.InvalidUserPK,
|
||||||
}
|
}
|
||||||
// only set flags if we don't have flags for this DN yet
|
// only set flags if we don't have flags for this DN yet
|
||||||
// as flags are only checked during the bind, we can remember whether a certain DN
|
// as flags are only checked during the bind, we can remember whether a certain DN
|
||||||
|
|||||||
20
internal/outpost/ldap/close.go
Normal file
20
internal/outpost/ldap/close.go
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package ldap
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
func (ls *LDAPServer) Close(dn string, conn net.Conn) error {
|
||||||
|
ls.connectionsSync.Lock()
|
||||||
|
defer ls.connectionsSync.Unlock()
|
||||||
|
key := ""
|
||||||
|
for k, c := range ls.connections {
|
||||||
|
if c == conn {
|
||||||
|
key = k
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if key == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
delete(ls.connections, key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@ -1,16 +1,30 @@
|
|||||||
package flags
|
package flags
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
"goauthentik.io/api/v3"
|
"goauthentik.io/api/v3"
|
||||||
|
"goauthentik.io/internal/outpost/flow"
|
||||||
)
|
)
|
||||||
|
|
||||||
const InvalidUserPK = -1
|
const InvalidUserPK = -1
|
||||||
|
|
||||||
type UserFlags struct {
|
type UserFlags struct {
|
||||||
UserInfo *api.User
|
UserInfo *api.User
|
||||||
UserPk int32
|
UserPk int32
|
||||||
CanSearch bool
|
CanSearch bool
|
||||||
Session *http.Cookie
|
Session *http.Cookie
|
||||||
|
SessionJWT *jwt.Token
|
||||||
|
}
|
||||||
|
|
||||||
|
func (uf UserFlags) SessionID() string {
|
||||||
|
if uf.SessionJWT == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
h := sha256.New()
|
||||||
|
h.Write([]byte(uf.SessionJWT.Claims.(*flow.SessionCookieClaims).SessionID))
|
||||||
|
return hex.EncodeToString(h.Sum(nil))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,21 +18,26 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type LDAPServer struct {
|
type LDAPServer struct {
|
||||||
s *ldap.Server
|
s *ldap.Server
|
||||||
log *log.Entry
|
log *log.Entry
|
||||||
ac *ak.APIController
|
ac *ak.APIController
|
||||||
cs *ak.CryptoStore
|
cs *ak.CryptoStore
|
||||||
defaultCert *tls.Certificate
|
defaultCert *tls.Certificate
|
||||||
providers []*ProviderInstance
|
providers []*ProviderInstance
|
||||||
|
connections map[string]net.Conn
|
||||||
|
connectionsSync sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(ac *ak.APIController) *LDAPServer {
|
func NewServer(ac *ak.APIController) ak.Outpost {
|
||||||
ls := &LDAPServer{
|
ls := &LDAPServer{
|
||||||
log: log.WithField("logger", "authentik.outpost.ldap"),
|
log: log.WithField("logger", "authentik.outpost.ldap"),
|
||||||
ac: ac,
|
ac: ac,
|
||||||
cs: ak.NewCryptoStore(ac.Client.CryptoApi),
|
cs: ak.NewCryptoStore(ac.Client.CryptoApi),
|
||||||
providers: []*ProviderInstance{},
|
providers: []*ProviderInstance{},
|
||||||
|
connections: map[string]net.Conn{},
|
||||||
|
connectionsSync: sync.Mutex{},
|
||||||
}
|
}
|
||||||
|
ac.AddEventHandler(ls.handleWSSessionEnd)
|
||||||
s := ldap.NewServer()
|
s := ldap.NewServer()
|
||||||
s.EnforceLDAP = true
|
s.EnforceLDAP = true
|
||||||
|
|
||||||
@ -50,6 +55,7 @@ func NewServer(ac *ak.APIController) *LDAPServer {
|
|||||||
s.BindFunc("", ls)
|
s.BindFunc("", ls)
|
||||||
s.UnbindFunc("", ls)
|
s.UnbindFunc("", ls)
|
||||||
s.SearchFunc("", ls)
|
s.SearchFunc("", ls)
|
||||||
|
s.CloseFunc("", ls)
|
||||||
return ls
|
return ls
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -117,3 +123,23 @@ func (ls *LDAPServer) TimerFlowCacheExpiry(ctx context.Context) {
|
|||||||
p.binder.TimerFlowCacheExpiry(ctx)
|
p.binder.TimerFlowCacheExpiry(ctx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ls *LDAPServer) handleWSSessionEnd(ctx context.Context, msg ak.Event) error {
|
||||||
|
if msg.Instruction != ak.EventKindSessionEnd {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
mmsg := ak.EventArgsSessionEnd{}
|
||||||
|
err := msg.ArgsAs(&mmsg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ls.connectionsSync.Lock()
|
||||||
|
defer ls.connectionsSync.Unlock()
|
||||||
|
ls.log.Info("Disconnecting session due to session end event")
|
||||||
|
conn, ok := ls.connections[mmsg.SessionID]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
delete(ls.connections, mmsg.SessionID)
|
||||||
|
return conn.Close()
|
||||||
|
}
|
||||||
|
|||||||
@ -44,38 +44,40 @@ func (ds *DirectSearcher) SearchSubschema(req *search.Request) (ldap.ServerSearc
|
|||||||
{
|
{
|
||||||
Name: "attributeTypes",
|
Name: "attributeTypes",
|
||||||
Values: []string{
|
Values: []string{
|
||||||
"( 2.5.4.0 NAME 'objectClass' SYNTAX '1.3.6.1.4.1.1466.115.121.1.38' NO-USER-MODIFICATION )",
|
|
||||||
"( 2.5.4.4 NAME 'sn' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.3 NAME 'cn' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.6 NAME 'c' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.7 NAME 'l' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.10 NAME 'o' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
|
||||||
"( 2.5.4.11 NAME 'ou' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
|
||||||
"( 2.5.4.12 NAME 'title' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.13 NAME 'description' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
|
||||||
"( 2.5.4.20 NAME 'telephoneNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.4.31 NAME 'member' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' )",
|
|
||||||
"( 2.5.4.42 NAME 'givenName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 2.5.21.2 NAME 'dITContentRules' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
|
||||||
"( 2.5.21.5 NAME 'attributeTypes' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
|
||||||
"( 2.5.21.6 NAME 'objectClasses' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
|
||||||
"( 0.9.2342.19200300.100.1.1 NAME 'uid' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 0.9.2342.19200300.100.1.1 NAME 'uid' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 0.9.2342.19200300.100.1.3 NAME 'mail' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 0.9.2342.19200300.100.1.3 NAME 'mail' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 0.9.2342.19200300.100.1.41 NAME 'mobile' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 0.9.2342.19200300.100.1.41 NAME 'mobile' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.2.13 NAME 'displayName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 1.2.840.113556.1.2.146 NAME 'company' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 1.2.840.113556.1.2.102 NAME 'memberOf' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' NO-USER-MODIFICATION )",
|
"( 1.2.840.113556.1.2.102 NAME 'memberOf' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' NO-USER-MODIFICATION )",
|
||||||
|
"( 1.2.840.113556.1.2.13 NAME 'displayName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.2.131 NAME 'co' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.2.131 NAME 'co' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.2.141 NAME 'department' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.2.141 NAME 'department' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 1.2.840.113556.1.2.146 NAME 'company' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.4.1 NAME 'name' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE NO-USER-MODIFICATION )",
|
"( 1.2.840.113556.1.4.1 NAME 'name' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE NO-USER-MODIFICATION )",
|
||||||
"( 1.2.840.113556.1.4.44 NAME 'homeDirectory' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
|
||||||
"( 1.2.840.113556.1.4.221 NAME 'sAMAccountName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.4.221 NAME 'sAMAccountName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.4.261 NAME 'division' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.4.261 NAME 'division' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 1.2.840.113556.1.4.44 NAME 'homeDirectory' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.4.750 NAME 'groupType' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.4.750 NAME 'groupType' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
||||||
"( 1.2.840.113556.1.4.782 NAME 'objectCategory' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' SINGLE-VALUE )",
|
"( 1.2.840.113556.1.4.782 NAME 'objectCategory' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' SINGLE-VALUE )",
|
||||||
"( 1.3.6.1.1.1.1.0 NAME 'uidNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
"( 1.3.6.1.1.1.1.0 NAME 'uidNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
||||||
"( 1.3.6.1.1.1.1.1 NAME 'gidNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
"( 1.3.6.1.1.1.1.1 NAME 'gidNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )",
|
||||||
"( 1.3.6.1.1.1.1.12 NAME 'memberUid' SYNTAX '1.3.6.1.4.1.1466.115.121.1.26' )",
|
"( 1.3.6.1.1.1.1.12 NAME 'memberUid' SYNTAX '1.3.6.1.4.1.1466.115.121.1.26' )",
|
||||||
|
"( 2.5.18.1 NAME 'createTimestamp' SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.18.2 NAME 'modifyTimestamp' SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 SINGLE-VALUE NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.21.2 NAME 'dITContentRules' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.21.5 NAME 'attributeTypes' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.21.6 NAME 'objectClasses' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.4.0 NAME 'objectClass' SYNTAX '1.3.6.1.4.1.1466.115.121.1.38' NO-USER-MODIFICATION )",
|
||||||
|
"( 2.5.4.10 NAME 'o' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
||||||
|
"( 2.5.4.11 NAME 'ou' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
||||||
|
"( 2.5.4.12 NAME 'title' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.13 NAME 'description' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' )",
|
||||||
|
"( 2.5.4.20 NAME 'telephoneNumber' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.3 NAME 'cn' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.31 NAME 'member' SYNTAX '1.3.6.1.4.1.1466.115.121.1.12' )",
|
||||||
|
"( 2.5.4.4 NAME 'sn' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.42 NAME 'givenName' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.6 NAME 'c' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
"( 2.5.4.7 NAME 'l' SYNTAX '1.3.6.1.4.1.1466.115.121.1.15' SINGLE-VALUE )",
|
||||||
|
|
||||||
// Custom attributes
|
// Custom attributes
|
||||||
// Temporarily use 1.3.6.1.4.1.26027.1.1 as a base
|
// Temporarily use 1.3.6.1.4.1.26027.1.1 as a base
|
||||||
|
|||||||
@ -53,6 +53,14 @@ func NewRequest(bindDN string, searchReq ldap.SearchRequest, conn net.Conn) (*Re
|
|||||||
if err != nil && len(searchReq.Filter) > 0 {
|
if err != nil && len(searchReq.Filter) > 0 {
|
||||||
l.WithError(err).WithField("objectClass", filterOC).Warning("invalid filter object class")
|
l.WithError(err).WithField("objectClass", filterOC).Warning("invalid filter object class")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle comma-separated attributes
|
||||||
|
normalizedAttributes := normalizeAttributes(searchReq.Attributes)
|
||||||
|
if len(normalizedAttributes) != len(searchReq.Attributes) {
|
||||||
|
// Create a copy of the search request with normalized attributes
|
||||||
|
searchReq.Attributes = normalizedAttributes
|
||||||
|
}
|
||||||
|
|
||||||
return &Request{
|
return &Request{
|
||||||
SearchRequest: searchReq,
|
SearchRequest: searchReq,
|
||||||
BindDN: bindDN,
|
BindDN: bindDN,
|
||||||
@ -64,6 +72,31 @@ func NewRequest(bindDN string, searchReq ldap.SearchRequest, conn net.Conn) (*Re
|
|||||||
}, span
|
}, span
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// normalizeAttributes handles the case where attributes might be passed as comma-separated strings
|
||||||
|
// rather than as individual array elements
|
||||||
|
func normalizeAttributes(attributes []string) []string {
|
||||||
|
if len(attributes) == 0 {
|
||||||
|
return attributes
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make([]string, 0, len(attributes))
|
||||||
|
for _, attr := range attributes {
|
||||||
|
if strings.Contains(attr, ",") {
|
||||||
|
// Split comma-separated attributes and add them individually
|
||||||
|
parts := strings.Split(attr, ",")
|
||||||
|
for _, part := range parts {
|
||||||
|
part = strings.TrimSpace(part)
|
||||||
|
if part != "" {
|
||||||
|
result = append(result, part)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result = append(result, attr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Request) Context() context.Context {
|
func (r *Request) Context() context.Context {
|
||||||
return r.ctx
|
return r.ctx
|
||||||
}
|
}
|
||||||
|
|||||||
98
internal/outpost/ldap/search/request_test.go
Normal file
98
internal/outpost/ldap/search/request_test.go
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
package search
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNormalizeAttributes(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
input []string
|
||||||
|
expectedOutput []string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "Empty input",
|
||||||
|
input: []string{},
|
||||||
|
expectedOutput: []string{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "No commas",
|
||||||
|
input: []string{"uid", "cn", "sn"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Single comma-separated string",
|
||||||
|
input: []string{"uid,cn,sn"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Mixed input",
|
||||||
|
input: []string{"uid,cn", "sn"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "With spaces",
|
||||||
|
input: []string{"uid, cn, sn"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Empty parts",
|
||||||
|
input: []string{"uid,, cn"},
|
||||||
|
expectedOutput: []string{"uid", "cn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Single element",
|
||||||
|
input: []string{"uid"},
|
||||||
|
expectedOutput: []string{"uid"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Only commas",
|
||||||
|
input: []string{",,,"},
|
||||||
|
expectedOutput: []string{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Multiple comma-separated attributes",
|
||||||
|
input: []string{"uid,cn", "sn,mail", "givenName"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn", "mail", "givenName"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Case preservation",
|
||||||
|
input: []string{"uid,CN,sAMAccountName"},
|
||||||
|
expectedOutput: []string{"uid", "CN", "sAMAccountName"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Leading and trailing spaces",
|
||||||
|
input: []string{" uid , cn , sn "},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Real-world LDAP attribute examples",
|
||||||
|
input: []string{"objectClass,memberOf,mail", "sAMAccountName,userPrincipalName"},
|
||||||
|
expectedOutput: []string{"objectClass", "memberOf", "mail", "sAMAccountName", "userPrincipalName"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Jira-style attribute format",
|
||||||
|
input: []string{"uid,cn,sn"},
|
||||||
|
expectedOutput: []string{"uid", "cn", "sn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Single string with single attribute",
|
||||||
|
input: []string{"cn"},
|
||||||
|
expectedOutput: []string{"cn"},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Mix of standard and operational attributes",
|
||||||
|
input: []string{"uid,+", "createTimestamp"},
|
||||||
|
expectedOutput: []string{"uid", "+", "createTimestamp"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result := normalizeAttributes(tt.input)
|
||||||
|
assert.Equal(t, tt.expectedOutput, result)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -5,6 +5,7 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -118,8 +119,8 @@ func NewApplication(p api.ProxyOutpostConfig, c *http.Client, server Server, old
|
|||||||
mux := mux.NewRouter()
|
mux := mux.NewRouter()
|
||||||
|
|
||||||
// Save cookie name, based on hashed client ID
|
// Save cookie name, based on hashed client ID
|
||||||
h := sha256.New()
|
hs := sha256.Sum256([]byte(*p.ClientId))
|
||||||
bs := string(h.Sum([]byte(*p.ClientId)))
|
bs := hex.EncodeToString(hs[:])
|
||||||
sessionName := fmt.Sprintf("authentik_proxy_%s", bs[:8])
|
sessionName := fmt.Sprintf("authentik_proxy_%s", bs[:8])
|
||||||
|
|
||||||
// When HOST_BROWSER is set, use that as Host header for token requests to make the issuer match
|
// When HOST_BROWSER is set, use that as Host header for token requests to make the issuer match
|
||||||
|
|||||||
@ -3,6 +3,7 @@ package application
|
|||||||
type ProxyClaims struct {
|
type ProxyClaims struct {
|
||||||
UserAttributes map[string]interface{} `json:"user_attributes"`
|
UserAttributes map[string]interface{} `json:"user_attributes"`
|
||||||
BackendOverride string `json:"backend_override"`
|
BackendOverride string `json:"backend_override"`
|
||||||
|
HostHeader string `json:"host_header"`
|
||||||
IsSuperuser bool `json:"is_superuser"`
|
IsSuperuser bool `json:"is_superuser"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -74,13 +74,18 @@ func (a *Application) proxyModifyRequest(ou *url.URL) func(req *http.Request) {
|
|||||||
r.URL.Scheme = ou.Scheme
|
r.URL.Scheme = ou.Scheme
|
||||||
r.URL.Host = ou.Host
|
r.URL.Host = ou.Host
|
||||||
claims := a.getClaimsFromSession(r)
|
claims := a.getClaimsFromSession(r)
|
||||||
if claims != nil && claims.Proxy != nil && claims.Proxy.BackendOverride != "" {
|
if claims != nil && claims.Proxy != nil {
|
||||||
u, err := url.Parse(claims.Proxy.BackendOverride)
|
if claims.Proxy.BackendOverride != "" {
|
||||||
if err != nil {
|
u, err := url.Parse(claims.Proxy.BackendOverride)
|
||||||
a.log.WithField("backend_override", claims.Proxy.BackendOverride).WithError(err).Warning("failed parse user backend override")
|
if err != nil {
|
||||||
} else {
|
a.log.WithField("backend_override", claims.Proxy.BackendOverride).WithError(err).Warning("failed parse user backend override")
|
||||||
r.URL.Scheme = u.Scheme
|
} else {
|
||||||
r.URL.Host = u.Host
|
r.URL.Scheme = u.Scheme
|
||||||
|
r.URL.Host = u.Host
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if claims.Proxy.HostHeader != "" {
|
||||||
|
r.Host = claims.Proxy.HostHeader
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
a.log.WithField("upstream_url", r.URL.String()).Trace("final upstream url")
|
a.log.WithField("upstream_url", r.URL.String()).Trace("final upstream url")
|
||||||
|
|||||||
@ -35,7 +35,7 @@ type ProxyServer struct {
|
|||||||
akAPI *ak.APIController
|
akAPI *ak.APIController
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxyServer(ac *ak.APIController) *ProxyServer {
|
func NewProxyServer(ac *ak.APIController) ak.Outpost {
|
||||||
l := log.WithField("logger", "authentik.outpost.proxyv2")
|
l := log.WithField("logger", "authentik.outpost.proxyv2")
|
||||||
defaultCert, err := crypto.GenerateSelfSignedCert()
|
defaultCert, err := crypto.GenerateSelfSignedCert()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -66,7 +66,7 @@ func NewProxyServer(ac *ak.APIController) *ProxyServer {
|
|||||||
globalMux.PathPrefix("/outpost.goauthentik.io/static").HandlerFunc(s.HandleStatic)
|
globalMux.PathPrefix("/outpost.goauthentik.io/static").HandlerFunc(s.HandleStatic)
|
||||||
globalMux.Path("/outpost.goauthentik.io/ping").HandlerFunc(sentryutils.SentryNoSample(s.HandlePing))
|
globalMux.Path("/outpost.goauthentik.io/ping").HandlerFunc(sentryutils.SentryNoSample(s.HandlePing))
|
||||||
rootMux.PathPrefix("/").HandlerFunc(s.Handle)
|
rootMux.PathPrefix("/").HandlerFunc(s.Handle)
|
||||||
ac.AddWSHandler(s.handleWSMessage)
|
ac.AddEventHandler(s.handleWSMessage)
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user