mirror of
https://github.com/tinyauthapp/tinyauth.git
synced 2026-08-12 12:03:31 +08:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc56ff7bf6 | ||
|
|
ad700e75e0 | ||
|
|
6d5563db2c | ||
|
|
cbd92a1104 | ||
|
|
470b596281 | ||
|
|
efcb1b64ea | ||
|
|
04eb1feb34 | ||
|
|
8f029b45ad | ||
|
|
8ff7a8597d | ||
|
|
a2c1ea865d | ||
|
|
2d19d5c3d4 | ||
|
|
1db1714971 | ||
|
|
c7077a7c84 | ||
|
|
80bc87188e | ||
|
|
0e7bdf6cd5 | ||
|
|
4db1b33034 | ||
|
|
f6637c0f65 | ||
|
|
f43d690320 | ||
|
|
50c25e4478 | ||
|
|
d6087dc45e | ||
|
|
6efb970673 | ||
|
|
a9221ece92 | ||
|
|
d5b7e60362 | ||
|
|
4d8cd86eec | ||
|
|
504866a432 | ||
|
|
0c1a64d47d | ||
|
|
a79438d6ec | ||
|
|
286aad2e08 | ||
|
|
5091fc2d7a | ||
|
|
0fc87ad58f | ||
|
|
a7eba59a42 | ||
|
|
ac8703eadb | ||
|
|
04a06ec5ff | ||
|
|
3cf3cc9090 | ||
|
|
589fe22138 | ||
|
|
1165c91fcc | ||
|
|
84117ce109 | ||
|
|
9eabfe89fd | ||
|
|
dade1e2c8f | ||
|
|
6e095fd4f2 | ||
|
|
2a0d7bd37a | ||
|
|
c22925c2fb | ||
|
|
d946926c36 | ||
|
|
8881116360 | ||
|
|
e75605b2c5 | ||
|
|
79bcccbe43 | ||
|
|
b62bb2d37a | ||
|
|
791adbb54d | ||
|
|
4cd4d67bda |
+11
-6
@@ -4,6 +4,10 @@
|
||||
|
||||
# The base URL where the app is hosted.
|
||||
TINYAUTH_APPURL=
|
||||
# Path to config file.
|
||||
TINYAUTH_CONFIGFILE=
|
||||
# Label provider to use for ACLs (auto, docker, kubernetes or none to disable). auto detects the environment.
|
||||
TINYAUTH_LABELPROVIDER="auto"
|
||||
|
||||
# database config
|
||||
|
||||
@@ -97,8 +101,6 @@ TINYAUTH_AUTH_SESSIONMAXLIFETIME=0
|
||||
TINYAUTH_AUTH_LOGINTIMEOUT=300
|
||||
# Maximum login retries.
|
||||
TINYAUTH_AUTH_LOGINMAXRETRIES=3
|
||||
# Enable lockdown mode after maximum login retries. Lockdown mode limit is calculated automatically.
|
||||
TINYAUTH_AUTH_LOCKDOWNENABLED=true
|
||||
# Comma-separated list of trusted proxy addresses.
|
||||
TINYAUTH_AUTH_TRUSTEDPROXIES=
|
||||
# ACL policy for allow-by-default or deny-by-default, available options are allow and deny, default is allow.
|
||||
@@ -130,9 +132,9 @@ TINYAUTH_APPS_name_RESPONSE_BASICAUTH_USERNAME=
|
||||
TINYAUTH_APPS_name_RESPONSE_BASICAUTH_PASSWORD=
|
||||
# Path to the file containing the basic auth password.
|
||||
TINYAUTH_APPS_name_RESPONSE_BASICAUTH_PASSWORDFILE=
|
||||
# Comma-separated list of allowed paths.
|
||||
# Disable authentication for only paths that match the regex string.
|
||||
TINYAUTH_APPS_name_PATH_ALLOW=
|
||||
# Comma-separated list of blocked paths.
|
||||
# Enable authentication for only paths that match the regex string.
|
||||
TINYAUTH_APPS_name_PATH_BLOCK=
|
||||
# Comma-separated list of required LDAP groups.
|
||||
TINYAUTH_APPS_name_LDAP_GROUPS=
|
||||
@@ -221,6 +223,11 @@ TINYAUTH_LDAP_AUTHKEY=
|
||||
# Cache duration for LDAP group membership in seconds.
|
||||
TINYAUTH_LDAP_GROUPCACHETTL=900
|
||||
|
||||
# experimental config
|
||||
|
||||
# Enable the OAuth bridge, uses a new way to format OAuth user information.
|
||||
TINYAUTH_EXPERIMENTAL_OAUTHBRIDGEENABLED=false
|
||||
|
||||
# tailscale config
|
||||
|
||||
# Enable Tailscale integration.
|
||||
@@ -233,8 +240,6 @@ TINYAUTH_TAILSCALE_APITOKENFILE=
|
||||
TINYAUTH_TAILSCALE_TAILNET=
|
||||
# Cache duration for Tailscale device and user lists in seconds.
|
||||
TINYAUTH_TAILSCALE_CACHEDURATION=300
|
||||
# Label provider to use for ACLs (auto, docker, kubernetes or none to disable). auto detects the environment.
|
||||
TINYAUTH_LABELPROVIDER="auto"
|
||||
|
||||
# log config
|
||||
|
||||
|
||||
@@ -9,8 +9,6 @@ updates:
|
||||
- "minor"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
cooldown:
|
||||
default-days: 1
|
||||
|
||||
- package-ecosystem: "gomod"
|
||||
directory: "/"
|
||||
@@ -21,19 +19,13 @@ updates:
|
||||
- "minor"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
cooldown:
|
||||
default-days: 1
|
||||
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
cooldown:
|
||||
default-days: 1
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
cooldown:
|
||||
default-days: 1
|
||||
interval: "daily"
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
@@ -21,7 +21,7 @@ jobs:
|
||||
package_json_file: ./frontend/package.json
|
||||
|
||||
- name: Setup go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "^1.26.4"
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Delete old release
|
||||
run: gh release delete --cleanup-tag --yes nightly || echo release not found
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
REPO: ${{ github.event.repository.name }}
|
||||
|
||||
- name: Create release
|
||||
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
prerelease: true
|
||||
tag_name: nightly
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
BUILD_TAGS: ${{ steps.metadata.outputs.BUILD_TAGS }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
package_json_file: ./frontend/package.json
|
||||
|
||||
- name: Install go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "^1.26.4"
|
||||
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -117,7 +117,7 @@ jobs:
|
||||
package_json_file: ./frontend/package.json
|
||||
|
||||
- name: Install go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "^1.26.4"
|
||||
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -167,7 +167,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -215,7 +215,7 @@ jobs:
|
||||
- image-build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -226,7 +226,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -274,7 +274,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -285,7 +285,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -333,7 +333,7 @@ jobs:
|
||||
- image-build-arm
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: nightly
|
||||
|
||||
@@ -344,7 +344,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -399,7 +399,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -438,7 +438,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -476,7 +476,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
files: binaries/*
|
||||
tag_name: nightly
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
BUILD_TAGS: ${{ steps.metadata.outputs.BUILD_TAGS }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Generate metadata
|
||||
id: metadata
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
package_json_file: ./frontend/package.json
|
||||
|
||||
- name: Install go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "^1.26.4"
|
||||
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
package_json_file: ./frontend/package.json
|
||||
|
||||
- name: Install go
|
||||
uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||
with:
|
||||
go-version: "^1.26.4"
|
||||
|
||||
@@ -130,7 +130,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
@@ -139,7 +139,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -187,7 +187,7 @@ jobs:
|
||||
- image-build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
@@ -196,7 +196,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -244,7 +244,7 @@ jobs:
|
||||
- generate-metadata
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
@@ -253,7 +253,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -301,7 +301,7 @@ jobs:
|
||||
- image-build-arm
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
@@ -310,7 +310,7 @@ jobs:
|
||||
images: ghcr.io/${{ github.repository_owner }}/tinyauth
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -366,7 +366,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -407,7 +407,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
@@ -449,6 +449,6 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
files: binaries/*
|
||||
|
||||
@@ -19,12 +19,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Run analysis
|
||||
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a
|
||||
uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc
|
||||
with:
|
||||
results_file: results.sarif
|
||||
results_format: sarif
|
||||
@@ -38,6 +38,6 @@ jobs:
|
||||
retention-days: 5
|
||||
|
||||
- name: Upload to code-scanning
|
||||
uses: github/codeql-action/upload-sarif@99df26d4f13ea111d4ec1a7dddef6063f76b97e9 # v4
|
||||
uses: github/codeql-action/upload-sarif@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
|
||||
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Generate Sponsors
|
||||
uses: JamesIves/github-sponsors-readme-action@2fd9142e765f755780202122261dc85e78459405 # v1
|
||||
|
||||
+4
-1
@@ -50,7 +50,10 @@ __debug_*
|
||||
config.certify.yml
|
||||
|
||||
# deepsec
|
||||
/.deepsec
|
||||
/.deepsec/
|
||||
|
||||
# jetbrains
|
||||
/.idea/
|
||||
|
||||
# claude stuff
|
||||
/.claude/
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
# Agents
|
||||
|
||||
*This file is written by Humans for Agents.*
|
||||
|
||||
## Overview
|
||||
|
||||
Tinyauth is a lightweight and open-source authentication server written in Go and TypeScript (React). It acts as either an authentication middleware (forward_auth, ext_authz or auth_request) to protect applications using proxy authentication or as an OpenID Connect provider to offer SSO (Single-Sign-On) to your self-hosted apps. It supports 2FA (via TOTP), LDAP, access controls (ACLs), local users and SSO users via OAuth. Tinyauth can be deployed with Docker, Kubernetes or bare-metal with a binary.
|
||||
|
||||
## Considerations
|
||||
|
||||
- The repository we are working at is `https://github.com/tinyauthapp/tinyauth`.
|
||||
- ALWAYS follow the instructions for committing and creating a pull request as mentioned below.
|
||||
|
||||
## Philosophy
|
||||
|
||||
Tinyauth is designed to run with simplicity in mind. This is why we try to avoid adding unnecessary persistent storage and configuration options.
|
||||
|
||||
Tinyauth can run without persistent storage and the SQLite database is only used for storing normal or OpenID Connect sessions. You MUST never store data in the database that are required for Tinyauth function.
|
||||
|
||||
As for the configuration, we support environment variables, CLI flags and a YAML configuration file. We try to keep the required configuration at a minimal with sane defaults so users can spend the least amount of time configuring Tinyauth.
|
||||
|
||||
We NEVER create a breaking change unless absolutely necessary and only if non-breaking changes have been discussed and deemed not ideal.
|
||||
|
||||
## Technical Overview
|
||||
|
||||
Tinyauth is designed to be as modular as possible. We utilize a repository-service-controller structure where each service/controller/middleware defines its dependencies in a Dig input struct and then the main bootstrap entrypoint dynamically injects the dependencies to each method.
|
||||
|
||||
All methods share one global static config struct which contains the user configuration as is, and a runtime config struct that contains dynamically generated values on startup. If a method needs a modified version, it MUST never modify the global configuration struct but rather create a local copy.
|
||||
|
||||
We write database migrations by hand. Migrations go in the respective database directory inside the `assets/migrations` directory and follow the `000001_migration_name_in_snake_case.sql` format where the 6 digit number is incremented on each new migration. The repository is automatically generated from SQL queries, SQLC and our own custom generator that unifies each SQLC package into one repository interface. Always ensure that migrations and queries exist for all available database drivers else our store generation will fail. After adding your migrations and queries, run the SQLC code-gen with `make sql` and update the store code-gen with `make generate`. DO NOT EDIT the automatically generated files from SQLC or our store generator, they are marked.
|
||||
|
||||
When updating translations, you should only update the `frontend/src/lib/i18n/locales/en.json` and `frontend/src/lib/i18n/locales/en-US.json` files (they should be exactly the same). Crowdin will handle the generation of the keys for the rest of the available locales. NEVER hard-code plain English in the frontend, instead use the available `i18next` library and the respective translations.
|
||||
|
||||
For the REST framework we use Gin. However functions or methods should avoid using the Gin Context (`gin.Context`) and default to stdlib arguments and outputs. The Gin Context is compatible with all stdlib declarations so it will not pose any issues with them.
|
||||
|
||||
When you need to log in the backend, use the injected logger, NOT the global zerolog struct.
|
||||
|
||||
In case you need toolchain versions, you can find the Node + Go version in the `Dockerfile` and the PNPM version in the `package.json` file inside the `frontend` directory.
|
||||
|
||||
Tinyauth uses Semantic Versioning (SemVer) for versions.
|
||||
|
||||
## File structure
|
||||
|
||||
Tinyauth is composed of two parts, the React frontend and the Go backend.
|
||||
|
||||
A high level of the backend is as follows:
|
||||
|
||||
```
|
||||
internal
|
||||
├── assets # Contains the embedded assets
|
||||
│ ├── dist # Dist is the compiled frontend
|
||||
│ └── migrations # Migrations in SQL for all supported databases
|
||||
│ ├── postgres
|
||||
│ └── sqlite
|
||||
├── bootstrap # The main entrypoint that bootstraps and starts Tinyauth, called by the CLI
|
||||
├── controller # All of the HTTP controllers
|
||||
├── middleware # The HTTP middlewares
|
||||
├── model # Configuration schemas
|
||||
├── repository # Repository holds all of the queries used by the services, each child-repository implements the store interface
|
||||
│ ├── memory
|
||||
│ ├── postgres
|
||||
│ └── sqlite
|
||||
├── service # The services that handle the underlying logic for the controllers
|
||||
├── test # Creates any necessary package-wide configurations and helpers used by tests
|
||||
└── utils # Small helpers and utils used by the app
|
||||
├── decoders # Wrappers around paerser decoders such as the label decoder
|
||||
├── loaders # The env, cli and YAML wrappers around the paerser loaders
|
||||
└── logger # A wrapper around the zerolog logging library
|
||||
```
|
||||
|
||||
Same for the frontend:
|
||||
|
||||
```
|
||||
frontend/src
|
||||
├── components # Different components used by the pages
|
||||
│ ├── auth # Forms used for authentication
|
||||
│ ├── domain-warning # Domain warning when configured domain and actual domain don't match
|
||||
│ ├── icons # Hardcoded SVG icons for OAuth providers
|
||||
│ ├── layout # Main frontend layout
|
||||
│ ├── providers # Different state providers such as theme
|
||||
│ ├── quick-actions # The top right quick settings menu
|
||||
│ └── ui # ShadCN based UI components
|
||||
├── context # Holds and provides the app and user context
|
||||
├── lib # Helpers used by the pages
|
||||
│ ├── hooks # Hooks around the query parameters
|
||||
│ └── i18n # Holds translation logic
|
||||
│ └── locales # The raw JSON locales provided by Crowdin
|
||||
├── pages # The actual app pages
|
||||
└── schemas # Different schemas, mostly used for fetching data from the backend
|
||||
```
|
||||
|
||||
## Make recipes
|
||||
|
||||
Tinyauth utilizes a Makefile for simplifying development. A reference of the available recipes can be found below:
|
||||
|
||||
- `deps` - Install the frontend and backend dependencies.
|
||||
- `clean-data` - Clean any data created by running Tinyauth.
|
||||
- `clean-webui` - Clean frontend build output.
|
||||
- `webui` - Compile the WebUI.
|
||||
- `binary` - Compile the binary for the current system.
|
||||
- `binary-linux-amd64` - Compile the binary for Linux amd64.
|
||||
- `binary-linux-arm64` - Compile the binary for Linux arm64.
|
||||
- `test` - Test the Go backend.
|
||||
- `vet` - Vet the Go backend.
|
||||
- `test-race` - Test the Go backend with the race detector enabled.
|
||||
- `dev` - Start the Docker-based development server.
|
||||
- `prod` - Start the Docker-based production deployment (used for testing pre-releases).
|
||||
- `sql` - Generate the SQLC repositories.
|
||||
- `generate` - Update Go code-gen.
|
||||
- `docker` - Build the Docker image for the current system.
|
||||
- `docker-distroless` - Build the distroless Docker image for the current system.
|
||||
- `lint-webui` - Lint the frontend with ESLint.
|
||||
- `fmt` - Format the Go code with the Go `fmt` tool.
|
||||
|
||||
## Development lifecycle
|
||||
|
||||
Development of Tinyauth happens inside two Docker containers. The backend is built automatically by air using a template build output for the frontend. The frontend is run with PNPM and then backend requests are routed with the help of Vite's proxy.
|
||||
|
||||
When developing, you should default to the `make dev` command in order to start everything in Docker and avoid platform-specific issues. If you need to test the CLI, use the `make binary` command.
|
||||
|
||||
After finishing with the development, test and vet the backend with `make test` and `make vet` respectively. If you believe you need to test for race conditions, use `make test-race`. You can also test specific parts of the code using the normal `go test` command, for example to run the `TestHealthController` test, you can use `go test ./internal/controller/ -run TestHealthController -v`. Finally format the Go code with `make fmt`.
|
||||
|
||||
If you made any changes to the frontend, make sure to lint with `make lint-webui`.
|
||||
|
||||
NEVER run any destructive commands like `make clean-data` or delete any configurations without the user's approval.
|
||||
|
||||
## Creating a pull request
|
||||
|
||||
When committing you MUST use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0) standard for your commit messages. You can add a commit description if you like. You MUST also use your standard noreply Co-Author trailer.
|
||||
|
||||
You should work in separate branches unless it's clearly specified to work in the main branch. When working in a separate branch, follow the naming convention below:
|
||||
|
||||
```
|
||||
[feat/refactor/fix/tests/docs/deps/etc]/[small-change-description-in-kebab-case]
|
||||
```
|
||||
|
||||
For example, if your change was to add OAuth to Tinyauth, the branch would look as follows:
|
||||
|
||||
```
|
||||
feat/oauth
|
||||
```
|
||||
|
||||
Or:
|
||||
|
||||
```
|
||||
feat/add-oauth-support
|
||||
```
|
||||
|
||||
The smaller branch name, the better.
|
||||
|
||||
Finally, when creating the actual pull request and if you have access to the internet/a GitHub tool, you should look if it resolves any open issues and if it does, reference them.
|
||||
@@ -39,6 +39,7 @@ RUN go mod download
|
||||
|
||||
COPY ./cmd ./cmd
|
||||
COPY ./internal ./internal
|
||||
COPY ./pkg ./pkg
|
||||
COPY --from=frontend-builder /frontend/dist ./internal/assets/dist
|
||||
|
||||
RUN CGO_ENABLED=0 go build -tags "${BUILD_TAGS}" -ldflags "${LDFLAGS} \
|
||||
|
||||
@@ -12,6 +12,7 @@ RUN go install github.com/go-delve/delve/cmd/dlv@v1.26.3
|
||||
|
||||
COPY ./cmd ./cmd
|
||||
COPY ./internal ./internal
|
||||
COPY ./pkg ./pkg
|
||||
COPY ./air.toml ./
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
@@ -39,6 +39,7 @@ RUN go mod download
|
||||
|
||||
COPY ./cmd ./cmd/
|
||||
COPY ./internal ./internal
|
||||
COPY ./pkg ./pkg
|
||||
COPY --from=frontend-builder /frontend/dist ./internal/assets/dist
|
||||
|
||||
RUN CGO_ENABLED=0 go build -tags "${BUILD_TAGS}" -ldflags "${LDFLAGS} \
|
||||
|
||||
@@ -78,18 +78,10 @@ test-race:
|
||||
dev:
|
||||
docker compose -f $(DEV_COMPOSE) up --force-recreate --pull=always --remove-orphans --build
|
||||
|
||||
# Development - Infisical
|
||||
dev-infisical:
|
||||
infisical run --env=dev -- docker compose -f $(DEV_COMPOSE) up --force-recreate --pull=always --remove-orphans --build
|
||||
|
||||
# Production
|
||||
prod:
|
||||
docker compose -f $(PROD_COMPOSE) up --force-recreate --pull=always --remove-orphans
|
||||
|
||||
# Production - Infisical
|
||||
prod-infisical:
|
||||
infisical run --env=dev -- docker compose -f $(PROD_COMPOSE) up --force-recreate --pull=always --remove-orphans
|
||||
|
||||
# SQL
|
||||
sql:
|
||||
sqlc generate
|
||||
@@ -115,3 +107,11 @@ docker-distroless:
|
||||
--build-arg=BUILD_TIMESTAMP=$(BUILD_TIMESTAMP) \
|
||||
--build-arg=BUILD_TAGS=$(BUILD_TAGS) \
|
||||
-f Dockerfile.distroless .
|
||||
|
||||
# Lint the frontend
|
||||
lint-webui:
|
||||
cd frontend && pnpm lint
|
||||
|
||||
# Format the code
|
||||
fmt:
|
||||
go fmt ./...
|
||||
@@ -62,28 +62,30 @@ If you like, you can help translate Tinyauth into more languages by visiting the
|
||||
|
||||
Tinyauth is licensed under the GNU Affero General Public License v3.0. TL;DR — You may copy, distribute and modify the software as long as you track changes/dates in source files. Any modifications to or software including (via compiler) AGPL-licensed code must also be made available under the AGPL along with build & install instructions. If you run a modified version over a network, you must also make the source available to the users of that service. For more information about the license check the [license](LICENSE) file.
|
||||
|
||||
|
||||
## Hosting Partners
|
||||
|
||||
If you use one of our partners, you can help support us while getting a great hosting deal.
|
||||
|
||||
<div>
|
||||
<a title="InstaPods" target="_blank" href="https://app.instapods.com/dashboard/pods/create?app=tinyauth&ref=tinyauth"><img src="https://instapods.com/deploy-button.svg"></a>
|
||||
</div>
|
||||
|
||||
## Sponsors
|
||||
|
||||
A big thank you to the following people for providing me with more coffee:
|
||||
A big thank-you to the following individuals and companies
|
||||
for their support for Tinyauth.
|
||||
|
||||
### Individuals
|
||||
|
||||
A huge thank you to [selfh.st](https://selfh.st) for their generous donation to Tinyauth.
|
||||
|
||||
<img alt="selfh.st" width="128" src="https://selfh.st/content/images/size/w640/format/webp/2025/04/selfh-st-logo-white-1.svg">
|
||||
|
||||
---
|
||||
|
||||
<!-- sponsors --><a href="https://github.com/erwinkramer"><img src="https://github.com/erwinkramer.png" width="64px" alt="User avatar: erwinkramer" /></a> <a href="https://github.com/nicotsx"><img src="https://github.com/nicotsx.png" width="64px" alt="User avatar: nicotsx" /></a> <a href="https://github.com/SimpleHomelab"><img src="https://github.com/SimpleHomelab.png" width="64px" alt="User avatar: SimpleHomelab" /></a> <a href="https://github.com/jmadden91"><img src="https://github.com/jmadden91.png" width="64px" alt="User avatar: jmadden91" /></a> <a href="https://github.com/tribor"><img src="https://github.com/tribor.png" width="64px" alt="User avatar: tribor" /></a> <a href="https://github.com/eliasbenb"><img src="https://github.com/eliasbenb.png" width="64px" alt="User avatar: eliasbenb" /></a> <a href="https://github.com/afunworm"><img src="https://github.com/afunworm.png" width="64px" alt="User avatar: afunworm" /></a> <a href="https://github.com/chip-well"><img src="https://github.com/chip-well.png" width="64px" alt="User avatar: chip-well" /></a> <a href="https://github.com/Lancelot-Enguerrand"><img src="https://github.com/Lancelot-Enguerrand.png" width="64px" alt="User avatar: Lancelot-Enguerrand" /></a> <a href="https://github.com/allgoewer"><img src="https://github.com/allgoewer.png" width="64px" alt="User avatar: allgoewer" /></a> <a href="https://github.com/NEANC"><img src="https://github.com/NEANC.png" width="64px" alt="User avatar: NEANC" /></a> <a href="https://github.com/axjab"><img src="https://github.com/axjab.png" width="64px" alt="User avatar: axjab" /></a> <a href="https://github.com/stegratech"><img src="https://github.com/stegratech.png" width="64px" alt="User avatar: stegratech" /></a> <a href="https://github.com/apearson"><img src="https://github.com/apearson.png" width="64px" alt="User avatar: apearson" /></a> <a href="https://github.com/Micky5991"><img src="https://github.com/Micky5991.png" width="64px" alt="User avatar: Micky5991" /></a> <!-- sponsors -->
|
||||
|
||||
### Companies and Organizations
|
||||
|
||||
- [JetBrains for Open-Source](https://jb.gg/OpenSource)
|
||||
- [CodeRabbit AI](https://www.coderabbit.ai)
|
||||
- [Dosu](https://dosu.dev/)
|
||||
- [InstaPods](https://instapods.com) - [Deploy Tinyauth from 3$/month](https://app.instapods.com/dashboard/pods/create?app=tinyauth&ref=tinyauth)
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
- **Freepik** for providing the police hat and badge.
|
||||
- **Renee French** for the original gopher logo.
|
||||
- **Coderabbit AI** for providing free AI code reviews.
|
||||
- **Syrhu** for providing the background image of the app.
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://www.star-history.com/#tinyauthapp/tinyauth&Date)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.6 MiB After Width: | Height: | Size: 3.7 MiB |
@@ -116,11 +116,11 @@ func generateTotpCmd() *cli.Command {
|
||||
userStr := fmt.Sprintf("%s:%s:%s", user.Username, user.Password, user.TOTPSecret)
|
||||
|
||||
fmt.Print("\nOr add the following TOTP secret to your authenticator app: ")
|
||||
fmt.Print(colors.green.Render(secret))
|
||||
fmt.Print(colors.blue.Render(secret))
|
||||
fmt.Print("\n\n")
|
||||
|
||||
fmt.Printf("Finally, add your user '%s' back to your configuration: ", user.Username)
|
||||
fmt.Print(colors.green.Render(userStr))
|
||||
fmt.Print(colors.blue.Render(userStr))
|
||||
fmt.Print("\n")
|
||||
|
||||
return nil
|
||||
|
||||
@@ -32,6 +32,7 @@ func main() {
|
||||
Configuration: tConfig,
|
||||
Resources: loaders,
|
||||
Run: func(_ []string) error {
|
||||
// enable this on experimental features
|
||||
if !reflect.DeepEqual(model.NewDefaultConfiguration(env).Experimental, tConfig.Experimental) {
|
||||
colors := getColors()
|
||||
fmt.Println(colors.yellow.Render("⚠") + " Experimental features are enabled, use with caution. Experimental features may change with each release.")
|
||||
|
||||
+25
-25
@@ -12,49 +12,49 @@
|
||||
},
|
||||
"packageManager": "pnpm@11.1.2",
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.20",
|
||||
"@radix-ui/react-label": "^2.1.11",
|
||||
"@radix-ui/react-select": "^2.3.3",
|
||||
"@radix-ui/react-separator": "^1.1.11",
|
||||
"@radix-ui/react-slot": "^1.3.0",
|
||||
"@tailwindcss/vite": "^4.3.2",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"@hookform/resolvers": "^5.5.7",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.24",
|
||||
"@radix-ui/react-label": "^2.1.15",
|
||||
"@radix-ui/react-select": "^2.3.7",
|
||||
"@radix-ui/react-separator": "^1.1.15",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/react-query": "^5.101.4",
|
||||
"axios": "^1.18.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"i18next": "^26.3.4",
|
||||
"i18next": "^26.3.6",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"i18next-resources-to-backend": "^1.2.1",
|
||||
"lucide-react": "^1.23.0",
|
||||
"i18next-resources-to-backend": "^1.2.2",
|
||||
"lucide-react": "^1.27.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"radix-ui": "^1.6.2",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-hook-form": "^7.81.0",
|
||||
"react-i18next": "^17.0.8",
|
||||
"radix-ui": "^1.6.7",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-hook-form": "^7.83.0",
|
||||
"react-i18next": "^17.0.11",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^8.2.0",
|
||||
"react-router": "^8.3.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tailwindcss": "^4.3.2",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tanstack/eslint-plugin-query": "^5.101.2",
|
||||
"@types/node": "^26.1.1",
|
||||
"@tanstack/eslint-plugin-query": "^5.101.4",
|
||||
"@types/node": "^26.1.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"eslint": "^10.6.0",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"eslint": "^10.8.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"globals": "^17.7.0",
|
||||
"globals": "^17.8.0",
|
||||
"rollup-plugin-visualizer": "^7.0.1",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.63.0",
|
||||
"vite": "^8.1.4"
|
||||
"typescript-eslint": "^8.65.0",
|
||||
"vite": "^8.1.5"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+1092
-1112
File diff suppressed because it is too large
Load Diff
@@ -32,8 +32,8 @@ import { useTranslation } from "react-i18next";
|
||||
import { useLocation } from "react-router";
|
||||
import { useRef } from "react";
|
||||
import {
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
recompileScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
@@ -70,7 +70,13 @@ export const QuickActions = () => {
|
||||
const redirectTimer = useRef<number | null>(null);
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const compiledParams = recompileScreenParams(screenParams);
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
type UseLoginForProps = {
|
||||
login_for?: "oidc" | "app";
|
||||
compiledParams: string;
|
||||
params: URLSearchParams;
|
||||
};
|
||||
|
||||
export const useLoginFor = (props: UseLoginForProps): string => {
|
||||
const { login_for, compiledParams } = props;
|
||||
const { login_for, params } = props;
|
||||
const compiledParams = params.toString() ? "?" + params.toString() : "";
|
||||
|
||||
switch (login_for) {
|
||||
case "oidc":
|
||||
@@ -12,6 +13,9 @@ export const useLoginFor = (props: UseLoginForProps): string => {
|
||||
case "app":
|
||||
return "/continue" + compiledParams;
|
||||
default:
|
||||
if (params.get("redirect_uri")) {
|
||||
return "/continue" + compiledParams
|
||||
}
|
||||
return "/logout";
|
||||
}
|
||||
};
|
||||
|
||||
@@ -75,18 +75,21 @@ export const useRedirectUri = (
|
||||
};
|
||||
};
|
||||
|
||||
// ported from internal/controller/oauth_controller.go
|
||||
const getEffectivePort = (url: URL): string => {
|
||||
if (url.port) {
|
||||
return url.port;
|
||||
}
|
||||
// https://www.geeksforgeeks.org/javascript/how-to-check-if-a-string-is-a-valid-ip-address-format-in-javascript
|
||||
const isIP = (str: string): boolean => {
|
||||
const ipv4 =
|
||||
/^(\d{1,3}\.){3}\d{1,3}$/;
|
||||
const ipv6 =
|
||||
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
||||
return ipv4.test(str) || ipv6.test(str) || str.startsWith("[");
|
||||
}
|
||||
|
||||
if (url.protocol == "https:") {
|
||||
return "443";
|
||||
const trimPeriod = (str: string): string => {
|
||||
if(str.lastIndexOf('.') === (str.length - 1)){
|
||||
str = str.substring(0, str.length - 1);
|
||||
}
|
||||
|
||||
return "80";
|
||||
};
|
||||
return str
|
||||
}
|
||||
|
||||
export const isTrustedDomain = (
|
||||
url: URL,
|
||||
@@ -94,15 +97,15 @@ export const isTrustedDomain = (
|
||||
cookieDomain: string,
|
||||
subdomainsEnabled: boolean,
|
||||
): boolean => {
|
||||
if (url.protocol != appUrl.protocol) {
|
||||
if (isIP(url.hostname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (getEffectivePort(url) != getEffectivePort(appUrl)) {
|
||||
if (url.port != appUrl.port) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (url.hostname == appUrl.hostname) {
|
||||
if (trimPeriod(url.hostname) == trimPeriod(appUrl.hostname)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -110,9 +113,6 @@ export const isTrustedDomain = (
|
||||
return false;
|
||||
}
|
||||
|
||||
if (url.hostname.endsWith("." + cookieDomain.toLowerCase())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return trimPeriod(url.hostname).endsWith("." + cookieDomain.toLowerCase())
|
||||
|| trimPeriod(url.hostname) == cookieDomain.toLowerCase();
|
||||
};
|
||||
|
||||
@@ -27,16 +27,10 @@ export function useScreenParams(params: URLSearchParams): ScreenParams {
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
export function recompileScreenParams(params: ScreenParams): string {
|
||||
const p = new URLSearchParams(
|
||||
export function searchParamsFromObject(obj: object): URLSearchParams {
|
||||
return new URLSearchParams(
|
||||
Object.fromEntries(
|
||||
Object.entries(params).filter(([, v]) => v !== undefined),
|
||||
Object.entries(obj).filter(([, v]) => v !== undefined),
|
||||
) as Record<string, string>,
|
||||
).toString();
|
||||
|
||||
if (p.length > 0) {
|
||||
return "?" + p;
|
||||
}
|
||||
|
||||
return "";
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,16 +15,16 @@
|
||||
"loginOauthSuccessTitle": "Přesměrování",
|
||||
"loginOauthSuccessSubtitle": "Přesměrování k poskytovateli OAuth",
|
||||
"loginOauthAutoRedirectTitle": "Automatické přesměrování OAuth",
|
||||
"loginOauthAutoRedirectSubtitle": "Pro ověření budete automaticky přesměrování na svého poskytovatele OAuth.",
|
||||
"loginOauthAutoRedirectButton": "Přesměrovat nyní",
|
||||
"loginOauthAutoRedirectSubtitle": "You will be automatically redirected to your OAuth provider to authenticate.",
|
||||
"loginOauthAutoRedirectButton": "Redirect now",
|
||||
"continueTitle": "Pokračovat",
|
||||
"continueRedirectingTitle": "Přesměrování...",
|
||||
"continueRedirectingSubtitle": "Brzy budete přesměrováni do aplikace",
|
||||
"continueRedirectManually": "Přesměrovat ručně",
|
||||
"continueRedirectManually": "Redirect me manually",
|
||||
"continueInsecureRedirectTitle": "Nezabezpečené přesměrování",
|
||||
"continueInsecureRedirectSubtitle": "Pokoušíte se přesměrovat z <code>https</code> na <code>http</code>, které není bezpečné. Opravdu chcete pokračovat?",
|
||||
"continueUntrustedRedirectTitle": "Nedůvěryhodné přesměrování",
|
||||
"continueUntrustedRedirectSubtitle": "Pokoušíte se přesměrovat na doménu, která neodpovídá vaší nakonfigurované doméně (<code>{{cookieDomain}}</code>). Opravdu chcete pokračovat?",
|
||||
"continueUntrustedRedirectTitle": "Untrusted redirect",
|
||||
"continueUntrustedRedirectSubtitle": "You are trying to redirect to a domain that does not match your configured domain (<code>{{cookieDomain}}</code>). Are you sure you want to continue?",
|
||||
"logoutFailTitle": "Odhlášení se nezdařilo",
|
||||
"logoutFailSubtitle": "Zkuste to prosím znovu",
|
||||
"logoutSuccessTitle": "Odhlášen",
|
||||
@@ -51,53 +51,53 @@
|
||||
"forgotPasswordTitle": "Zapomněli jste heslo?",
|
||||
"failedToFetchProvidersTitle": "Nepodařilo se načíst poskytovatele ověřování. Zkontrolujte prosím konfiguraci.",
|
||||
"errorTitle": "Došlo k chybě",
|
||||
"errorSubtitleInfo": "Při zpracování požadavku došlo k následující chybě:",
|
||||
"errorSubtitleInfo": "The following error occurred while processing your request:",
|
||||
"errorSubtitle": "Nastala chyba při pokusu o provedení této akce. Pro více informací prosím zkontrolujte konzolu.",
|
||||
"forgotPasswordMessage": "Heslo můžete obnovit změnou proměnné `USERS`.",
|
||||
"fieldRequired": "Toto pole je povinné",
|
||||
"invalidInput": "Neplatný údaj",
|
||||
"domainWarningTitle": "Neplatná doména",
|
||||
"domainWarningSubtitle": "Pro přístup k této instanci používáte špatnou doménu. Při pokračování mohou nastat problémy s autentizací.",
|
||||
"domainWarningCurrent": "Aktuální:",
|
||||
"domainWarningExpected": "Vyžadovaná:",
|
||||
"ignoreTitle": "Ignorovat",
|
||||
"goToCorrectDomainTitle": "Přejít na správnou doménu",
|
||||
"authorizeTitle": "Autorizovat",
|
||||
"authorizeCardTitle": "Pokračovat do {{app}}?",
|
||||
"authorizeSubtitle": "Chcete pokračovat do této aplikace? Pečlivě si zkontrolujte jí vyžadovaná oprávnění, prosím.",
|
||||
"authorizeSubtitleOAuth": "Chcete pokračovat do této aplikace?",
|
||||
"authorizeLoadingTitle": "Načítání...",
|
||||
"domainWarningTitle": "Invalid Domain",
|
||||
"domainWarningSubtitle": "You are accessing this instance from an incorrect domain. If you proceed, you may encounter issues with authentication.",
|
||||
"domainWarningCurrent": "Current:",
|
||||
"domainWarningExpected": "Expected:",
|
||||
"ignoreTitle": "Ignore",
|
||||
"goToCorrectDomainTitle": "Go to correct domain",
|
||||
"authorizeTitle": "Authorize",
|
||||
"authorizeCardTitle": "Continue to {{app}}?",
|
||||
"authorizeSubtitle": "Would you like to continue to this app? Please carefully review the permissions requested by the app.",
|
||||
"authorizeSubtitleOAuth": "Would you like to continue to this app?",
|
||||
"authorizeLoadingTitle": "Loading...",
|
||||
"authorizeLoadingSubtitle": "Please wait while we load the client information.",
|
||||
"authorizeSuccessTitle": "Autorizováno",
|
||||
"authorizeSuccessSubtitle": "Během několika vteřin budete přesměrováni do aplikace.",
|
||||
"authorizeErrorClientInfo": "Při načítání klientských informací došlo k chybě. Zkuste to prosím později.",
|
||||
"authorizeErrorInvalidParams": "Parametry požadavku jsou chybné/neplatné. Prosím, zkontrolujte URL a zkuste znovu.",
|
||||
"authorizeSuccessTitle": "Authorized",
|
||||
"authorizeSuccessSubtitle": "You will be redirected to the app in a few seconds.",
|
||||
"authorizeErrorClientInfo": "An error occurred while loading the client information. Please try again later.",
|
||||
"authorizeErrorInvalidParams": "The request is missing required parameters or has invalid parameters. Please check the URL and try again.",
|
||||
"openidScopeName": "OpenID Connect",
|
||||
"openidScopeDescription": "Povolí aplikaci přístup k Vaším informacím OpenID Connect.",
|
||||
"emailScopeName": "E-mail",
|
||||
"emailScopeDescription": "Povolí aplikaci přístup k Vaší e-mailové adrese.",
|
||||
"profileScopeName": "Profil",
|
||||
"profileScopeDescription": "Povolí aplikaci přístup k informacím o Vašem profilu.",
|
||||
"groupsScopeName": "Skupiny",
|
||||
"groupsScopeDescription": "Povolí aplikaci přístup k informacím o Vaší skupině.",
|
||||
"backToLoginButton": "Zpět na přihlášení",
|
||||
"phoneScopeName": "Telefon",
|
||||
"phoneScopeDescription": "Povolí aplikaci přístup k Vašemu telefonnímu číslu.",
|
||||
"addressScopeName": "Adresa",
|
||||
"addressScopeDescription": "Povolí aplikaci přístup k Vaší adrese.",
|
||||
"loginTailscaleTitle": "Pokračovat přes Tailscale",
|
||||
"openidScopeDescription": "Allows the app to access your OpenID Connect information.",
|
||||
"emailScopeName": "Email",
|
||||
"emailScopeDescription": "Allows the app to access your email address.",
|
||||
"profileScopeName": "Profile",
|
||||
"profileScopeDescription": "Allows the app to access your profile information.",
|
||||
"groupsScopeName": "Groups",
|
||||
"groupsScopeDescription": "Allows the app to access your group information.",
|
||||
"backToLoginButton": "Back to login",
|
||||
"phoneScopeName": "Phone",
|
||||
"phoneScopeDescription": "Allows the app to access your phone number.",
|
||||
"addressScopeName": "Address",
|
||||
"addressScopeDescription": "Allows the app to access your address.",
|
||||
"loginTailscaleTitle": "Continue with Tailscale",
|
||||
"loginTailscaleDescription": "You appear to be accessing Tinyauth from an authorized Tailscale device. Would you like to continue with your Tailscale connection?",
|
||||
"loginTailscaleDeviceName": "Název zařízení:",
|
||||
"loginTailscaleOtherMethod": "Přihlásit jinou metodou",
|
||||
"loginTailscaleSuccess": "Úspěšně přihlášeno přes Tailscale.",
|
||||
"loginTailscaleFail": "Chyba při přihlášení přes Tailscale. Zkuste znovu, případně se přihlašte jiným způsobem, prosím.",
|
||||
"loginTailscaleDeviceName": "Device name:",
|
||||
"loginTailscaleOtherMethod": "Login with another method",
|
||||
"loginTailscaleSuccess": "Successfully authenticated with Tailscale.",
|
||||
"loginTailscaleFail": "Failed to authenticate with Tailscale. Please try again or use another login method.",
|
||||
"logoutTailscaleSubtitle": "You are currently logged in with Tailscale on your device <code>{{deviceName}}</code>. Click the button below to logout.",
|
||||
"quickActionsLanguage": "Jazyk",
|
||||
"quickActionsTheme": "Motiv",
|
||||
"quickActionsThemeLight": "Světlý",
|
||||
"quickActionsThemeDark": "Tmavý",
|
||||
"quickActionsThemeSystem": "Systémový",
|
||||
"quickActionsLogout": "Odhlásit se",
|
||||
"quickActionsLanguage": "Language",
|
||||
"quickActionsTheme": "Theme",
|
||||
"quickActionsThemeLight": "Light",
|
||||
"quickActionsThemeDark": "Dark",
|
||||
"quickActionsThemeSystem": "System",
|
||||
"quickActionsLogout": "Logout",
|
||||
"quickActionsTitle": "Quick Actions",
|
||||
"quickActionsProviderLocal": "Local",
|
||||
"quickActionsProviderLDAP": "LDAP",
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import {
|
||||
recompileScreenParams,
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
import { useEffect } from "react";
|
||||
@@ -89,7 +89,13 @@ export const AuthorizePage = () => {
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const isOidc = screenParams.login_for === "oidc";
|
||||
const compiledParams = recompileScreenParams(screenParams);
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
|
||||
// TODO: maybe a better way to do this
|
||||
const shouldAutoAuthorize =
|
||||
|
||||
@@ -13,7 +13,7 @@ import { Navigate, useLocation, useNavigate } from "react-router";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useRedirectUri } from "@/lib/hooks/redirect-uri";
|
||||
import {
|
||||
recompileScreenParams,
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
|
||||
@@ -31,8 +31,14 @@ export const ContinuePage = () => {
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const redirectUri = screenParams.redirect_uri;
|
||||
const isAppLogin = screenParams.login_for === "app";
|
||||
const recompiledParams = recompileScreenParams(screenParams);
|
||||
const isAppLogin = screenParams.login_for === "app" || !screenParams.login_for;
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
|
||||
const { url, valid, trusted, allowedProto, httpsDowngrade } = useRedirectUri(
|
||||
redirectUri,
|
||||
@@ -89,7 +95,7 @@ export const ContinuePage = () => {
|
||||
}, [shouldAutoRedirect, redirectToTarget]);
|
||||
|
||||
if (!auth.authenticated) {
|
||||
return <Navigate to={`/login${recompiledParams}`} replace />;
|
||||
return <Navigate to={`/login${compiledParams}`} replace />;
|
||||
}
|
||||
|
||||
if (!hasValidRedirect || !isAppLogin) {
|
||||
|
||||
@@ -12,8 +12,8 @@ import { useTranslation } from "react-i18next";
|
||||
import Markdown from "react-markdown";
|
||||
import { useLocation } from "react-router";
|
||||
import {
|
||||
recompileScreenParams,
|
||||
useScreenParams,
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
|
||||
export const ForgotPasswordPage = () => {
|
||||
@@ -22,7 +22,13 @@ export const ForgotPasswordPage = () => {
|
||||
const { search } = useLocation();
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const compiledParams = recompileScreenParams(screenParams);
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
|
||||
@@ -26,7 +26,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Navigate, useLocation } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
recompileScreenParams,
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
import { useLoginFor } from "@/lib/hooks/login-for";
|
||||
@@ -63,18 +63,21 @@ export const LoginPage = () => {
|
||||
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const compiledParams = recompileScreenParams({
|
||||
...screenParams,
|
||||
oidc_prompt: undefined,
|
||||
});
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
const loginForUrl = useLoginFor({
|
||||
login_for: screenParams.login_for,
|
||||
compiledParams,
|
||||
params: searchParamsFromObject({ ...screenParams, oidc_prompt: undefined}),
|
||||
});
|
||||
|
||||
const [isOauthAutoRedirect, setIsOauthAutoRedirect] = useState(
|
||||
providers.find((provider) => provider.id === oauth.autoRedirect) !==
|
||||
undefined && screenParams.redirect_uri !== undefined,
|
||||
undefined && (screenParams.redirect_uri || screenParams.oidc_ticket),
|
||||
);
|
||||
|
||||
const oauthProviders = providers.filter(
|
||||
@@ -171,8 +174,7 @@ export const LoginPage = () => {
|
||||
!auth.authenticated &&
|
||||
isOauthAutoRedirect &&
|
||||
!hasAutoRedirectedRef.current &&
|
||||
screenParams.redirect_uri &&
|
||||
screenParams.login_for
|
||||
(screenParams.redirect_uri || screenParams.oidc_ticket)
|
||||
) {
|
||||
hasAutoRedirectedRef.current = true;
|
||||
oauthMutate(oauth.autoRedirect);
|
||||
@@ -183,8 +185,8 @@ export const LoginPage = () => {
|
||||
hasAutoRedirectedRef,
|
||||
oauth.autoRedirect,
|
||||
isOauthAutoRedirect,
|
||||
screenParams.login_for,
|
||||
screenParams.redirect_uri,
|
||||
screenParams.oidc_ticket
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -17,8 +17,8 @@ import { type UseMutationResult } from "@tanstack/react-query";
|
||||
import { type AxiosResponse } from "axios";
|
||||
import { useLocation } from "react-router";
|
||||
import {
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
recompileScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
|
||||
export const LogoutPage = () => {
|
||||
@@ -29,7 +29,13 @@ export const LogoutPage = () => {
|
||||
const redirectTimer = useRef<number | null>(null);
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const compiledParams = recompileScreenParams(screenParams);
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
|
||||
const logoutMutation = useMutation({
|
||||
mutationFn: () => axios.post("/api/user/logout"),
|
||||
|
||||
@@ -17,7 +17,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Navigate, useLocation } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
recompileScreenParams,
|
||||
searchParamsFromObject,
|
||||
useScreenParams,
|
||||
} from "@/lib/hooks/screen-params";
|
||||
import { useLoginFor } from "@/lib/hooks/login-for";
|
||||
@@ -32,10 +32,16 @@ export const TotpPage = () => {
|
||||
|
||||
const searchParams = new URLSearchParams(search);
|
||||
const screenParams = useScreenParams(searchParams);
|
||||
const compiledParams = recompileScreenParams(screenParams);
|
||||
const compiledParams = (() => {
|
||||
const params = searchParamsFromObject(screenParams).toString();
|
||||
if (params.length > 0) {
|
||||
return `?${params}`;
|
||||
}
|
||||
return "";
|
||||
})();
|
||||
const loginForUrl = useLoginFor({
|
||||
login_for: screenParams.login_for,
|
||||
compiledParams,
|
||||
params: searchParamsFromObject(screenParams),
|
||||
});
|
||||
|
||||
const totpMutation = useMutation({
|
||||
|
||||
+4
-1
@@ -46,11 +46,14 @@ func generateExampleEnv() {
|
||||
func buildEnvEntry(child reflect.StructField, childValue reflect.Value, parentPath string, entries *[]EnvEntry) {
|
||||
desc := child.Tag.Get("description")
|
||||
tag := child.Tag.Get("yaml")
|
||||
gen := child.Tag.Get("gen")
|
||||
|
||||
if tag == "-" {
|
||||
if tag == "-" && gen != "include" {
|
||||
return
|
||||
}
|
||||
|
||||
tag = strings.TrimSuffix(tag, ",omitempty")
|
||||
|
||||
value := childValue.Interface()
|
||||
|
||||
entry := EnvEntry{
|
||||
|
||||
+63
-19
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
@@ -13,9 +12,13 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
)
|
||||
|
||||
type ConfigOptions struct {
|
||||
Env string
|
||||
Flag string
|
||||
YAML string
|
||||
}
|
||||
type MarkdownEntry struct {
|
||||
Env string
|
||||
Flag string
|
||||
Options ConfigOptions
|
||||
Description string
|
||||
Default any
|
||||
}
|
||||
@@ -47,16 +50,27 @@ func generateMarkdown() {
|
||||
func buildMdEntry(child reflect.StructField, childValue reflect.Value, parentPath string, entries *[]MarkdownEntry) {
|
||||
desc := child.Tag.Get("description")
|
||||
tag := child.Tag.Get("yaml")
|
||||
gen := child.Tag.Get("gen")
|
||||
|
||||
if tag == "-" {
|
||||
if tag == "-" && gen != "include" {
|
||||
return
|
||||
}
|
||||
|
||||
tag = strings.TrimSuffix(tag, ",omitempty")
|
||||
|
||||
value := childValue.Interface()
|
||||
|
||||
configOptions := ConfigOptions{
|
||||
Env: strings.ToUpper(strings.ReplaceAll(parentPath, ".", "_")) + strings.ToUpper(child.Name),
|
||||
Flag: fmt.Sprintf("--%s%s", strings.TrimPrefix(parentPath, "tinyauth."), strings.ToLower(child.Name)),
|
||||
}
|
||||
|
||||
if tag != "-" && tag != "" {
|
||||
configOptions.YAML = strings.TrimPrefix(parentPath, "tinyauth.") + tag
|
||||
}
|
||||
|
||||
entry := MarkdownEntry{
|
||||
Env: strings.ToUpper(strings.ReplaceAll(parentPath, ".", "_")) + strings.ToUpper(child.Name),
|
||||
Flag: fmt.Sprintf("--%s%s", strings.TrimPrefix(parentPath, "tinyauth."), strings.ToLower(child.Name)),
|
||||
Options: configOptions,
|
||||
Description: desc,
|
||||
}
|
||||
|
||||
@@ -83,11 +97,14 @@ func buildMdMapEntry(child reflect.StructField, parentPath string, entries *[]Ma
|
||||
}
|
||||
|
||||
tag := child.Tag.Get("yaml")
|
||||
gen := child.Tag.Get("gen")
|
||||
|
||||
if tag == "-" {
|
||||
if tag == "-" && gen != "include" {
|
||||
return
|
||||
}
|
||||
|
||||
tag = strings.TrimSuffix(tag, ",omitempty")
|
||||
|
||||
mapPath := parentPath + tag + ".[name]."
|
||||
valueType := fieldType.Elem()
|
||||
|
||||
@@ -102,27 +119,54 @@ func buildMdChildPath(parent string, child string) string {
|
||||
}
|
||||
|
||||
func compileMd(entries []MarkdownEntry) []byte {
|
||||
buffer := bytes.Buffer{}
|
||||
buffer := strings.Builder{}
|
||||
|
||||
buffer.WriteString("<!--- This file is automatically generated by gen/gen_md.go. Do not edit manually. --->\n\n")
|
||||
buffer.WriteString("# Tinyauth configuration reference\n\n")
|
||||
buffer.WriteString("| Environment | Flag | Description | Default |\n")
|
||||
buffer.WriteString("| - | - | - | - |\n")
|
||||
buffer.WriteString("{/* This part is automatically generated by gen/gen_md.go in the main repository. DO NOT EDIT. */}\n\n")
|
||||
buffer.WriteString("import { Tabs, TabItem } from '@astrojs/starlight/components';\n\n")
|
||||
buffer.WriteString("<Tabs>\n")
|
||||
|
||||
renderTabItem(&buffer, entries, "Environment")
|
||||
renderTabItem(&buffer, entries, "Flags")
|
||||
renderTabItem(&buffer, entries, "YAML")
|
||||
|
||||
buffer.WriteString("</Tabs>\n")
|
||||
|
||||
return []byte(buffer.String())
|
||||
}
|
||||
|
||||
func renderTabItem(buffer *strings.Builder, entries []MarkdownEntry, section string) {
|
||||
buffer.WriteString(fmt.Sprintf(" <TabItem label=\"%s\">\n", section))
|
||||
buffer.WriteString(" ### main\n\n")
|
||||
buffer.WriteString(" | Option | Description | Default |\n")
|
||||
buffer.WriteString(" | - | - | - |\n")
|
||||
|
||||
configType := strings.ToLower(section)
|
||||
previousSection := ""
|
||||
|
||||
for _, entry := range entries {
|
||||
if strings.Count(entry.Env, "_") > 1 {
|
||||
section := strings.Split(strings.TrimPrefix(entry.Env, "TINYAUTH_"), "_")[0]
|
||||
section := strings.Split(entry.Options.YAML, ".")[0]
|
||||
var option string
|
||||
switch configType {
|
||||
case "yaml":
|
||||
option = entry.Options.YAML
|
||||
case "flags":
|
||||
option = entry.Options.Flag
|
||||
case "environment":
|
||||
option = entry.Options.Env
|
||||
}
|
||||
if option == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Count(entry.Options.YAML, ".") >= 1 {
|
||||
if section != previousSection {
|
||||
buffer.WriteString("\n## " + strings.ToLower(section) + "\n\n")
|
||||
buffer.WriteString("| Environment | Flag | Description | Default |\n")
|
||||
buffer.WriteString("| - | - | - | - |\n")
|
||||
buffer.WriteString("\n ### " + strings.ToLower(section) + "\n\n")
|
||||
buffer.WriteString(" | Option | Description | Default |\n")
|
||||
buffer.WriteString(" | - | - | - |\n")
|
||||
previousSection = section
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&buffer, "| `%s` | `%s` | %s | %s |\n", entry.Env, entry.Flag, entry.Description, entry.Default)
|
||||
fmt.Fprintf(buffer, " | `%s` | %s | %s |\n", option, entry.Description, entry.Default)
|
||||
}
|
||||
|
||||
return buffer.Bytes()
|
||||
buffer.WriteString(" </TabItem>\n")
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ require (
|
||||
github.com/docker/docker v28.5.2+incompatible
|
||||
github.com/gin-gonic/gin v1.12.0
|
||||
github.com/go-jose/go-jose/v4 v4.1.4
|
||||
github.com/go-ldap/ldap/v3 v3.4.13
|
||||
github.com/go-ldap/ldap/v3 v3.4.14
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1
|
||||
github.com/google/go-querystring v1.2.0
|
||||
@@ -24,12 +24,13 @@ require (
|
||||
github.com/weppos/publicsuffix-go v0.50.3
|
||||
go.uber.org/dig v1.19.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/net v0.57.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/tools v0.48.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
k8s.io/apimachinery v0.36.2
|
||||
k8s.io/client-go v0.36.2
|
||||
modernc.org/sqlite v1.53.0
|
||||
k8s.io/apimachinery v0.36.3
|
||||
k8s.io/client-go v0.36.3
|
||||
modernc.org/sqlite v1.55.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -72,7 +73,7 @@ require (
|
||||
github.com/fxamacker/cbor/v2 v2.9.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.4 // indirect
|
||||
@@ -135,7 +136,6 @@ require (
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/mod v0.38.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/term v0.45.0 // indirect
|
||||
@@ -147,12 +147,12 @@ require (
|
||||
k8s.io/klog/v2 v2.140.0 // indirect
|
||||
k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a // indirect
|
||||
k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 // indirect
|
||||
modernc.org/libc v1.73.4 // indirect
|
||||
modernc.org/libc v1.74.1 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
rsc.io/qr v0.2.0 // indirect
|
||||
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect
|
||||
sigs.k8s.io/randfill v1.0.0 // indirect
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.2 // indirect
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.3 // indirect
|
||||
sigs.k8s.io/yaml v1.6.0 // indirect
|
||||
)
|
||||
|
||||
@@ -113,12 +113,12 @@ github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w
|
||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13 h1:+x1nG9h+MZN7h/lUi5Q3UZ0fJ1GyDQYbPvbuH38baDQ=
|
||||
github.com/go-ldap/ldap/v3 v3.4.13/go.mod h1:LxsGZV6vbaK0sIvYfsv47rfh4ca0JXokCoKjZxsszv0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14/go.mod h1:S4eJUMUNjDkE0ZJtIZdybwyb03sGGLW6gxXT1Hs8VKA=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
@@ -380,32 +380,32 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
|
||||
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
|
||||
k8s.io/api v0.36.2 h1:TF6YDLIzKfccK7cq9YpTcGX8TJmEkHVRv78DM51fRYY=
|
||||
k8s.io/api v0.36.2/go.mod h1:F4LbMO4brjZYh7yFkXWhynSvtB7YauxV4c+HHkNRGNg=
|
||||
k8s.io/apimachinery v0.36.2 h1:0PE/W/WNy1UX61NLbXY5TMbJ6UwLL6E6lAPkYrKFxbQ=
|
||||
k8s.io/apimachinery v0.36.2/go.mod h1:fvf/HOLXq9RId0rnDIbN1OEBvHXdQbLMM8nu0LcBUf4=
|
||||
k8s.io/client-go v0.36.2 h1:bfgxmFKc9CgqsgX4xKLAAdmTQlWee7Ob/HlDOrJ5TBI=
|
||||
k8s.io/client-go v0.36.2/go.mod h1:1vgO4OAlfPnoLcb+Rze2GF5rAr14w8qjrYMoyXJzQj0=
|
||||
k8s.io/api v0.36.3 h1:NxB+05W2UGqXWFXcLO0RB5cnqnUPP5v5sVlaOH0Iz4w=
|
||||
k8s.io/api v0.36.3/go.mod h1:JzLQKqRHC5+I8RVj/lS3lCg0mg6nWI9Fo/Sk3ElxHzg=
|
||||
k8s.io/apimachinery v0.36.3 h1:PkzMRBRG8joFD8EhCuQAtNPvJlxb82FwplP26HIzvAM=
|
||||
k8s.io/apimachinery v0.36.3/go.mod h1:cTSjBWgPe/6CQyBKzY/hDIRWCQQQeK0mfLbml0UYFHE=
|
||||
k8s.io/client-go v0.36.3 h1:M4JdVzXxYcZk4fGpfDdYnxSwhLKWCFoQsHW6t+z8Hfg=
|
||||
k8s.io/client-go v0.36.3/go.mod h1:gcPwr0c87vjjG6HB6pWEqOeuYVoXSsREjzux2j6GF30=
|
||||
k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc=
|
||||
k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0=
|
||||
k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a h1:xCeOEAOoGYl2jnJoHkC3hkbPJgdATINPMAxaynU2Ovg=
|
||||
k8s.io/kube-openapi v0.0.0-20260317180543-43fb72c5454a/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0=
|
||||
k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2 h1:AZYQSJemyQB5eRxqcPky+/7EdBj0xi3g0ZcxxJ7vbWU=
|
||||
k8s.io/utils v0.0.0-20260210185600-b8788abfbbc2/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk=
|
||||
modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c=
|
||||
modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws=
|
||||
modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE=
|
||||
modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
|
||||
modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc=
|
||||
modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
|
||||
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
|
||||
modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
|
||||
modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
@@ -414,8 +414,8 @@ modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
|
||||
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
|
||||
modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
|
||||
modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
@@ -426,7 +426,7 @@ sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5E
|
||||
sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg=
|
||||
sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU=
|
||||
sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY=
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.2 h1:kwVWMx5yS1CrnFWA/2QHyRVJ8jM6dBA80uLmm0wJkk8=
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.3 h1:u08YRbVUi59ri4YD6cg0UqNM4Dimn0sIl+wldcx5PYw=
|
||||
sigs.k8s.io/structured-merge-diff/v6 v6.3.3/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
|
||||
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
|
||||
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
|
||||
|
||||
@@ -88,17 +88,13 @@ func (app *BootstrapApp) Setup() error {
|
||||
app.log.App.Info().Msgf("Starting Tinyauth version: %s", model.Version)
|
||||
|
||||
// get app url
|
||||
if app.config.AppURL == "" {
|
||||
return errors.New("app url cannot be empty, perhaps config loading failed")
|
||||
}
|
||||
|
||||
appUrl, err := url.Parse(app.config.AppURL)
|
||||
appURL, err := utils.SafeParseAppURL(app.config.AppURL)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse app url: %w", err)
|
||||
}
|
||||
|
||||
app.runtime.AppURL = strings.ToLower(appUrl.Scheme + "://" + appUrl.Host)
|
||||
app.runtime.AppURL = appURL
|
||||
|
||||
// validate session config
|
||||
if app.config.Auth.SessionMaxLifetime != 0 && app.config.Auth.SessionMaxLifetime < app.config.Auth.SessionExpiry {
|
||||
@@ -172,7 +168,13 @@ func (app *BootstrapApp) Setup() error {
|
||||
app.runtime.CookieDomain = cookieDomain
|
||||
|
||||
// cookie names
|
||||
app.runtime.UUID = utils.GenerateUUID(appUrl.Hostname())
|
||||
u, err := url.Parse(app.runtime.AppURL)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse app url: %w", err)
|
||||
}
|
||||
|
||||
app.runtime.UUID = utils.GenerateUUID(u.Hostname())
|
||||
|
||||
cookieId := strings.Split(app.runtime.UUID, "-")[0] // first 8 characters of the uuid should be good enough
|
||||
|
||||
|
||||
@@ -30,6 +30,16 @@ func (app *BootstrapApp) setupRouter() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set trusted proxies: %w", err)
|
||||
}
|
||||
|
||||
app.runtime.TrustedProxiesConfigured = true
|
||||
} else {
|
||||
err := engine.SetTrustedProxies(nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set trusted proxies: %w", err)
|
||||
}
|
||||
|
||||
app.log.App.Warn().Msg("Trusted proxies are not configured, IP access controls will NOT work")
|
||||
}
|
||||
|
||||
middlewareProvideFor := []any{
|
||||
|
||||
@@ -85,7 +85,8 @@ func (app *BootstrapApp) getLabelProvider() (service.LabelProvider, error) {
|
||||
err := app.dig.Provide(service.NewKubernetesService)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to provide kubernetes service: %w", err)
|
||||
app.log.App.Warn().Err(err).Msg("Failed to provide kubernetes service")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
err = app.dig.Invoke(func(k *service.KubernetesService) error {
|
||||
@@ -94,7 +95,8 @@ func (app *BootstrapApp) getLabelProvider() (service.LabelProvider, error) {
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to invoke kubernetes service: %w", err)
|
||||
app.log.App.Warn().Err(err).Msg("Failed to invoke kubernetes service")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Kubernetes will fail to initialize with an error if it cannot connect to the cluster
|
||||
@@ -114,7 +116,8 @@ func (app *BootstrapApp) getLabelProvider() (service.LabelProvider, error) {
|
||||
err := app.dig.Provide(service.NewDockerService)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to provide docker service: %w", err)
|
||||
app.log.App.Warn().Err(err).Msg("Failed to provide docker service")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
err = app.dig.Invoke(func(d *service.DockerService) error {
|
||||
@@ -123,7 +126,8 @@ func (app *BootstrapApp) getLabelProvider() (service.LabelProvider, error) {
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to invoke docker service: %w", err)
|
||||
app.log.App.Warn().Err(err).Msg("Failed to invoke docker service")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if app.services.dockerService == nil {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/service"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/validators"
|
||||
"go.uber.org/dig"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -219,35 +220,16 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var name string
|
||||
|
||||
if strings.TrimSpace(user.Name) != "" {
|
||||
controller.log.App.Debug().Msg("Using name from OAuth provider")
|
||||
name = user.Name
|
||||
} else {
|
||||
controller.log.App.Debug().Msg("No name from OAuth provider, generating from email")
|
||||
parts := strings.SplitN(user.Email, "@", 2)
|
||||
if len(parts) == 2 {
|
||||
name = fmt.Sprintf("%s (%s)", utils.Capitalize(parts[0]), parts[1])
|
||||
} else {
|
||||
name = utils.Capitalize(user.Email)
|
||||
}
|
||||
}
|
||||
|
||||
var username string
|
||||
|
||||
if strings.TrimSpace(user.PreferredUsername) != "" {
|
||||
controller.log.App.Debug().Msg("Using preferred username from OAuth provider")
|
||||
username = user.PreferredUsername
|
||||
} else {
|
||||
controller.log.App.Debug().Msg("No preferred username from OAuth provider, generating from email")
|
||||
username = strings.Replace(user.Email, "@", "_", 1)
|
||||
}
|
||||
oauthUserInfo := controller.createOAuthUserInfo(oauthUserInfo{
|
||||
Username: user.PreferredUsername,
|
||||
Email: user.Email,
|
||||
Name: user.Name,
|
||||
})
|
||||
|
||||
sessionCookie := repository.Session{
|
||||
Username: username,
|
||||
Name: name,
|
||||
Email: user.Email,
|
||||
Username: oauthUserInfo.Username,
|
||||
Name: oauthUserInfo.Name,
|
||||
Email: oauthUserInfo.Email,
|
||||
Provider: svc.ID(),
|
||||
OAuthGroups: utils.CoalesceToString(user.Groups),
|
||||
OAuthName: svc.Name(),
|
||||
@@ -311,56 +293,102 @@ func (controller *OAuthController) getCookieDomain() string {
|
||||
}
|
||||
|
||||
func (controller *OAuthController) isRedirectSafe(redirectURI string) bool {
|
||||
u, err := url.Parse(redirectURI)
|
||||
v := validators.NewDomainValidator(validators.DomainValidatorOptions{
|
||||
WithPort: true,
|
||||
})
|
||||
|
||||
_, err := v.SafeHostname(controller.runtime.AppURL)
|
||||
|
||||
if err != nil {
|
||||
controller.log.App.Error().Err(err).Msg("Failed to parse redirect URI")
|
||||
controller.log.App.Error().Err(err).Msg("App URL is invalid, cannot validate redirect URI")
|
||||
return false
|
||||
}
|
||||
|
||||
if u.Scheme == "" || u.Host == "" {
|
||||
controller.log.App.Warn().Msg("Redirect URI has invalid scheme or host")
|
||||
return false
|
||||
}
|
||||
err = v.Validate(redirectURI, controller.runtime.AppURL)
|
||||
|
||||
au, err := url.Parse(controller.runtime.AppURL)
|
||||
|
||||
if err != nil {
|
||||
controller.log.App.Error().Err(err).Msg("Failed to parse app URL")
|
||||
return false
|
||||
}
|
||||
|
||||
if u.Scheme != au.Scheme {
|
||||
controller.log.App.Warn().Msg("Redirect URI scheme does not match app URL scheme")
|
||||
return false
|
||||
}
|
||||
|
||||
getEffectivePort := func(u *url.URL) string {
|
||||
if u.Port() != "" {
|
||||
return u.Port()
|
||||
}
|
||||
if u.Scheme == "https" {
|
||||
return "443"
|
||||
}
|
||||
return "80"
|
||||
}
|
||||
|
||||
if getEffectivePort(u) != getEffectivePort(au) {
|
||||
controller.log.App.Warn().Msg("Redirect URI port does not match app URL port")
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.EqualFold(u.Hostname(), au.Hostname()) {
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
controller.log.App.Debug().Err(err).Msg("Failed to validate redirect URI")
|
||||
|
||||
if !errors.Is(err, validators.ErrHostnameMismatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
if !controller.config.Auth.SubdomainsEnabled {
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.HasSuffix(strings.ToLower(u.Hostname()), "."+strings.ToLower(controller.runtime.CookieDomain)) {
|
||||
v = validators.NewDomainValidator(validators.DomainValidatorOptions{})
|
||||
|
||||
hostname, err := v.SafeHostname(redirectURI)
|
||||
|
||||
if err != nil {
|
||||
controller.log.App.Error().Err(err).Msg("Failed to get safe hostname from redirect URI")
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.HasSuffix(hostname, "."+strings.ToLower(controller.runtime.CookieDomain)) ||
|
||||
hostname == controller.runtime.CookieDomain {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
type oauthUserInfo struct {
|
||||
Email string
|
||||
Username string
|
||||
Name string
|
||||
}
|
||||
|
||||
func (controller *OAuthController) createOAuthUserInfo(input oauthUserInfo) oauthUserInfo {
|
||||
info := oauthUserInfo{
|
||||
Email: input.Email,
|
||||
}
|
||||
|
||||
if controller.config.Experimental.OAuthBridgeEnabled {
|
||||
if input.Username != "" {
|
||||
info.Username = input.Username
|
||||
} else {
|
||||
parts := strings.SplitN(input.Email, "@", 2)
|
||||
if len(parts) != 2 {
|
||||
controller.log.App.Error().Str("email", input.Email).Msg("Invalid email address")
|
||||
} else {
|
||||
info.Username = parts[0]
|
||||
}
|
||||
}
|
||||
|
||||
if input.Name != "" {
|
||||
info.Name = input.Name
|
||||
} else {
|
||||
info.Name = utils.Capitalize(info.Username)
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
if input.Name != "" {
|
||||
controller.log.App.Debug().Msg("Using name from OAuth provider")
|
||||
info.Name = input.Name
|
||||
} else {
|
||||
controller.log.App.Debug().Msg("No name from OAuth provider, generating from email")
|
||||
parts := strings.SplitN(input.Email, "@", 2)
|
||||
if len(parts) != 2 {
|
||||
controller.log.App.Error().Str("email", input.Email).Msg("Invalid email address")
|
||||
} else {
|
||||
info.Name = fmt.Sprintf("%s (%s)", utils.Capitalize(parts[0]), parts[1])
|
||||
}
|
||||
}
|
||||
|
||||
if input.Username != "" {
|
||||
controller.log.App.Debug().Msg("Using preferred username from OAuth provider")
|
||||
info.Username = input.Username
|
||||
} else {
|
||||
controller.log.App.Debug().Msg("No preferred username from OAuth provider, generating from email")
|
||||
info.Username = strings.Replace(info.Email, "@", "_", 1)
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
)
|
||||
|
||||
func TestOAuthControllerIsRedirectSafe(t *testing.T) {
|
||||
func TestOAuthController_isRedirectSafe(t *testing.T) {
|
||||
log := logger.NewLogger().WithTestConfig()
|
||||
log.Init()
|
||||
|
||||
@@ -81,22 +81,6 @@ func TestOAuthControllerIsRedirectSafe(t *testing.T) {
|
||||
redirectURI: "https://sub.example.com",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
description: "Cookie domain itself is not a subdomain match",
|
||||
appURL: "https://tinyauth.example.com",
|
||||
cookieDomain: "example.com",
|
||||
subdomainsEnabled: true,
|
||||
redirectURI: "https://example.com",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
description: "Different scheme returns false",
|
||||
appURL: "https://tinyauth.example.com",
|
||||
cookieDomain: "example.com",
|
||||
subdomainsEnabled: true,
|
||||
redirectURI: "http://tinyauth.example.com",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
description: "Different port returns false",
|
||||
appURL: "https://tinyauth.example.com",
|
||||
@@ -121,14 +105,6 @@ func TestOAuthControllerIsRedirectSafe(t *testing.T) {
|
||||
redirectURI: "https:/malicious",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
description: "Redirect URI without scheme returns false",
|
||||
appURL: "https://tinyauth.example.com",
|
||||
cookieDomain: "example.com",
|
||||
subdomainsEnabled: true,
|
||||
redirectURI: "tinyauth.example.com",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
description: "Relative redirect URI returns false",
|
||||
appURL: "https://tinyauth.example.com",
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -343,27 +344,31 @@ func (controller *OIDCController) authorizeComplete(c *gin.Context) {
|
||||
// Create the authorization code
|
||||
code := controller.oidc.CreateCode(*authorizeReq, *userContext)
|
||||
|
||||
queries, err := query.Values(AuthorizeCallback{
|
||||
Code: code,
|
||||
State: authorizeReq.State,
|
||||
})
|
||||
cu, err := url.Parse(authorizeReq.RedirectURI)
|
||||
|
||||
if err != nil {
|
||||
controller.authorizeError(c, authorizeErrorParams{
|
||||
err: err,
|
||||
reason: "Failed to build query",
|
||||
reasonPublic: "Failed to build query",
|
||||
callback: authorizeReq.RedirectURI,
|
||||
callbackError: "server_error",
|
||||
state: authorizeReq.State,
|
||||
json: true,
|
||||
err: err,
|
||||
reason: "Failed to parse redirect URI",
|
||||
reasonPublic: "Failed to parse redirect URI",
|
||||
json: true,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
q := cu.Query()
|
||||
|
||||
q.Set("code", code)
|
||||
|
||||
if authorizeReq.State != "" {
|
||||
q.Set("state", authorizeReq.State)
|
||||
}
|
||||
|
||||
cu.RawQuery = q.Encode()
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"status": 200,
|
||||
"redirect_uri": fmt.Sprintf("%s?%s", authorizeReq.RedirectURI, queries.Encode()),
|
||||
"redirect_uri": cu.String(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -639,37 +644,37 @@ func (controller *OIDCController) authorizeError(c *gin.Context, params authoriz
|
||||
controller.log.App.Error().Err(params.err).Str("reason", params.reason).Msg("Authorization error")
|
||||
|
||||
if params.callback != "" {
|
||||
errorQueries := CallbackError{
|
||||
Error: params.callbackError,
|
||||
}
|
||||
|
||||
if params.reasonPublic != "" {
|
||||
errorQueries.ErrorDescription = params.reasonPublic
|
||||
}
|
||||
|
||||
if params.state != "" {
|
||||
errorQueries.State = params.state
|
||||
}
|
||||
|
||||
queries, err := query.Values(errorQueries)
|
||||
cu, err := url.Parse(params.callback)
|
||||
|
||||
if err != nil {
|
||||
controller.log.App.Error().Err(err).Msg("Failed to build callback error query")
|
||||
controller.log.App.Error().Err(err).Msg("Failed to parse callback URL")
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
redirectUrl := fmt.Sprintf("%s?%s", params.callback, queries.Encode())
|
||||
q := cu.Query()
|
||||
|
||||
q.Set("error", params.callbackError)
|
||||
|
||||
if params.reasonPublic != "" {
|
||||
q.Set("error_description", params.reasonPublic)
|
||||
}
|
||||
|
||||
if params.state != "" {
|
||||
q.Set("state", params.state)
|
||||
}
|
||||
|
||||
cu.RawQuery = q.Encode()
|
||||
|
||||
if params.json {
|
||||
c.JSON(200, gin.H{
|
||||
"status": 200,
|
||||
"redirect_uri": redirectUrl,
|
||||
"redirect_uri": cu.String(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(http.StatusFound, redirectUrl)
|
||||
c.Redirect(http.StatusFound, cu.String())
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -111,9 +112,10 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
aclsCtx := &service.ACLContext{
|
||||
ACLs: acls,
|
||||
IP: net.ParseIP(clientIP),
|
||||
Path: proxyCtx.Path,
|
||||
ACLs: acls,
|
||||
IP: net.ParseIP(clientIP),
|
||||
Path: proxyCtx.Path,
|
||||
TrustedProxiesConfigured: controller.runtime.TrustedProxiesConfigured,
|
||||
}
|
||||
|
||||
if controller.policyEngine.Evaluate(service.RuleIPBypassed, aclsCtx) {
|
||||
@@ -550,6 +552,19 @@ func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
|
||||
// remove any query params from the request path
|
||||
upath, err := url.Parse(ctx.Path)
|
||||
|
||||
if err != nil {
|
||||
return ProxyContext{}, fmt.Errorf("failed to parse request path: %v", err)
|
||||
}
|
||||
|
||||
if upath.Host != "" || !strings.HasPrefix(upath.Path, "/") {
|
||||
return ProxyContext{}, fmt.Errorf("invalid request path")
|
||||
}
|
||||
|
||||
ctx.Path = path.Clean(upath.Path)
|
||||
|
||||
// We don't care if the header is empty, we will just assume it's not a browser
|
||||
userAgent, _ := controller.getHeader(c, "user-agent")
|
||||
isBrowser := BrowserUserAgentRegex.MatchString(userAgent)
|
||||
|
||||
@@ -308,6 +308,171 @@ func TestProxyController(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL requires auth on exact match",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/admin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL skips auth for non-matching path",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/public")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusOK, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with query params",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/admin?foo=bar")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with a trailing slash",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/admin/")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with dot segments",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/foo/../admin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with percent-encoded characters",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/%61dmin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with a percent-encoded double slash",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/%2Fadmin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure a protocol-relative x-forwarded-uri is rejected",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "//admin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure a relative x-forwarded-uri is rejected",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-block.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "public")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusBadRequest, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with query params on envoy ext authz",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("HEAD", "/api/auth/envoy?path=/admin%3Ffoo=bar", nil)
|
||||
req.Host = "path-block.example.com"
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path block ACL cannot be bypassed with dot segments on nginx auth request",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/nginx", nil)
|
||||
req.Header.Set("x-original-url", "https://path-block.example.com/foo/../admin")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path allow ACL still matches when query params are present",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-allow.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/allowed?foo=bar")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusOK, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure path allow ACL cannot be extended with dot segments",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-allow.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/allowed/../secret")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure an allowed path inside the query string does not bypass auth",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
|
||||
req.Header.Set("x-forwarded-host", "path-allow.example.com")
|
||||
req.Header.Set("x-forwarded-proto", "https")
|
||||
req.Header.Set("x-forwarded-uri", "/secret?next=/allowed")
|
||||
router.ServeHTTP(recorder, req)
|
||||
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Ensure ip bypass ACL works on forward auth",
|
||||
middlewares: []gin.HandlerFunc{},
|
||||
@@ -708,7 +873,7 @@ func TestProxyController(t *testing.T) {
|
||||
Log: log,
|
||||
})
|
||||
|
||||
authService := service.NewAuthService(service.AuthServiceInput{
|
||||
authService, err := service.NewAuthService(service.AuthServiceInput{
|
||||
Log: log,
|
||||
Config: &cfg,
|
||||
Runtime: &runtime,
|
||||
@@ -721,6 +886,8 @@ func TestProxyController(t *testing.T) {
|
||||
PolicyEngine: policyEngine,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.description, func(t *testing.T) {
|
||||
router := gin.Default()
|
||||
|
||||
@@ -72,26 +72,12 @@ func (controller *UserController) loginHandler(c *gin.Context) {
|
||||
|
||||
controller.log.App.Debug().Str("username", req.Username).Msg("Login attempt")
|
||||
|
||||
isLocked, remaining := controller.auth.IsAccountLocked(req.Username)
|
||||
|
||||
if isLocked {
|
||||
controller.log.App.Warn().Str("username", req.Username).Msg("Account is locked due to too many failed login attempts")
|
||||
controller.log.AuditLoginFailure(req.Username, "local", c.ClientIP(), "account locked")
|
||||
c.Writer.Header().Add("x-tinyauth-lock-locked", "true")
|
||||
c.Writer.Header().Add("x-tinyauth-lock-reset", time.Now().Add(time.Duration(remaining)*time.Second).Format(time.RFC3339))
|
||||
c.JSON(429, gin.H{
|
||||
"status": 429,
|
||||
"message": fmt.Sprintf("Too many failed login attempts. Try again in %d seconds", remaining),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
search, err := controller.auth.SearchUser(req.Username)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUserNotFound) {
|
||||
controller.auth.DummyPasswordCheck(req.Password)
|
||||
controller.log.App.Warn().Str("username", req.Username).Msg("User not found during login attempt")
|
||||
controller.auth.RecordLoginAttempt(req.Username, false)
|
||||
controller.log.AuditLoginFailure(req.Username, "unknown", c.ClientIP(), "user not found")
|
||||
c.JSON(401, gin.H{
|
||||
"status": 401,
|
||||
@@ -107,14 +93,24 @@ func (controller *UserController) loginHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
isLocked, remaining := controller.auth.IsAccountLocked(req.Username)
|
||||
|
||||
if isLocked {
|
||||
controller.log.App.Warn().Str("username", req.Username).Msg("Account is locked due to too many failed login attempts")
|
||||
controller.log.AuditLoginFailure(req.Username, search.Type.String(), c.ClientIP(), "account locked")
|
||||
c.Writer.Header().Add("x-tinyauth-lock-locked", "true")
|
||||
c.Writer.Header().Add("x-tinyauth-lock-reset", time.Now().Add(time.Duration(remaining)*time.Second).Format(time.RFC3339))
|
||||
c.JSON(429, gin.H{
|
||||
"status": 429,
|
||||
"message": fmt.Sprintf("Too many failed login attempts. Try again in %d seconds", remaining),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := controller.auth.CheckUserPassword(*search, req.Password); err != nil {
|
||||
controller.log.App.Warn().Str("username", req.Username).Msg("Invalid password during login attempt")
|
||||
controller.auth.RecordLoginAttempt(req.Username, false)
|
||||
if search.Type == model.UserLocal {
|
||||
controller.log.AuditLoginFailure(req.Username, "local", c.ClientIP(), "invalid password")
|
||||
} else {
|
||||
controller.log.AuditLoginFailure(req.Username, "ldap", c.ClientIP(), "invalid password")
|
||||
}
|
||||
controller.log.AuditLoginFailure(req.Username, search.Type.String(), c.ClientIP(), "invalid password")
|
||||
c.JSON(401, gin.H{
|
||||
"status": 401,
|
||||
"message": "Unauthorized",
|
||||
@@ -215,11 +211,7 @@ func (controller *UserController) loginHandler(c *gin.Context) {
|
||||
|
||||
controller.log.App.Info().Str("username", req.Username).Msg("Login successful")
|
||||
|
||||
if search.Type == model.UserLocal {
|
||||
controller.log.AuditLoginSuccess(req.Username, "local", c.ClientIP())
|
||||
} else {
|
||||
controller.log.AuditLoginSuccess(req.Username, "ldap", c.ClientIP())
|
||||
}
|
||||
controller.log.AuditLoginSuccess(req.Username, search.Type.String(), c.ClientIP())
|
||||
|
||||
controller.auth.RecordLoginAttempt(req.Username, true)
|
||||
|
||||
|
||||
@@ -542,7 +542,8 @@ func TestUserController(t *testing.T) {
|
||||
Runtime: &runtime,
|
||||
Ctx: ctx,
|
||||
})
|
||||
authService := service.NewAuthService(service.AuthServiceInput{
|
||||
|
||||
authService, err := service.NewAuthService(service.AuthServiceInput{
|
||||
Log: log,
|
||||
Config: &cfg,
|
||||
Runtime: &runtime,
|
||||
@@ -555,6 +556,8 @@ func TestUserController(t *testing.T) {
|
||||
PolicyEngine: policyEngine,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
beforeEach := func() {
|
||||
// Clear failed login attempts before each test
|
||||
authService.ClearLoginAttempts()
|
||||
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -39,6 +40,7 @@ var (
|
||||
type ContextMiddleware struct {
|
||||
log *logger.Logger
|
||||
runtime *model.RuntimeConfig
|
||||
config *model.Config
|
||||
auth *service.AuthService
|
||||
broker *service.OAuthBrokerService
|
||||
tailscale *service.TailscaleService
|
||||
@@ -49,6 +51,7 @@ type ContextMiddlewareInput struct {
|
||||
|
||||
Log *logger.Logger
|
||||
RuntimeConfig *model.RuntimeConfig
|
||||
StaticConfig *model.Config
|
||||
AuthService *service.AuthService
|
||||
BrokerService *service.OAuthBrokerService
|
||||
TailscaleService *service.TailscaleService
|
||||
@@ -58,6 +61,7 @@ func NewContextMiddleware(i ContextMiddlewareInput) *ContextMiddleware {
|
||||
return &ContextMiddleware{
|
||||
log: i.Log,
|
||||
runtime: i.RuntimeConfig,
|
||||
config: i.StaticConfig,
|
||||
auth: i.AuthService,
|
||||
broker: i.BrokerService,
|
||||
tailscale: i.TailscaleService,
|
||||
@@ -244,6 +248,9 @@ func (m *ContextMiddleware) basicAuth(username string, password string) (*model.
|
||||
search, err := m.auth.SearchUser(username)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUserNotFound) {
|
||||
m.auth.DummyPasswordCheck(password)
|
||||
}
|
||||
return nil, nil, fmt.Errorf("error searching for user: %w", err)
|
||||
}
|
||||
|
||||
@@ -278,7 +285,7 @@ func (m *ContextMiddleware) basicAuth(username string, password string) (*model.
|
||||
}
|
||||
userContext.Provider = model.ProviderLocal
|
||||
case model.UserLDAP:
|
||||
user, err := m.auth.GetLDAPUser(username)
|
||||
user, err := m.auth.GetLDAPUser(search.Username)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("error retrieving ldap user details: %w", err)
|
||||
@@ -328,16 +335,19 @@ func (m *ContextMiddleware) tailscaleWhois(ip string) (*model.TailscaleContext,
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
username := strings.Replace(whois.LoginName, "@", "_", 1)
|
||||
|
||||
uctx := model.TailscaleContext{
|
||||
BaseContext: model.BaseContext{
|
||||
Username: username,
|
||||
Email: whois.LoginName,
|
||||
Name: whois.DisplayName,
|
||||
Email: whois.LoginName,
|
||||
Name: whois.DisplayName,
|
||||
},
|
||||
NodeName: whois.NodeName,
|
||||
}
|
||||
|
||||
if m.config.Experimental.OAuthBridgeEnabled {
|
||||
uctx.BaseContext.Username = strings.SplitN(whois.LoginName, "@", 2)[0]
|
||||
} else {
|
||||
uctx.BaseContext.Username = strings.Replace(whois.LoginName, "@", "_", 1)
|
||||
}
|
||||
|
||||
return &uctx, nil
|
||||
}
|
||||
|
||||
@@ -264,7 +264,8 @@ func TestContextMiddleware(t *testing.T) {
|
||||
Runtime: &runtime,
|
||||
Ctx: ctx,
|
||||
})
|
||||
authService := service.NewAuthService(service.AuthServiceInput{
|
||||
|
||||
authService, err := service.NewAuthService(service.AuthServiceInput{
|
||||
Log: log,
|
||||
Config: &cfg,
|
||||
Runtime: &runtime,
|
||||
@@ -277,6 +278,8 @@ func TestContextMiddleware(t *testing.T) {
|
||||
PolicyEngine: policyEngine,
|
||||
})
|
||||
|
||||
require.NoError(t, err)
|
||||
|
||||
contextMiddleware := NewContextMiddleware(ContextMiddlewareInput{
|
||||
Log: log,
|
||||
RuntimeConfig: &runtime,
|
||||
|
||||
+22
-21
@@ -49,7 +49,6 @@ func NewDefaultConfiguration(runtimeEnv RuntimeEnv) *Config {
|
||||
ACLs: ACLsConfig{
|
||||
Policy: "allow",
|
||||
},
|
||||
LockdownEnabled: true,
|
||||
},
|
||||
UI: UIConfig{
|
||||
Title: "Tinyauth",
|
||||
@@ -102,22 +101,23 @@ func NewDefaultConfiguration(runtimeEnv RuntimeEnv) *Config {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
AppURL string `description:"The base URL where the app is hosted." yaml:"appUrl,omitempty"`
|
||||
Database DatabaseConfig `description:"Database configuration." yaml:"database,omitempty"`
|
||||
Analytics AnalyticsConfig `description:"Analytics configuration." yaml:"analytics,omitempty"`
|
||||
Resources ResourcesConfig `description:"Resources configuration." yaml:"resources,omitempty"`
|
||||
Server ServerConfig `description:"Server configuration." yaml:"server,omitempty"`
|
||||
Auth AuthConfig `description:"Authentication configuration." yaml:"auth,omitempty"`
|
||||
Apps map[string]App `description:"Application ACLs configuration." yaml:"apps,omitempty"`
|
||||
OAuth OAuthConfig `description:"OAuth configuration." yaml:"oauth,omitempty"`
|
||||
OIDC OIDCConfig `description:"OIDC configuration." yaml:"oidc,omitempty"`
|
||||
UI UIConfig `description:"UI customization." yaml:"ui,omitempty"`
|
||||
LDAP LDAPConfig `description:"LDAP configuration." yaml:"ldap,omitempty"`
|
||||
Experimental ExperimentalConfig `description:"Experimental features, use with caution." yaml:"experimental,omitempty"`
|
||||
Tailscale TailscaleConfig `description:"Tailscale configuration." yaml:"tailscale,omitempty"`
|
||||
LabelProvider string `description:"Label provider to use for ACLs (auto, docker, kubernetes or none to disable). auto detects the environment." yaml:"labelProvider,omitempty"`
|
||||
Log LogConfig `description:"Logging configuration." yaml:"log,omitempty"`
|
||||
ConfigFile string `description:"Path to config file." yaml:"-"`
|
||||
AppURL string `description:"The base URL where the app is hosted." yaml:"appUrl,omitempty"`
|
||||
ConfigFile string `description:"Path to config file." yaml:"-" gen:"include"`
|
||||
LabelProvider string `description:"Label provider to use for ACLs (auto, docker, kubernetes or none to disable). auto detects the environment." yaml:"labelProvider,omitempty"`
|
||||
Database DatabaseConfig `description:"Database configuration." yaml:"database,omitempty"`
|
||||
Analytics AnalyticsConfig `description:"Analytics configuration." yaml:"analytics,omitempty"`
|
||||
Resources ResourcesConfig `description:"Resources configuration." yaml:"resources,omitempty"`
|
||||
Server ServerConfig `description:"Server configuration." yaml:"server,omitempty"`
|
||||
Auth AuthConfig `description:"Authentication configuration." yaml:"auth,omitempty"`
|
||||
Apps map[string]App `description:"Application ACLs configuration." yaml:"apps,omitempty"`
|
||||
OAuth OAuthConfig `description:"OAuth configuration." yaml:"oauth,omitempty"`
|
||||
OIDC OIDCConfig `description:"OIDC configuration." yaml:"oidc,omitempty"`
|
||||
UI UIConfig `description:"UI customization." yaml:"ui,omitempty"`
|
||||
LDAP LDAPConfig `description:"LDAP configuration." yaml:"ldap,omitempty"`
|
||||
// enable the cli warning on experimental features
|
||||
Experimental ExperimentalConfig `description:"Experimental features, use with caution." yaml:"experimental,omitempty"`
|
||||
Tailscale TailscaleConfig `description:"Tailscale configuration." yaml:"tailscale,omitempty"`
|
||||
Log LogConfig `description:"Logging configuration." yaml:"log,omitempty"`
|
||||
}
|
||||
|
||||
type DatabaseConfig struct {
|
||||
@@ -151,7 +151,6 @@ type AuthConfig struct {
|
||||
SessionMaxLifetime int `description:"Maximum session lifetime in seconds." yaml:"sessionMaxLifetime,omitempty"`
|
||||
LoginTimeout int `description:"Login timeout in seconds." yaml:"loginTimeout,omitempty"`
|
||||
LoginMaxRetries int `description:"Maximum login retries." yaml:"loginMaxRetries,omitempty"`
|
||||
LockdownEnabled bool `description:"Enable lockdown mode after maximum login retries. Lockdown mode limit is calculated automatically." yaml:"lockdownEnabled,omitempty"`
|
||||
TrustedProxies []string `description:"Comma-separated list of trusted proxy addresses." yaml:"trustedProxies,omitempty"`
|
||||
ACLs ACLsConfig `description:"ACLs configuration." yaml:"acls,omitempty"`
|
||||
}
|
||||
@@ -239,7 +238,9 @@ type LogStreamConfig struct {
|
||||
Level string `description:"Log level for this stream. Use global if empty." yaml:"level,omitempty"`
|
||||
}
|
||||
|
||||
type ExperimentalConfig struct{}
|
||||
type ExperimentalConfig struct {
|
||||
OAuthBridgeEnabled bool `description:"Enable the OAuth bridge, uses a new way to format OAuth user information." yaml:"oauthBridgeEnabled,omitempty"`
|
||||
}
|
||||
|
||||
type TailscaleConfig struct {
|
||||
Enabled bool `description:"Enable Tailscale integration." yaml:"enabled,omitempty"`
|
||||
@@ -331,6 +332,6 @@ type AppBasicAuth struct {
|
||||
}
|
||||
|
||||
type AppPath struct {
|
||||
Allow string `description:"Comma-separated list of allowed paths." yaml:"allow,omitempty"`
|
||||
Block string `description:"Comma-separated list of blocked paths." yaml:"block,omitempty"`
|
||||
Allow string `description:"Disable authentication for only paths that match the regex string." yaml:"allow,omitempty"`
|
||||
Block string `description:"Enable authentication for only paths that match the regex string." yaml:"block,omitempty"`
|
||||
}
|
||||
|
||||
+12
-11
@@ -1,17 +1,18 @@
|
||||
package model
|
||||
|
||||
type RuntimeConfig struct {
|
||||
AppURL string
|
||||
UUID string
|
||||
CookieDomain string
|
||||
SessionCookieName string
|
||||
CSRFCookieName string
|
||||
RedirectCookieName string
|
||||
OAuthSessionCookieName string
|
||||
LocalUsers []LocalUser
|
||||
OAuthProviders map[string]OAuthServiceConfig
|
||||
OAuthWhitelist []string
|
||||
ConfiguredProviders []Provider
|
||||
AppURL string
|
||||
UUID string
|
||||
CookieDomain string
|
||||
SessionCookieName string
|
||||
CSRFCookieName string
|
||||
RedirectCookieName string
|
||||
OAuthSessionCookieName string
|
||||
LocalUsers []LocalUser
|
||||
OAuthProviders map[string]OAuthServiceConfig
|
||||
OAuthWhitelist []string
|
||||
ConfiguredProviders []Provider
|
||||
TrustedProxiesConfigured bool
|
||||
}
|
||||
|
||||
type Provider struct {
|
||||
|
||||
@@ -7,6 +7,16 @@ const (
|
||||
UserLDAP
|
||||
)
|
||||
|
||||
func (t UserSearchType) String() string {
|
||||
switch t {
|
||||
case UserLocal:
|
||||
return "local"
|
||||
case UserLDAP:
|
||||
return "ldap"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
type LDAPUser struct {
|
||||
DN string
|
||||
Groups []string
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
@@ -43,6 +44,10 @@ func (rule *UserAllowedRule) Evaluate(ctx *ACLContext) Effect {
|
||||
rule.Log.App.Debug().Msg("User is an OAuth user, checking OAuth whitelist")
|
||||
match, err := utils.CheckFilter(ctx.ACLs.OAuth.Whitelist, ctx.UserContext.OAuth.Email)
|
||||
if err != nil {
|
||||
if errors.Is(err, utils.ErrFilterEmpty) {
|
||||
rule.Log.App.Debug().Msg("OAuth whitelist is empty, abstaining")
|
||||
return EffectAbstain
|
||||
}
|
||||
rule.Log.App.Warn().Err(err).Str("item", ctx.UserContext.OAuth.Email).Msg("Invalid entry in OAuth whitelist")
|
||||
return EffectDeny
|
||||
}
|
||||
@@ -72,7 +77,7 @@ func (rule *UserAllowedRule) Evaluate(ctx *ACLContext) Effect {
|
||||
match, err := utils.CheckFilter(ctx.ACLs.Users.Allow, ctx.UserContext.GetUsername())
|
||||
|
||||
if err != nil {
|
||||
if err == utils.ErrFilterEmpty {
|
||||
if errors.Is(err, utils.ErrFilterEmpty) {
|
||||
return EffectAbstain
|
||||
}
|
||||
rule.Log.App.Warn().Err(err).Str("item", ctx.UserContext.GetUsername()).Msg("Invalid entry in users allow list")
|
||||
@@ -215,6 +220,10 @@ type IPAllowedRule struct {
|
||||
}
|
||||
|
||||
func (rule *IPAllowedRule) Evaluate(ctx *ACLContext) Effect {
|
||||
if !ctx.TrustedProxiesConfigured {
|
||||
return EffectAllow // We can't block the proxy
|
||||
}
|
||||
|
||||
// merge global and per-app block/allow lists
|
||||
blockedIps := append([]string{}, rule.Config.Auth.IP.Block...)
|
||||
allowedIPs := append([]string{}, rule.Config.Auth.IP.Allow...)
|
||||
@@ -263,6 +272,10 @@ type IPBypassedRule struct {
|
||||
}
|
||||
|
||||
func (rule *IPBypassedRule) Evaluate(ctx *ACLContext) Effect {
|
||||
if !ctx.TrustedProxiesConfigured {
|
||||
return EffectDeny
|
||||
}
|
||||
|
||||
// merge global and per-app bypass lists
|
||||
bypassList := append([]string{}, rule.Config.Auth.IP.Bypass...)
|
||||
if ctx.ACLs != nil {
|
||||
|
||||
@@ -44,6 +44,21 @@ func TestUserAllowedRule(t *testing.T) {
|
||||
},
|
||||
expected: EffectAbstain,
|
||||
},
|
||||
{
|
||||
name: "abstains when filter is empty",
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{
|
||||
OAuth: model.AppOAuth{Whitelist: ""},
|
||||
},
|
||||
UserContext: &model.UserContext{
|
||||
Provider: model.ProviderOAuth,
|
||||
OAuth: &model.OAuthContext{
|
||||
BaseContext: model.BaseContext{Username: "alice"},
|
||||
},
|
||||
},
|
||||
},
|
||||
expected: EffectAbstain,
|
||||
},
|
||||
{
|
||||
name: "allows OAuth user when email matches whitelist",
|
||||
ctx: &ACLContext{
|
||||
@@ -611,11 +626,20 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
ctx *ACLContext
|
||||
expected Effect
|
||||
}{
|
||||
{
|
||||
name: "when trusted proxies are not configured, IP is allowed",
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
{
|
||||
name: "allows when ACLs are nil and no global lists configured",
|
||||
ctx: &ACLContext{
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -625,7 +649,8 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Block: []string{"10.0.0.1"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -637,8 +662,9 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
},
|
||||
},
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -648,7 +674,8 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Allow: []string{"192.168.1.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("192.168.1.10"),
|
||||
IP: net.ParseIP("192.168.1.10"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -660,8 +687,9 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
},
|
||||
},
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("192.168.1.10"),
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("192.168.1.10"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -671,15 +699,17 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Allow: []string{"192.168.1.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "allows when no block or allow lists are configured",
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -692,7 +722,8 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
Allow: []string{"10.0.0.1"},
|
||||
},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -705,7 +736,8 @@ func TestIPAllowedRule(t *testing.T) {
|
||||
Allow: []string{"10.0.0.1"},
|
||||
},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -735,12 +767,23 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ctx *ACLContext
|
||||
expected Effect
|
||||
}{
|
||||
{
|
||||
name: "when trusted proxies are not configured, IP is not bypassed",
|
||||
rule: defaultIPBR,
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: false,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "deny when ACLs are nil and no global bypass",
|
||||
rule: defaultIPBR,
|
||||
ctx: &ACLContext{
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -748,8 +791,9 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
name: "allows when ACLs are nil but IP matches global bypass",
|
||||
rule: globBypassIPBR,
|
||||
ctx: &ACLContext{
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -757,8 +801,9 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
name: "denies when ACLs are nil and IP does not match global bypass",
|
||||
rule: globBypassIPBR,
|
||||
ctx: &ACLContext{
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("192.168.1.1"),
|
||||
ACLs: nil,
|
||||
IP: net.ParseIP("192.168.1.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -769,7 +814,8 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Bypass: []string{"10.0.0.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -780,7 +826,8 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Bypass: []string{"172.16.0.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -791,7 +838,8 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Bypass: []string{"10.0.0.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
IP: net.ParseIP("10.0.0.5"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
@@ -802,7 +850,8 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Bypass: []string{"10.0.0.0/24"}},
|
||||
},
|
||||
IP: net.ParseIP("192.168.1.1"),
|
||||
IP: net.ParseIP("192.168.1.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -810,8 +859,9 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
name: "denies when bypass list is empty",
|
||||
rule: defaultIPBR,
|
||||
ctx: &ACLContext{
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
ACLs: &model.App{},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectDeny,
|
||||
},
|
||||
@@ -822,7 +872,8 @@ func TestIPBypassedRule(t *testing.T) {
|
||||
ACLs: &model.App{
|
||||
IP: model.AppIP{Bypass: []string{"not-an-ip", "10.0.0.1"}},
|
||||
},
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
IP: net.ParseIP("10.0.0.1"),
|
||||
TrustedProxiesConfigured: true,
|
||||
},
|
||||
expected: EffectAllow,
|
||||
},
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/validators"
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
type LabelProvider interface {
|
||||
GetLabels(appDomain string) (*model.App, error)
|
||||
Lookup(locator func(name string, app *model.App) bool) error
|
||||
}
|
||||
|
||||
type AccessControlsService struct {
|
||||
@@ -35,27 +37,74 @@ func NewAccessControlsService(i AccessControlServiceInput) *AccessControlsServic
|
||||
}
|
||||
}
|
||||
|
||||
func (service *AccessControlsService) lookupStaticACLs(domain string) *model.App {
|
||||
var nameMatch *model.App
|
||||
func (service *AccessControlsService) getACLs(domain string, lookup func(locator func(name string, app *model.App) bool) error) (*model.App, error) {
|
||||
v := validators.NewDomainValidator(validators.DomainValidatorOptions{})
|
||||
|
||||
// First try to find a matching app by domain, then fallback to matching by app name (subdomain)
|
||||
for app, config := range service.config.Apps {
|
||||
if config.Config.Domain == domain {
|
||||
service.log.App.Debug().Str("name", app).Msg("Found matching container by domain")
|
||||
return &config
|
||||
var domainMatch *model.App
|
||||
var nameMatch *model.App
|
||||
var nameMatchedApps []string
|
||||
|
||||
locatorFunc := func(name string, app *model.App) bool {
|
||||
if app.Config.Domain != "" {
|
||||
err := v.Validate(app.Config.Domain, domain)
|
||||
if err == nil {
|
||||
service.log.App.Debug().Str("name", name).Msg("Found matching container by domain")
|
||||
domainMatch = app
|
||||
return true
|
||||
} else if !errors.Is(err, validators.ErrHostnameMismatch) {
|
||||
service.log.App.Debug().Str("name", name).Err(err).Msg("Domain validation failed")
|
||||
}
|
||||
}
|
||||
if strings.SplitN(domain, ".", 2)[0] == app {
|
||||
service.log.App.Debug().Str("name", app).Msg("Found matching container by app name")
|
||||
nameMatch = &config
|
||||
if strings.HasPrefix(strings.ToLower(domain), strings.ToLower(name+".")) {
|
||||
service.log.App.Debug().Str("name", name).Msg("Found matching container by app name")
|
||||
nameMatch = app
|
||||
nameMatchedApps = append(nameMatchedApps, name)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return nameMatch
|
||||
err := lookup(locatorFunc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if domainMatch != nil {
|
||||
service.log.App.Debug().Str("domain", domain).Msg("Found matching app by domain")
|
||||
return domainMatch, nil
|
||||
}
|
||||
|
||||
if nameMatch == nil {
|
||||
service.log.App.Debug().Str("domain", domain).Msg("No match found for domain, skipping")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if len(nameMatchedApps) > 1 {
|
||||
service.log.App.Warn().Str("domain", domain).Strs("apps", nameMatchedApps).Msg("Multiple apps matched domain by name, app names must be unique, using last match")
|
||||
}
|
||||
|
||||
service.log.App.Debug().Str("domain", domain).Msg("Found matching app by app name")
|
||||
return nameMatch, nil
|
||||
}
|
||||
|
||||
func (service *AccessControlsService) lookupStaticACLs(domain string) (*model.App, error) {
|
||||
return service.getACLs(domain, func(locator func(name string, app *model.App) bool) error {
|
||||
for app, config := range service.config.Apps {
|
||||
if ok := locator(app, &config); ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (service *AccessControlsService) GetAccessControls(domain string) (*model.App, error) {
|
||||
// First check in the static config
|
||||
app := service.lookupStaticACLs(domain)
|
||||
app, err := service.lookupStaticACLs(domain)
|
||||
|
||||
// Will never return an error here, but we need to check it
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if app != nil {
|
||||
service.log.App.Debug().Msg("Using static ACLs for app")
|
||||
@@ -64,9 +113,9 @@ func (service *AccessControlsService) GetAccessControls(domain string) (*model.A
|
||||
|
||||
// If we have a label provider configured, try to get ACLs from it
|
||||
if service.labelProvider != nil {
|
||||
return service.labelProvider.GetLabels(domain)
|
||||
return service.getACLs(domain, service.labelProvider.Lookup)
|
||||
}
|
||||
|
||||
// no labels
|
||||
// No labels
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -4,224 +4,184 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
)
|
||||
|
||||
type mockLabelProvider struct {
|
||||
getLabelsFn func(appDomain string) (*model.App, error)
|
||||
calledWith string
|
||||
callCount int
|
||||
type mockProvider struct {
|
||||
acls map[string]model.App
|
||||
shouldError bool
|
||||
}
|
||||
|
||||
func (m *mockLabelProvider) GetLabels(appDomain string) (*model.App, error) {
|
||||
m.calledWith = appDomain
|
||||
m.callCount++
|
||||
if m.getLabelsFn != nil {
|
||||
return m.getLabelsFn(appDomain)
|
||||
func newMockProvider(acls map[string]model.App, shouldError bool) *mockProvider {
|
||||
return &mockProvider{acls: acls, shouldError: shouldError}
|
||||
}
|
||||
|
||||
func (m *mockProvider) Lookup(locator func(name string, app *model.App) bool) error {
|
||||
if m.shouldError {
|
||||
return errors.New("mock error")
|
||||
}
|
||||
return nil, nil
|
||||
for name, app := range m.acls {
|
||||
if ok := locator(name, &app); ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestLookupStaticACLs(t *testing.T) {
|
||||
func TestAccessControlsService(t *testing.T) {
|
||||
log := logger.NewLogger().WithTestConfig()
|
||||
log.Init()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
apps map[string]model.App
|
||||
domain string
|
||||
expectNil bool
|
||||
expectedDomain string
|
||||
name string
|
||||
domain string
|
||||
acls map[string]model.App
|
||||
want *model.App
|
||||
}{
|
||||
{
|
||||
name: "returns nil when no apps are configured",
|
||||
apps: nil,
|
||||
domain: "foo.example.com",
|
||||
expectNil: true,
|
||||
name: "returns ACLs for domain",
|
||||
domain: "example.com",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
want: &model.App{Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
{
|
||||
name: "returns nil when no app matches",
|
||||
apps: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "foo.example.com"}},
|
||||
name: "returns ACLs for domain with port",
|
||||
domain: "example.com:8080",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
domain: "bar.example.com",
|
||||
expectNil: true,
|
||||
want: &model.App{Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
{
|
||||
name: "matches by exact domain",
|
||||
apps: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "foo.example.com"}},
|
||||
name: "returns ACLs for domain with trailing dot",
|
||||
domain: "example.com.",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
domain: "foo.example.com",
|
||||
expectedDomain: "foo.example.com",
|
||||
want: &model.App{Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
{
|
||||
name: "matches by app name when domain does not match any app",
|
||||
apps: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "configured.example.com"}},
|
||||
name: "returns ACLs for non-ascii domain",
|
||||
domain: "bücher.example.com",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "bücher.example.com"}},
|
||||
},
|
||||
domain: "foo.example.com",
|
||||
expectedDomain: "configured.example.com",
|
||||
want: &model.App{Config: model.AppConfig{Domain: "bücher.example.com"}},
|
||||
},
|
||||
{
|
||||
name: "matches by app name for nested subdomains",
|
||||
apps: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "configured.example.com"}},
|
||||
name: "returns ACLs for punycode domain and non-ascii config",
|
||||
domain: "bücher.example.com",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "xn--bcher-kva.example.com"}},
|
||||
},
|
||||
domain: "foo.sub.example.com",
|
||||
expectedDomain: "configured.example.com",
|
||||
want: &model.App{Config: model.AppConfig{Domain: "xn--bcher-kva.example.com"}},
|
||||
},
|
||||
{
|
||||
name: "selects the app matching by domain among multiple apps",
|
||||
apps: map[string]model.App{
|
||||
"unrelated": {Config: model.AppConfig{Domain: "other.example.com"}},
|
||||
"target": {Config: model.AppConfig{Domain: "foo.example.com"}},
|
||||
name: "returns ACLs with case-insensitive matching",
|
||||
domain: "Example.com",
|
||||
acls: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
domain: "foo.example.com",
|
||||
expectedDomain: "foo.example.com",
|
||||
want: &model.App{Config: model.AppConfig{Domain: "example.com"}},
|
||||
},
|
||||
{
|
||||
name: "falls back to name matching when domain fails",
|
||||
domain: "app.example.com",
|
||||
acls: map[string]model.App{
|
||||
"app": {Path: model.AppPath{Allow: "/foo"}},
|
||||
},
|
||||
want: &model.App{Path: model.AppPath{Allow: "/foo"}},
|
||||
},
|
||||
{
|
||||
name: "name matching is case-insensitive",
|
||||
domain: "aPp.example.com",
|
||||
acls: map[string]model.App{
|
||||
"APP": {Path: model.AppPath{Allow: "/foo"}},
|
||||
},
|
||||
want: &model.App{Path: model.AppPath{Allow: "/foo"}},
|
||||
},
|
||||
{
|
||||
name: "returns nil when no ACLs are found",
|
||||
domain: "example.com",
|
||||
acls: map[string]model.App{},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
// run once for a mock provider
|
||||
for _, test := range tests {
|
||||
t.Run(test.name+"(getACLs)", func(t *testing.T) {
|
||||
mock := newMockProvider(test.acls, false)
|
||||
acls := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{Apps: tt.apps},
|
||||
LabelProvider: nil,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: mock,
|
||||
})
|
||||
got := svc.lookupStaticACLs(tt.domain)
|
||||
if tt.expectNil {
|
||||
assert.Nil(t, got)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, tt.expectedDomain, got.Config.Domain)
|
||||
app, err := acls.getACLs(test.domain, mock.Lookup)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.want, app)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAccessControls(t *testing.T) {
|
||||
log := logger.NewLogger().WithTestConfig()
|
||||
log.Init()
|
||||
|
||||
t.Run("returns static ACLs when domain matches", func(t *testing.T) {
|
||||
config := model.Config{
|
||||
Apps: map[string]model.App{
|
||||
"foo": {
|
||||
Config: model.AppConfig{Domain: "foo.example.com"},
|
||||
Users: model.AppUsers{Allow: "alice"},
|
||||
// run again for static acls
|
||||
for _, test := range tests {
|
||||
t.Run(test.name+"(staticACLs)", func(t *testing.T) {
|
||||
acls := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{
|
||||
Apps: test.acls,
|
||||
},
|
||||
},
|
||||
}
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &config,
|
||||
LabelProvider: nil,
|
||||
})
|
||||
app, err := acls.lookupStaticACLs(test.domain)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, test.want, app)
|
||||
})
|
||||
}
|
||||
|
||||
got, err := svc.GetAccessControls("foo.example.com")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "foo.example.com", got.Config.Domain)
|
||||
assert.Equal(t, "alice", got.Users.Allow)
|
||||
// get acls should return an error when the provider fails
|
||||
mock := newMockProvider(map[string]model.App{}, true)
|
||||
acls := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
})
|
||||
_, err := acls.getACLs("example.com", mock.Lookup)
|
||||
require.Error(t, err)
|
||||
|
||||
t.Run("returns nil when no static match and no label provider", func(t *testing.T) {
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: nil,
|
||||
})
|
||||
|
||||
got, err := svc.GetAccessControls("unknown.example.com")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
|
||||
t.Run("returns nil when label provider pointer wraps a nil interface", func(t *testing.T) {
|
||||
var provider LabelProvider
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: provider, // nil provider
|
||||
})
|
||||
|
||||
got, err := svc.GetAccessControls("unknown.example.com")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
|
||||
t.Run("falls back to label provider when no static match", func(t *testing.T) {
|
||||
expected := &model.App{
|
||||
Config: model.AppConfig{Domain: "dynamic.example.com"},
|
||||
Users: model.AppUsers{Allow: "bob"},
|
||||
}
|
||||
mock := &mockLabelProvider{
|
||||
getLabelsFn: func(appDomain string) (*model.App, error) {
|
||||
return expected, nil
|
||||
},
|
||||
}
|
||||
var provider LabelProvider = mock
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: provider,
|
||||
})
|
||||
|
||||
got, err := svc.GetAccessControls("dynamic.example.com")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Same(t, expected, got)
|
||||
assert.Equal(t, "dynamic.example.com", mock.calledWith)
|
||||
assert.Equal(t, 1, mock.callCount)
|
||||
})
|
||||
|
||||
t.Run("does not call label provider when static match found", func(t *testing.T) {
|
||||
mock := &mockLabelProvider{}
|
||||
var provider LabelProvider = mock
|
||||
config := model.Config{
|
||||
// get access controls should get acls from
|
||||
// static when static acls are configured
|
||||
acls = NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{
|
||||
Apps: map[string]model.App{
|
||||
"foo": {Config: model.AppConfig{Domain: "foo.example.com"}},
|
||||
},
|
||||
}
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &config,
|
||||
LabelProvider: provider,
|
||||
})
|
||||
|
||||
got, err := svc.GetAccessControls("foo.example.com")
|
||||
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "foo.example.com", got.Config.Domain)
|
||||
assert.Equal(t, 0, mock.callCount)
|
||||
},
|
||||
})
|
||||
app, err := acls.GetAccessControls("foo.example.com")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, &model.App{Config: model.AppConfig{Domain: "foo.example.com"}}, app)
|
||||
|
||||
t.Run("propagates label provider errors", func(t *testing.T) {
|
||||
providerErr := errors.New("provider boom")
|
||||
mock := &mockLabelProvider{
|
||||
getLabelsFn: func(appDomain string) (*model.App, error) {
|
||||
return nil, providerErr
|
||||
},
|
||||
}
|
||||
var provider LabelProvider = mock
|
||||
svc := NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: provider,
|
||||
})
|
||||
// should return nil for no apps
|
||||
app, err = acls.GetAccessControls("bar.example.com")
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, app)
|
||||
|
||||
got, err := svc.GetAccessControls("dynamic.example.com")
|
||||
|
||||
assert.Nil(t, got)
|
||||
assert.ErrorIs(t, err, providerErr)
|
||||
assert.Equal(t, 1, mock.callCount)
|
||||
// Should use label provider if available
|
||||
mock = newMockProvider(map[string]model.App{
|
||||
"bar": {
|
||||
Config: model.AppConfig{Domain: "bar.example.com"},
|
||||
},
|
||||
}, false)
|
||||
acls = NewAccessControlsService(AccessControlServiceInput{
|
||||
Log: log,
|
||||
Config: &model.Config{},
|
||||
LabelProvider: mock,
|
||||
})
|
||||
app, err = acls.GetAccessControls("bar.example.com")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, &model.App{Config: model.AppConfig{Domain: "bar.example.com"}}, app)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"math/big"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/steveiliop56/ding"
|
||||
@@ -16,6 +15,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/repository"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/cache"
|
||||
"go.uber.org/dig"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -69,21 +69,13 @@ type AuthService struct {
|
||||
tailscale *TailscaleService
|
||||
policyEngine *PolicyEngine
|
||||
|
||||
lockdown struct {
|
||||
active bool
|
||||
until time.Time
|
||||
ctx context.Context
|
||||
cancelFunc context.CancelFunc
|
||||
mu sync.RWMutex
|
||||
}
|
||||
dummyHash string
|
||||
|
||||
caches struct {
|
||||
login *CacheStore[LoginAttempt]
|
||||
oauth *CacheStore[OAuthPendingSession]
|
||||
ldap *CacheStore[[]string]
|
||||
login *cache.CacheStore[LoginAttempt]
|
||||
oauth *cache.CacheStore[OAuthPendingSession]
|
||||
ldap *cache.CacheStore[[]string]
|
||||
}
|
||||
|
||||
maxLoginLimits int
|
||||
}
|
||||
|
||||
type AuthServiceInput struct {
|
||||
@@ -101,7 +93,7 @@ type AuthServiceInput struct {
|
||||
PolicyEngine *PolicyEngine
|
||||
}
|
||||
|
||||
func NewAuthService(i AuthServiceInput) *AuthService {
|
||||
func NewAuthService(i AuthServiceInput) (*AuthService, error) {
|
||||
service := &AuthService{
|
||||
log: i.Log,
|
||||
runtime: i.Runtime,
|
||||
@@ -114,19 +106,19 @@ func NewAuthService(i AuthServiceInput) *AuthService {
|
||||
policyEngine: i.PolicyEngine,
|
||||
}
|
||||
|
||||
// get the max login limits based on the number of users and the configured max retries
|
||||
service.maxLoginLimits = service.calculateLockdownLimit()
|
||||
// dummy hash
|
||||
dummyHash, err := bcrypt.GenerateFromPassword([]byte(utils.GenerateString(8)), bcrypt.DefaultCost)
|
||||
|
||||
loginCacheSize := 0
|
||||
|
||||
if !service.config.Auth.LockdownEnabled {
|
||||
loginCacheSize = service.maxLoginLimits
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate dummy hash: %w", err)
|
||||
}
|
||||
|
||||
service.dummyHash = string(dummyHash)
|
||||
|
||||
// caches setup
|
||||
oauthCache := NewCacheStore[OAuthPendingSession](256)
|
||||
loginCache := NewCacheStore[LoginAttempt](loginCacheSize)
|
||||
ldapCache := NewCacheStore[[]string](1024)
|
||||
oauthCache := cache.NewCacheStore[OAuthPendingSession](256)
|
||||
loginCache := cache.NewCacheStore[LoginAttempt](service.calculateLockdownLimit())
|
||||
ldapCache := cache.NewCacheStore[[]string](1024)
|
||||
|
||||
service.caches.oauth = oauthCache
|
||||
service.caches.login = loginCache
|
||||
@@ -148,7 +140,28 @@ func NewAuthService(i AuthServiceInput) *AuthService {
|
||||
}
|
||||
}, ding.RingMinor)
|
||||
|
||||
return service
|
||||
i.Ding.Go(func(ctx context.Context) {
|
||||
ticker := time.NewTicker(15 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
service.log.App.Debug().Msg("Updating login cache limits")
|
||||
service.caches.login.SetMaxSize(service.calculateLockdownLimit())
|
||||
service.log.App.Debug().Msg("Login cache limits updated")
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}, ding.RingMinor)
|
||||
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func (auth *AuthService) DummyPasswordCheck(password string) {
|
||||
bcrypt.CompareHashAndPassword([]byte(auth.dummyHash), []byte(password))
|
||||
}
|
||||
|
||||
func (auth *AuthService) SearchUser(username string) (*model.UserSearch, error) {
|
||||
@@ -245,10 +258,6 @@ func (auth *AuthService) GetLDAPUser(userDN string) (*model.LDAPUser, error) {
|
||||
}
|
||||
|
||||
func (auth *AuthService) IsAccountLocked(identifier string) (bool, int) {
|
||||
if locked, remaining := auth.IsInLockdown(); locked {
|
||||
return true, remaining
|
||||
}
|
||||
|
||||
if auth.config.Auth.LoginMaxRetries <= 0 || auth.config.Auth.LoginTimeout <= 0 {
|
||||
return false, 0
|
||||
}
|
||||
@@ -271,15 +280,7 @@ func (auth *AuthService) RecordLoginAttempt(identifier string, success bool) {
|
||||
return
|
||||
}
|
||||
|
||||
if !success && auth.config.Auth.LockdownEnabled && auth.caches.login.Size() >= auth.maxLoginLimits {
|
||||
if locked, _ := auth.IsInLockdown(); locked {
|
||||
return
|
||||
}
|
||||
go auth.lockdownMode()
|
||||
return
|
||||
}
|
||||
|
||||
auth.caches.login.WithLock(func(actions CacheStoreActions[LoginAttempt]) {
|
||||
auth.caches.login.WithLock(func(actions cache.CacheStoreActions[LoginAttempt]) {
|
||||
entry, ok := actions.Get(identifier)
|
||||
|
||||
if !ok {
|
||||
@@ -344,7 +345,7 @@ func (auth *AuthService) CreateSession(ctx context.Context, data repository.Sess
|
||||
return nil, fmt.Errorf("tailscale service not configured, cannot create session for tailscale user")
|
||||
}
|
||||
|
||||
uuid, err := uuid.NewRandom()
|
||||
u, err := uuid.NewRandom()
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to generate session uuid: %w", err)
|
||||
@@ -361,7 +362,7 @@ func (auth *AuthService) CreateSession(ctx context.Context, data repository.Sess
|
||||
expiresAt := time.Now().Add(time.Duration(expiry) * time.Second)
|
||||
|
||||
session := repository.CreateSessionParams{
|
||||
UUID: uuid.String(),
|
||||
UUID: u.String(),
|
||||
Username: data.Username,
|
||||
Email: data.Email,
|
||||
Name: data.Name,
|
||||
@@ -616,62 +617,7 @@ func (auth *AuthService) GetOAuthPendingSession(sessionId string) (*OAuthPending
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (auth *AuthService) lockdownMode() {
|
||||
auth.lockdown.mu.Lock()
|
||||
|
||||
if auth.lockdown.active {
|
||||
auth.lockdown.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(auth.ctx)
|
||||
|
||||
auth.log.App.Warn().Msg("Too many failed login attempts, entering lockdown mode")
|
||||
|
||||
auth.lockdown.active = true
|
||||
auth.lockdown.ctx = ctx
|
||||
auth.lockdown.cancelFunc = cancel
|
||||
|
||||
d := time.Duration(auth.config.Auth.LoginTimeout) * time.Second
|
||||
auth.lockdown.until = time.Now().Add(d)
|
||||
timer := time.NewTimer(d)
|
||||
|
||||
auth.lockdown.mu.Unlock()
|
||||
|
||||
defer cancel()
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-timer.C:
|
||||
// Timer expired, end lockdown
|
||||
case <-ctx.Done():
|
||||
// Context cancelled, end lockdown
|
||||
}
|
||||
|
||||
auth.lockdown.mu.Lock()
|
||||
|
||||
auth.log.App.Info().Msg("Exiting lockdown mode")
|
||||
|
||||
auth.caches.login.Clear()
|
||||
auth.lockdown.active = false
|
||||
auth.lockdown.until = time.Time{}
|
||||
auth.lockdown.ctx = nil
|
||||
auth.lockdown.cancelFunc = nil
|
||||
|
||||
auth.lockdown.mu.Unlock()
|
||||
}
|
||||
|
||||
func (auth *AuthService) IsInLockdown() (bool, int) {
|
||||
auth.lockdown.mu.RLock()
|
||||
defer auth.lockdown.mu.RUnlock()
|
||||
if auth.lockdown.active {
|
||||
remaining := int(time.Until(auth.lockdown.until).Seconds())
|
||||
return true, remaining
|
||||
}
|
||||
return false, 0
|
||||
}
|
||||
|
||||
// mostly a testing function, not useful for anything else
|
||||
// ClearLoginAttempts is a testing function, not useful for anything else
|
||||
func (auth *AuthService) ClearLoginAttempts() {
|
||||
auth.caches.login.Clear()
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveiliop56/ding"
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
@@ -31,7 +31,6 @@ type DockerServiceInput struct {
|
||||
}
|
||||
|
||||
func NewDockerService(i DockerServiceInput) (*DockerService, error) {
|
||||
|
||||
client, err := client.NewClientWithOpts(client.FromEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -68,49 +67,38 @@ func (docker *DockerService) inspectContainer(containerId string) (container.Ins
|
||||
return docker.client.ContainerInspect(docker.context, containerId)
|
||||
}
|
||||
|
||||
func (docker *DockerService) GetLabels(appDomain string) (*model.App, error) {
|
||||
func (docker *DockerService) Lookup(locator func(name string, app *model.App) bool) error {
|
||||
if !docker.isConnected {
|
||||
docker.log.App.Debug().Msg("Docker service not connected, returning empty labels")
|
||||
return nil, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
containers, err := docker.getContainers()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return fmt.Errorf("failed to get containers: %w", err)
|
||||
}
|
||||
|
||||
for _, ctr := range containers {
|
||||
inspect, err := docker.inspectContainer(ctr.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
docker.log.App.Error().Err(err).Msgf("Failed to inspect container %s", ctr.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
labels, err := decoders.DecodeLabels[model.Apps](inspect.Config.Labels, "apps")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
docker.log.App.Warn().Err(err).Msgf("Failed to decode labels for container %s", ctr.ID)
|
||||
continue
|
||||
}
|
||||
|
||||
var nameMatch *model.App
|
||||
|
||||
// First try to find a matching app by domain, then fallback to matching by app name (subdomain)
|
||||
for appName, appLabels := range labels.Apps {
|
||||
if appLabels.Config.Domain == appDomain {
|
||||
docker.log.App.Debug().Str("id", inspect.ID).Str("name", inspect.Name).Msg("Found matching container by domain")
|
||||
return &appLabels, nil
|
||||
for app, config := range labels.Apps {
|
||||
if ok := locator(app, &config); ok {
|
||||
return nil
|
||||
}
|
||||
if strings.SplitN(appDomain, ".", 2)[0] == appName {
|
||||
docker.log.App.Debug().Str("id", inspect.ID).Str("name", inspect.Name).Msg("Found matching container by app name")
|
||||
nameMatch = &appLabels
|
||||
}
|
||||
}
|
||||
|
||||
if nameMatch != nil {
|
||||
return nameMatch, nil
|
||||
}
|
||||
}
|
||||
|
||||
docker.log.App.Debug().Str("domain", appDomain).Msg("No matching container found for domain")
|
||||
return nil, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (docker *DockerService) watchAndClose(ctx context.Context) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/decoders"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/validators"
|
||||
"go.uber.org/dig"
|
||||
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
@@ -22,31 +23,23 @@ import (
|
||||
"k8s.io/client-go/rest"
|
||||
)
|
||||
|
||||
type ingressEntry struct {
|
||||
name string
|
||||
app model.App
|
||||
}
|
||||
|
||||
type ingressKey struct {
|
||||
namespace string
|
||||
name string
|
||||
}
|
||||
|
||||
type ingressAppKey struct {
|
||||
ingressKey
|
||||
appName string
|
||||
}
|
||||
|
||||
type ingressApp struct {
|
||||
domain string
|
||||
appName string
|
||||
app model.App
|
||||
}
|
||||
|
||||
type KubernetesService struct {
|
||||
log *logger.Logger
|
||||
|
||||
client dynamic.Interface
|
||||
started bool
|
||||
mu sync.RWMutex
|
||||
ingressApps map[ingressKey][]ingressApp
|
||||
domainIndex map[string]ingressAppKey
|
||||
appNameIndex map[string]ingressAppKey
|
||||
client dynamic.Interface
|
||||
connected bool
|
||||
mu sync.RWMutex
|
||||
ingressEntries map[ingressKey][]ingressEntry
|
||||
}
|
||||
|
||||
type KubernetesServiceInput struct {
|
||||
@@ -86,90 +79,45 @@ func NewKubernetesService(i KubernetesServiceInput) (*KubernetesService, error)
|
||||
i.Log.App.Debug().Str("api", gvr.GroupVersion().String()).Msg("Successfully accessed Ingress API, starting watcher")
|
||||
|
||||
service := &KubernetesService{
|
||||
log: i.Log,
|
||||
client: client,
|
||||
ingressApps: make(map[ingressKey][]ingressApp),
|
||||
domainIndex: make(map[string]ingressAppKey),
|
||||
appNameIndex: make(map[string]ingressAppKey),
|
||||
log: i.Log,
|
||||
client: client,
|
||||
ingressEntries: make(map[ingressKey][]ingressEntry),
|
||||
}
|
||||
|
||||
i.Ding.Go(func(ctx context.Context) {
|
||||
service.watchGVR(gvr, ctx)
|
||||
}, ding.RingMajor)
|
||||
|
||||
service.started = true
|
||||
service.connected = true
|
||||
i.Log.App.Debug().Msg("Kubernetes label provider started successfully")
|
||||
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func (k *KubernetesService) addIngressApps(namespace, name string, apps []ingressApp) {
|
||||
func (k *KubernetesService) addIngressEntries(key ingressKey, entries []ingressEntry) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
|
||||
key := ingressKey{namespace, name}
|
||||
// Remove existing entries for this ingress
|
||||
if existing, ok := k.ingressApps[key]; ok {
|
||||
for _, app := range existing {
|
||||
delete(k.domainIndex, app.domain)
|
||||
delete(k.appNameIndex, app.appName)
|
||||
}
|
||||
}
|
||||
// Add new entries
|
||||
k.ingressApps[key] = apps
|
||||
for _, app := range apps {
|
||||
appKey := ingressAppKey{key, app.appName}
|
||||
k.domainIndex[app.domain] = appKey
|
||||
k.appNameIndex[app.appName] = appKey
|
||||
}
|
||||
k.ingressEntries[key] = entries
|
||||
}
|
||||
|
||||
func (k *KubernetesService) removeIngress(namespace, name string) {
|
||||
func (k *KubernetesService) removeIngress(key ingressKey) {
|
||||
k.mu.Lock()
|
||||
defer k.mu.Unlock()
|
||||
|
||||
key := ingressKey{namespace, name}
|
||||
if apps, ok := k.ingressApps[key]; ok {
|
||||
for _, app := range apps {
|
||||
delete(k.domainIndex, app.domain)
|
||||
delete(k.appNameIndex, app.appName)
|
||||
}
|
||||
delete(k.ingressApps, key)
|
||||
}
|
||||
delete(k.ingressEntries, key)
|
||||
}
|
||||
|
||||
func (k *KubernetesService) getByDomain(domain string) *model.App {
|
||||
func (k *KubernetesService) getEntry(locator func(name string, app *model.App) bool) {
|
||||
k.mu.RLock()
|
||||
defer k.mu.RUnlock()
|
||||
|
||||
if appKey, ok := k.domainIndex[domain]; ok {
|
||||
if apps, ok := k.ingressApps[appKey.ingressKey]; ok {
|
||||
for i := range apps {
|
||||
app := &apps[i]
|
||||
if app.domain == domain && app.appName == appKey.appName {
|
||||
return &app.app
|
||||
}
|
||||
// O(n^2) is not great but the number of ingress entries is expected to be small
|
||||
for _, entries := range k.ingressEntries {
|
||||
for _, entry := range entries {
|
||||
if ok := locator(entry.name, &entry.app); ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *KubernetesService) getByAppName(appName string) *model.App {
|
||||
k.mu.RLock()
|
||||
defer k.mu.RUnlock()
|
||||
|
||||
if appKey, ok := k.appNameIndex[appName]; ok {
|
||||
if apps, ok := k.ingressApps[appKey.ingressKey]; ok {
|
||||
for i := range apps {
|
||||
app := &apps[i]
|
||||
if app.appName == appName {
|
||||
return &app.app
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (k *KubernetesService) extractPaths(rule map[string]any) ([]string, error) {
|
||||
@@ -219,7 +167,8 @@ func (k *KubernetesService) extractHosts(item *unstructured.Unstructured) ([]str
|
||||
}
|
||||
paths, err := k.extractPaths(rule)
|
||||
if err != nil {
|
||||
// This is purely to warn users, it doesn't affect our ability to extract hosts so we won't fail the whole operation
|
||||
// This is purely to warn users
|
||||
// It doesn't affect our ability to extract hosts, so we won't fail the whole operation
|
||||
k.log.App.Warn().Err(err).Str("namespace", item.GetNamespace()).Str("name", item.GetName()).Msg("Failed to extract paths from ingress rule")
|
||||
continue
|
||||
}
|
||||
@@ -235,44 +184,71 @@ func (k *KubernetesService) extractHosts(item *unstructured.Unstructured) ([]str
|
||||
}
|
||||
|
||||
func (k *KubernetesService) updateFromItem(item *unstructured.Unstructured) {
|
||||
namespace := item.GetNamespace()
|
||||
name := item.GetName()
|
||||
key := ingressKey{
|
||||
namespace: item.GetNamespace(),
|
||||
name: item.GetName(),
|
||||
}
|
||||
|
||||
annotations := item.GetAnnotations()
|
||||
if annotations == nil {
|
||||
k.removeIngress(namespace, name)
|
||||
k.removeIngress(key)
|
||||
return
|
||||
}
|
||||
|
||||
hosts, err := k.extractHosts(item)
|
||||
if err != nil {
|
||||
k.removeIngress(namespace, name)
|
||||
k.removeIngress(key)
|
||||
return
|
||||
}
|
||||
|
||||
if len(hosts) == 0 {
|
||||
k.log.App.Warn().Str("namespace", key.namespace).Str("name", key.name).Msg("No hosts found in ingress, skipping")
|
||||
k.removeIngress(key)
|
||||
return
|
||||
}
|
||||
|
||||
labels, err := decoders.DecodeLabels[model.Apps](annotations, "apps")
|
||||
if err != nil {
|
||||
k.log.App.Warn().Err(err).Str("namespace", namespace).Str("name", name).Msg("Failed to decode ingress labels, skipping")
|
||||
k.removeIngress(namespace, name)
|
||||
k.log.App.Warn().Err(err).Str("namespace", key.namespace).Str("name", key.name).Msg("Failed to decode ingress labels, skipping")
|
||||
k.removeIngress(key)
|
||||
return
|
||||
}
|
||||
var apps []ingressApp
|
||||
for appName, appLabels := range labels.Apps {
|
||||
if appLabels.Config.Domain == "" {
|
||||
continue
|
||||
|
||||
var entries []ingressEntry
|
||||
|
||||
v := validators.NewDomainValidator(validators.DomainValidatorOptions{})
|
||||
|
||||
for name, config := range labels.Apps {
|
||||
if config.Config.Domain != "" {
|
||||
hostname, err := v.SafeHostname(config.Config.Domain)
|
||||
if err != nil {
|
||||
k.log.App.Warn().Err(err).Str("namespace", key.namespace).Str("name", key.name).Str("domain", config.Config.Domain).Msg("Domain is invalid, matching will rely on app name")
|
||||
} else if slices.Contains(hosts, hostname) {
|
||||
entries = append(entries, ingressEntry{
|
||||
name: name,
|
||||
app: config,
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(hosts) > 0 && !slices.Contains(hosts, appLabels.Config.Domain) {
|
||||
k.log.App.Warn().Str("namespace", namespace).Str("name", name).Str("appName", appName).Str("domain", appLabels.Config.Domain).Msg("App domain does not match any hosts defined in ingress rules, skipping")
|
||||
continue
|
||||
|
||||
for _, host := range hosts {
|
||||
if strings.HasPrefix(strings.ToLower(host), strings.ToLower(name+".")) {
|
||||
entries = append(entries, ingressEntry{
|
||||
name: name,
|
||||
app: config,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
apps = append(apps, ingressApp{
|
||||
domain: appLabels.Config.Domain,
|
||||
appName: appName,
|
||||
app: appLabels,
|
||||
})
|
||||
}
|
||||
if len(apps) == 0 {
|
||||
k.removeIngress(namespace, name)
|
||||
} else {
|
||||
k.addIngressApps(namespace, name, apps)
|
||||
|
||||
if len(entries) == 0 {
|
||||
k.removeIngress(key)
|
||||
return
|
||||
}
|
||||
|
||||
k.addIngressEntries(key, entries)
|
||||
}
|
||||
|
||||
func (k *KubernetesService) resyncGVR(gvr schema.GroupVersionResource, ctx context.Context) error {
|
||||
@@ -315,7 +291,10 @@ func (k *KubernetesService) runWatcher(gvr schema.GroupVersionResource, w watch.
|
||||
case watch.Added, watch.Modified:
|
||||
k.updateFromItem(item)
|
||||
case watch.Deleted:
|
||||
k.removeIngress(item.GetNamespace(), item.GetName())
|
||||
k.removeIngress(ingressKey{
|
||||
namespace: item.GetNamespace(),
|
||||
name: item.GetName(),
|
||||
})
|
||||
}
|
||||
case <-resyncTicker.C:
|
||||
if err := k.resyncGVR(gvr, ctx); err != nil {
|
||||
@@ -362,25 +341,13 @@ func (k *KubernetesService) watchGVR(gvr schema.GroupVersionResource, ctx contex
|
||||
}
|
||||
}
|
||||
|
||||
func (k *KubernetesService) GetLabels(appDomain string) (*model.App, error) {
|
||||
if !k.started {
|
||||
k.log.App.Debug().Str("domain", appDomain).Msg("Kubernetes label provider not started, skipping")
|
||||
return nil, nil
|
||||
func (k *KubernetesService) Lookup(locator func(name string, app *model.App) bool) error {
|
||||
if !k.connected {
|
||||
k.log.App.Debug().Msg("Kubernetes label provider not started, skipping")
|
||||
return nil
|
||||
}
|
||||
|
||||
// First check cache
|
||||
app := k.getByDomain(appDomain)
|
||||
if app != nil {
|
||||
k.log.App.Debug().Str("domain", appDomain).Msg("Found labels in cache by domain")
|
||||
return app, nil
|
||||
}
|
||||
appName := strings.SplitN(appDomain, ".", 2)[0]
|
||||
app = k.getByAppName(appName)
|
||||
if app != nil {
|
||||
k.log.App.Debug().Str("domain", appDomain).Str("appName", appName).Msg("Found labels in cache by app name")
|
||||
return app, nil
|
||||
}
|
||||
k.getEntry(locator)
|
||||
|
||||
k.log.App.Debug().Str("domain", appDomain).Msg("No labels found for domain")
|
||||
return nil, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
||||
@@ -25,47 +26,66 @@ func TestKubernetesService(t *testing.T) {
|
||||
description: "Cache by domain returns app and misses unknown domain",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
app := model.App{Config: model.AppConfig{Domain: "foo.example.com"}}
|
||||
svc.addIngressApps("default", "my-ingress", []ingressApp{
|
||||
{domain: "foo.example.com", appName: "foo", app: app},
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: app,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
got := svc.getByDomain("foo.example.com")
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "foo.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "foo.example.com", got.Config.Domain)
|
||||
|
||||
got = svc.getByDomain("notfound.example.com")
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Cache by app name returns app and misses unknown name",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
app := model.App{Config: model.AppConfig{Domain: "bar.example.com"}}
|
||||
svc.addIngressApps("default", "my-ingress", []ingressApp{
|
||||
{domain: "bar.example.com", appName: "bar", app: app},
|
||||
})
|
||||
|
||||
got := svc.getByAppName("bar")
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "bar.example.com", got.Config.Domain)
|
||||
|
||||
got = svc.getByAppName("notfound")
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "RemoveIngress clears domain and app name entries",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
app := model.App{Config: model.AppConfig{Domain: "baz.example.com"}}
|
||||
svc.addIngressApps("default", "my-ingress", []ingressApp{
|
||||
{domain: "baz.example.com", appName: "baz", app: app},
|
||||
app := model.App{Config: model.AppConfig{Domain: "foo.example.com"}}
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: app,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
svc.removeIngress("default", "my-ingress")
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "foo.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "foo.example.com", got.Config.Domain)
|
||||
|
||||
got := svc.getByDomain("baz.example.com")
|
||||
assert.Nil(t, got)
|
||||
got = svc.getByAppName("baz")
|
||||
got = nil
|
||||
svc.removeIngress(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
})
|
||||
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "foo.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
@@ -73,67 +93,130 @@ func TestKubernetesService(t *testing.T) {
|
||||
description: "AddIngressApps replaces stale entries for the same ingress",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
old := model.App{Config: model.AppConfig{Domain: "old.example.com"}}
|
||||
svc.addIngressApps("default", "my-ingress", []ingressApp{
|
||||
{domain: "old.example.com", appName: "old", app: old},
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: old,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
updated := model.App{Config: model.AppConfig{Domain: "new.example.com"}}
|
||||
svc.addIngressApps("default", "my-ingress", []ingressApp{
|
||||
{domain: "new.example.com", appName: "new", app: updated},
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: updated,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
got := svc.getByDomain("old.example.com")
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "old.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
|
||||
got = svc.getByDomain("new.example.com")
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "new.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "new.example.com", got.Config.Domain)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "GetLabels returns app from cache when started",
|
||||
description: "GetLabels returns app from cache when connected",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
svc.started = true
|
||||
svc.connected = true
|
||||
|
||||
app := model.App{Config: model.AppConfig{Domain: "hit.example.com"}}
|
||||
svc.addIngressApps("default", "ing", []ingressApp{
|
||||
{domain: "hit.example.com", appName: "hit", app: app},
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: app,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
got, err := svc.GetLabels("hit.example.com")
|
||||
var got *model.App
|
||||
err := svc.Lookup(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "hit.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "hit.example.com", got.Config.Domain)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "GetLabels returns empty app on cache miss when started",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
svc.started = true
|
||||
svc.connected = true
|
||||
|
||||
got, err := svc.GetLabels("notfound.example.com")
|
||||
var got *model.App
|
||||
err := svc.Lookup(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "notfound.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got)
|
||||
require.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "GetLabels resolves app by app name",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
svc.started = true
|
||||
svc.connected = true
|
||||
|
||||
app := model.App{Config: model.AppConfig{Domain: "myapp.internal.example.com"}}
|
||||
svc.addIngressApps("default", "ing", []ingressApp{
|
||||
{domain: "myapp.internal.example.com", appName: "myapp", app: app},
|
||||
app := model.App{Path: model.AppPath{Allow: "/foo"}}
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: app,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
got, err := svc.GetLabels("myapp.internal.example.com")
|
||||
var got *model.App
|
||||
err := svc.Lookup(func(name string, app *model.App) bool {
|
||||
if strings.HasPrefix("foo.internal.example.com", "foo.") {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "myapp.internal.example.com", got.Config.Domain)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "/foo", got.Path.Allow)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "GetLabels returns empty app when service not yet started",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
got, err := svc.GetLabels("anything.example.com")
|
||||
var got *model.App
|
||||
err := svc.Lookup(func(name string, app *model.App) bool {
|
||||
return false
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
@@ -148,30 +231,437 @@ func TestKubernetesService(t *testing.T) {
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
"tinyauth.apps.myapp.users.allow": "alice",
|
||||
})
|
||||
item.Object["spec"] = map[string]any{
|
||||
"rules": []any{
|
||||
map[string]any{
|
||||
"host": "myapp.example.com",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
got := svc.getByDomain("myapp.example.com")
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "myapp.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "myapp.example.com", got.Config.Domain)
|
||||
assert.Equal(t, "alice", got.Users.Allow)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Update from item skips annotations with no hosts",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
})
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "myapp.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem fails when label parsing fails",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
"tinyauth.apps.myapp.users.break": "i-dont-exist",
|
||||
})
|
||||
item.Object["spec"] = map[string]any{
|
||||
"rules": []any{
|
||||
map[string]any{
|
||||
"host": "myapp.example.com",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "myapp.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
require.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem with no annotations removes existing cache entries",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
app := model.App{Config: model.AppConfig{Domain: "todelete.example.com"}}
|
||||
svc.addIngressApps("default", "test-ingress", []ingressApp{
|
||||
{domain: "todelete.example.com", appName: "todelete", app: app},
|
||||
svc.addIngressEntries(ingressKey{
|
||||
namespace: "default",
|
||||
name: "my-ingress",
|
||||
}, []ingressEntry{
|
||||
{
|
||||
app: app,
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetName("my-ingress")
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
got := svc.getByDomain("todelete.example.com")
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if app.Config.Domain == "todelete.example.com" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractPaths returns all non empty paths from a rule",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
rule := map[string]any{
|
||||
"http": map[string]any{
|
||||
"paths": []any{
|
||||
map[string]any{"path": "/"},
|
||||
map[string]any{"path": "/api"},
|
||||
map[string]any{"path": ""},
|
||||
map[string]any{"pathType": "Prefix"},
|
||||
"not-a-map",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
paths, err := svc.extractPaths(rule)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"/", "/api"}, paths)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractPaths returns nothing when http or paths are missing",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
paths, err := svc.extractPaths(map[string]any{})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, paths)
|
||||
|
||||
paths, err = svc.extractPaths(map[string]any{
|
||||
"http": map[string]any{},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, paths)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractPaths errors when http is not a map",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
paths, err := svc.extractPaths(map[string]any{
|
||||
"http": "invalid",
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, paths)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractPaths errors when paths is not a slice",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
paths, err := svc.extractPaths(map[string]any{
|
||||
"http": map[string]any{
|
||||
"paths": "invalid",
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, paths)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractHosts returns hosts from all rules",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "foo.example.com",
|
||||
"http": map[string]any{
|
||||
"paths": []any{
|
||||
map[string]any{"path": "/"},
|
||||
},
|
||||
},
|
||||
},
|
||||
map[string]any{
|
||||
"host": "bar.example.com",
|
||||
},
|
||||
map[string]any{
|
||||
"host": "",
|
||||
},
|
||||
"not-a-map",
|
||||
}, "spec", "rules"))
|
||||
|
||||
hosts, err := svc.extractHosts(&item)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"foo.example.com", "bar.example.com"}, hosts)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractHosts still returns hosts when a rule has no catch all path",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "foo.example.com",
|
||||
"http": map[string]any{
|
||||
"paths": []any{
|
||||
map[string]any{"path": "/api"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
hosts, err := svc.extractHosts(&item)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"foo.example.com"}, hosts)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractHosts still returns hosts when path extraction fails",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "foo.example.com",
|
||||
"http": "invalid",
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
hosts, err := svc.extractHosts(&item)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"foo.example.com"}, hosts)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractHosts returns nothing when spec.rules is missing",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
|
||||
hosts, err := svc.extractHosts(&item)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, hosts)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "ExtractHosts errors when spec.rules is not a slice",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
require.NoError(t, unstructured.SetNestedField(item.Object, "invalid", "spec", "rules"))
|
||||
|
||||
hosts, err := svc.extractHosts(&item)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, hosts)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem registers app when its domain matches an ingress host",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
})
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "myapp.example.com",
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if name == "myapp" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "myapp.example.com", got.Config.Domain)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem registers app when its name matches an ingress host prefix",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.users.allow": "alice",
|
||||
})
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "MyApp.example.com",
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if name == "myapp" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, "alice", got.Users.Allow)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem skips apps that match neither host nor name",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
})
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "other.example.com",
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
got = app
|
||||
return true
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem falls back to app name when the domain is invalid",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace("default")
|
||||
item.SetName("test-ingress")
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "not a domain",
|
||||
})
|
||||
require.NoError(t, unstructured.SetNestedSlice(item.Object, []any{
|
||||
map[string]any{
|
||||
"host": "myapp.example.com",
|
||||
},
|
||||
}, "spec", "rules"))
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
if name == "myapp" {
|
||||
got = app
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
require.NotNil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem removes entries when host extraction fails",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
key := ingressKey{
|
||||
namespace: "default",
|
||||
name: "test-ingress",
|
||||
}
|
||||
svc.addIngressEntries(key, []ingressEntry{
|
||||
{
|
||||
app: model.App{Config: model.AppConfig{Domain: "stale.example.com"}},
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace(key.namespace)
|
||||
item.SetName(key.name)
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.domain": "myapp.example.com",
|
||||
})
|
||||
require.NoError(t, unstructured.SetNestedField(item.Object, "invalid", "spec", "rules"))
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
got = app
|
||||
return true
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "UpdateFromItem removes entries when annotations are not decodable",
|
||||
run: func(t *testing.T, svc *KubernetesService) {
|
||||
key := ingressKey{
|
||||
namespace: "default",
|
||||
name: "test-ingress",
|
||||
}
|
||||
svc.addIngressEntries(key, []ingressEntry{
|
||||
{
|
||||
app: model.App{Config: model.AppConfig{Domain: "stale.example.com"}},
|
||||
name: "foo",
|
||||
},
|
||||
})
|
||||
|
||||
item := unstructured.Unstructured{}
|
||||
item.SetNamespace(key.namespace)
|
||||
item.SetName(key.name)
|
||||
item.SetAnnotations(map[string]string{
|
||||
"tinyauth.apps.myapp.config.oauthWhitelist": "[",
|
||||
})
|
||||
|
||||
svc.updateFromItem(&item)
|
||||
|
||||
var got *model.App
|
||||
svc.getEntry(func(name string, app *model.App) bool {
|
||||
got = app
|
||||
return true
|
||||
})
|
||||
assert.Nil(t, got)
|
||||
},
|
||||
},
|
||||
@@ -180,10 +670,8 @@ func TestKubernetesService(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.description, func(t *testing.T) {
|
||||
svc := &KubernetesService{
|
||||
ingressApps: make(map[ingressKey][]ingressApp),
|
||||
domainIndex: make(map[string]ingressAppKey),
|
||||
appNameIndex: make(map[string]ingressAppKey),
|
||||
log: log,
|
||||
ingressEntries: make(map[ingressKey][]ingressEntry),
|
||||
log: log,
|
||||
}
|
||||
test.run(t, svc)
|
||||
})
|
||||
|
||||
@@ -24,6 +24,7 @@ func NewOAuthService(config model.OAuthServiceConfig, id string, ctx context.Con
|
||||
httpClient := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: config.Insecure,
|
||||
MinVersion: tls.VersionTLS12,
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/repository"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/cache"
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
@@ -158,9 +159,9 @@ type OIDCService struct {
|
||||
issuer string
|
||||
|
||||
caches struct {
|
||||
code *CacheStore[AuthorizeCodeEntry]
|
||||
usedCode *CacheStore[UsedCodeEntry]
|
||||
authorize *CacheStore[AuthorizeRequest]
|
||||
code *cache.CacheStore[AuthorizeCodeEntry]
|
||||
usedCode *cache.CacheStore[UsedCodeEntry]
|
||||
authorize *cache.CacheStore[AuthorizeRequest]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -339,11 +340,11 @@ func NewOIDCService(i OIDCServiceInput) (*OIDCService, error) {
|
||||
i.Ding.Go(service.cleanupRoutine, ding.RingMinor)
|
||||
|
||||
// Create caches
|
||||
codeCash := NewCacheStore[AuthorizeCodeEntry](256)
|
||||
usedCode := NewCacheStore[UsedCodeEntry](256)
|
||||
authorize := NewCacheStore[AuthorizeRequest](256)
|
||||
codeCache := cache.NewCacheStore[AuthorizeCodeEntry](256)
|
||||
usedCode := cache.NewCacheStore[UsedCodeEntry](256)
|
||||
authorize := cache.NewCacheStore[AuthorizeRequest](256)
|
||||
|
||||
service.caches.code = codeCash
|
||||
service.caches.code = codeCache
|
||||
service.caches.usedCode = usedCode
|
||||
service.caches.authorize = authorize
|
||||
|
||||
@@ -503,7 +504,7 @@ func (service *OIDCService) GetCodeEntry(codeHash string, clientId string) (*Aut
|
||||
var entry AuthorizeCodeEntry
|
||||
var ok bool
|
||||
|
||||
service.caches.code.WithLock(func(actions CacheStoreActions[AuthorizeCodeEntry]) {
|
||||
service.caches.code.WithLock(func(actions cache.CacheStoreActions[AuthorizeCodeEntry]) {
|
||||
entry, ok = actions.Get(codeHash)
|
||||
|
||||
if !ok {
|
||||
|
||||
@@ -29,10 +29,11 @@ type Rule interface {
|
||||
}
|
||||
|
||||
type ACLContext struct {
|
||||
ACLs *model.App
|
||||
UserContext *model.UserContext
|
||||
IP net.IP
|
||||
Path string
|
||||
ACLs *model.App
|
||||
UserContext *model.UserContext
|
||||
IP net.IP
|
||||
Path string
|
||||
TrustedProxiesConfigured bool
|
||||
}
|
||||
|
||||
type PolicyEngine struct {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/model"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils"
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils/logger"
|
||||
"github.com/tinyauthapp/tinyauth/pkg/cache"
|
||||
"go.uber.org/dig"
|
||||
)
|
||||
|
||||
@@ -59,8 +60,8 @@ type TailscaleService struct {
|
||||
apiToken string
|
||||
|
||||
caches struct {
|
||||
devices *CacheStore[tailscaleAPIDevices]
|
||||
users *CacheStore[tailscaleAPIUsers]
|
||||
devices *cache.CacheStore[tailscaleAPIDevices]
|
||||
users *cache.CacheStore[tailscaleAPIUsers]
|
||||
}
|
||||
|
||||
urls struct {
|
||||
@@ -100,8 +101,8 @@ func NewTailscaleService(i TailscaleServiceInput) (*TailscaleService, error) {
|
||||
apiToken: apiToken,
|
||||
}
|
||||
|
||||
devicesCache := NewCacheStore[tailscaleAPIDevices](0)
|
||||
usersCache := NewCacheStore[tailscaleAPIUsers](0)
|
||||
devicesCache := cache.NewCacheStore[tailscaleAPIDevices](0)
|
||||
usersCache := cache.NewCacheStore[tailscaleAPIUsers](0)
|
||||
|
||||
s.caches.devices = devicesCache
|
||||
s.caches.users = usersCache
|
||||
|
||||
+13
-4
@@ -58,7 +58,15 @@ func CreateTestConfigs(t *testing.T) (model.Config, model.RuntimeConfig) {
|
||||
Domain: "path-allow.example.com",
|
||||
},
|
||||
Path: model.AppPath{
|
||||
Allow: "/allowed",
|
||||
Allow: "^/allowed$",
|
||||
},
|
||||
},
|
||||
"app_path_block": {
|
||||
Config: model.AppConfig{
|
||||
Domain: "path-block.example.com",
|
||||
},
|
||||
Path: model.AppPath{
|
||||
Block: "^/admin$",
|
||||
},
|
||||
},
|
||||
"app_user_allow": {
|
||||
@@ -163,9 +171,10 @@ func CreateTestConfigs(t *testing.T) (model.Config, model.RuntimeConfig) {
|
||||
},
|
||||
},
|
||||
},
|
||||
CookieDomain: "example.com",
|
||||
AppURL: "https://tinyauth.example.com",
|
||||
SessionCookieName: "tinyauth-session",
|
||||
CookieDomain: "example.com",
|
||||
AppURL: "https://tinyauth.example.com",
|
||||
SessionCookieName: "tinyauth-session",
|
||||
TrustedProxiesConfigured: true,
|
||||
}
|
||||
|
||||
return config, runtime
|
||||
|
||||
@@ -7,10 +7,55 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/weppos/publicsuffix-go/publicsuffix"
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
// GetCookieDomain parses the app url and returns the domain value to use for cookies.
|
||||
var (
|
||||
ErrEmptyURL = fmt.Errorf("invalid url")
|
||||
)
|
||||
|
||||
func SafeParseAppURL(str string) (string, error) {
|
||||
if strings.TrimSpace(str) == "" {
|
||||
return "", ErrEmptyURL
|
||||
}
|
||||
|
||||
u, err := url.Parse(str)
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid url: %w", err)
|
||||
}
|
||||
|
||||
if u.Host == "" ||
|
||||
(u.Scheme != "http" &&
|
||||
u.Scheme != "https") {
|
||||
return "", fmt.Errorf("invalid url, must be in format https(s)://host")
|
||||
}
|
||||
|
||||
hostname := strings.ToLower(u.Hostname())
|
||||
hostname = strings.TrimSuffix(hostname, ".")
|
||||
|
||||
if netIP := net.ParseIP(hostname); netIP != nil {
|
||||
return "", fmt.Errorf("ip addresses not allowed")
|
||||
}
|
||||
|
||||
hostname, err = idna.Lookup.ToASCII(hostname)
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to convert hostname to ascii: %w", err)
|
||||
}
|
||||
|
||||
appURL := fmt.Sprintf("%s://%s", u.Scheme, hostname)
|
||||
|
||||
if u.Port() != "" {
|
||||
appURL += ":" + u.Port()
|
||||
}
|
||||
|
||||
return appURL, nil
|
||||
}
|
||||
|
||||
// GetCookieDomain parses the app URL and returns the domain value to use for cookies.
|
||||
// When auth for subdomains is enabled, it strips the leftmost label
|
||||
// GetCookieDomain assumes the app URL is first parsed with SafeParseAppURL
|
||||
// (e.g. sub1.sub2.domain.com -> sub2.domain.com), otherwise it returns the full hostname.
|
||||
func GetCookieDomain(appUrl string, subdomainsEnabled bool) (string, error) {
|
||||
u, err := url.Parse(appUrl)
|
||||
@@ -21,10 +66,6 @@ func GetCookieDomain(appUrl string, subdomainsEnabled bool) (string, error) {
|
||||
|
||||
hostname := strings.ToLower(u.Hostname())
|
||||
|
||||
if netIP := net.ParseIP(hostname); netIP != nil {
|
||||
return "", fmt.Errorf("ip addresses not allowed")
|
||||
}
|
||||
|
||||
parts := strings.Split(hostname, ".")
|
||||
|
||||
if len(parts) < 2 {
|
||||
|
||||
@@ -7,7 +7,86 @@ import (
|
||||
"github.com/tinyauthapp/tinyauth/internal/utils"
|
||||
)
|
||||
|
||||
func TestGetRootDomain(t *testing.T) {
|
||||
func TestSafeParseAPPURL(t *testing.T) {
|
||||
// Normal app url
|
||||
appURL := "http://sub.tinyauth.app"
|
||||
expected := "http://sub.tinyauth.app"
|
||||
result, err := utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Strip path
|
||||
appURL = "http://sub.tinyauth.app/path"
|
||||
expected = "http://sub.tinyauth.app"
|
||||
result, err = utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Preserve port
|
||||
appURL = "http://sub.tinyauth.app:8080"
|
||||
expected = "http://sub.tinyauth.app:8080"
|
||||
result, err = utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Remove trailing dot
|
||||
appURL = "http://sub.tinyauth.app."
|
||||
expected = "http://sub.tinyauth.app"
|
||||
result, err = utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Convert to ascii
|
||||
appURL = "http://bücher.example.com"
|
||||
expected = "http://xn--bcher-kva.example.com"
|
||||
result, err = utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Lowercase
|
||||
appURL = "HTTP://SUb.tinyAUth.aPP"
|
||||
expected = "http://sub.tinyauth.app"
|
||||
result, err = utils.SafeParseAppURL(appURL)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, expected, result)
|
||||
|
||||
// Empty string
|
||||
appURL = ""
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorIs(t, err, utils.ErrEmptyURL)
|
||||
|
||||
// Invalid URL
|
||||
appURL = "invalidurl"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "invalid url")
|
||||
|
||||
// Non http or https URL
|
||||
appURL = "ftp://sub.tinyauth.app"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "invalid url")
|
||||
|
||||
// Invalid punycode
|
||||
appURL = "http://ab--cd.example.com"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "failed to convert hostname to ascii")
|
||||
|
||||
// IP address
|
||||
appURL = "http://10.10.10.10"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "ip addresses not allowed")
|
||||
|
||||
// IPv6 address
|
||||
appURL = "http://[::1]:8080"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "ip addresses not allowed")
|
||||
|
||||
// Invalid URL
|
||||
appURL = "://"
|
||||
_, err = utils.SafeParseAppURL(appURL)
|
||||
assert.ErrorContains(t, err, "invalid url")
|
||||
}
|
||||
|
||||
func TestGetCookieDomain(t *testing.T) {
|
||||
// Normal case
|
||||
domain := "http://sub.tinyauth.app"
|
||||
expected := "tinyauth.app"
|
||||
@@ -27,11 +106,6 @@ func TestGetRootDomain(t *testing.T) {
|
||||
_, err = utils.GetCookieDomain(domain, true)
|
||||
assert.EqualError(t, err, "invalid app url, must be in format subdomain.domain.tld or domain.tld")
|
||||
|
||||
// IP address
|
||||
domain = "http://10.10.10.10"
|
||||
_, err = utils.GetCookieDomain(domain, true)
|
||||
assert.ErrorContains(t, err, "ip addresses not allowed")
|
||||
|
||||
// Invalid URL
|
||||
domain = "http://[::1]:namedport"
|
||||
_, err = utils.GetCookieDomain(domain, true)
|
||||
@@ -56,6 +130,11 @@ func TestGetRootDomain(t *testing.T) {
|
||||
_, err = utils.GetCookieDomain(domain, true)
|
||||
assert.ErrorContains(t, err, "domain in public suffix list, cannot set cookies")
|
||||
|
||||
// Domain managed by ICANN without subdomain
|
||||
domain = "http://co.uk"
|
||||
_, err = utils.GetCookieDomain(domain, true)
|
||||
assert.ErrorContains(t, err, "domain in public suffix list, cannot set cookies")
|
||||
|
||||
// Domain without subdomain
|
||||
domain = "http://tinyauth.app"
|
||||
expected = "tinyauth.app"
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Public packages
|
||||
|
||||
This directory contains packages that can be used by
|
||||
other projects.
|
||||
|
||||
While we try to maintain a consistent API, no promises
|
||||
can be made for non-breaking changes throughout updates
|
||||
as we constantly need to make changes to comply with the
|
||||
needs of Tinyauth. We advise pinning the version of the
|
||||
package you wish to use.
|
||||
+19
-3
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package cache
|
||||
|
||||
import (
|
||||
"slices"
|
||||
@@ -33,8 +33,8 @@ func NewCacheStore[T any](maxSize int) *CacheStore[T] {
|
||||
}
|
||||
}
|
||||
|
||||
// With lock allows performing multiple operations on the cache store atomically.
|
||||
// The provided mutate function receives a set of actions (Set, Get, Delete) that
|
||||
// WithLock allows performing multiple operations on a single lock.
|
||||
// The provided mutate function receives a set of actions (Set, Get, Delete, Update) that
|
||||
// can be used to manipulate the cache store within the locked context.
|
||||
func (cs *CacheStore[T]) WithLock(mutate func(actions CacheStoreActions[T])) {
|
||||
cs.mu.Lock()
|
||||
@@ -195,3 +195,19 @@ func (cs *CacheStore[T]) Clear() {
|
||||
cs.cache = make(map[string]cacheEntry[T])
|
||||
cs.order = make([]string, 0)
|
||||
}
|
||||
|
||||
func (cs *CacheStore[T]) SetMaxSize(maxSize int) {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
cs.maxSize = maxSize
|
||||
for len(cs.cache) > maxSize {
|
||||
if !cs.evictOne() {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
func (cs *CacheStore[T]) GetMaxSize() int {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
return cs.maxSize
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package cache
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
@@ -316,6 +316,21 @@ func TestCacheStoreSizeAndClear(t *testing.T) {
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
func TestCacheStoreWithMaxSize(t *testing.T) {
|
||||
cs := NewCacheStore[string](0)
|
||||
assert.Equal(t, 0, cs.Size())
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
cs.Set(strconv.Itoa(i), strconv.Itoa(i), 0)
|
||||
}
|
||||
|
||||
assert.Equal(t, 100, cs.Size())
|
||||
|
||||
cs.SetMaxSize(10)
|
||||
|
||||
assert.Equal(t, 10, cs.Size())
|
||||
}
|
||||
|
||||
func TestCacheStoreWithLock(t *testing.T) {
|
||||
cs := NewCacheStore[int](0)
|
||||
cs.Set("counter", 1, 0)
|
||||
@@ -0,0 +1,190 @@
|
||||
// Package validators provides validators for various types of data.
|
||||
//
|
||||
// Domain validator is a simple utility that ensures two domains are exact
|
||||
// matches while ensuring that techniques used to bypass such checks do
|
||||
// not impact the validation.
|
||||
|
||||
package validators
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/idna"
|
||||
)
|
||||
|
||||
// Errors
|
||||
var (
|
||||
ErrSchemeMismatch = fmt.Errorf("scheme mismatch")
|
||||
ErrPortMismatch = fmt.Errorf("port mismatch")
|
||||
ErrHostnameMismatch = fmt.Errorf("hostname mismatch")
|
||||
)
|
||||
|
||||
// DomainValidatorOptions is a set of options for DomainValidator.
|
||||
type DomainValidatorOptions struct {
|
||||
// Ensure domains have the same scheme.
|
||||
WithScheme bool
|
||||
// Ensure domains have the same port.
|
||||
WithPort bool
|
||||
// Specify a list of allowed schemes if WithScheme is set to true.
|
||||
AllowedSchemes []string
|
||||
}
|
||||
|
||||
// DomainValidator is a simple utility that ensures two domains are exact
|
||||
// matches while ensuring that techniques used to bypass such checks do
|
||||
// not impact the validation.
|
||||
type DomainValidator struct {
|
||||
opts DomainValidatorOptions
|
||||
}
|
||||
|
||||
// NewDomainValidator creates a new DomainValidator.
|
||||
func NewDomainValidator(opts DomainValidatorOptions) *DomainValidator {
|
||||
return &DomainValidator{
|
||||
opts: opts,
|
||||
}
|
||||
}
|
||||
|
||||
func (v *DomainValidator) checkScheme(rawURL string) error {
|
||||
if !v.opts.WithScheme {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(v.opts.AllowedSchemes) == 0 {
|
||||
return fmt.Errorf("allowed schemes must be specified")
|
||||
}
|
||||
|
||||
for _, scheme := range v.opts.AllowedSchemes {
|
||||
if strings.HasPrefix(strings.ToLower(rawURL), strings.ToLower(scheme)+"://") {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("invalid scheme")
|
||||
|
||||
}
|
||||
|
||||
func (v *DomainValidator) getURL(i string) (*url.URL, error) {
|
||||
if i == "" {
|
||||
return nil, fmt.Errorf("url cannot be empty")
|
||||
}
|
||||
|
||||
if v.opts.WithScheme {
|
||||
err := v.checkScheme(i)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid scheme: %w", err)
|
||||
}
|
||||
|
||||
u, err := url.Parse(i)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse input url: %w", err)
|
||||
}
|
||||
|
||||
if u.Host == "" || u.Scheme == "" {
|
||||
return nil, fmt.Errorf("missing host or scheme in url: %s", i)
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
rawURL := i
|
||||
|
||||
if !strings.Contains(i, "://") {
|
||||
// From godoc: [scheme:][//[userinfo@]host][/]path[?query][#fragment]
|
||||
// So, we can omit the colon and tell the Go URL lib that we want
|
||||
// to parse the URL without the scheme. If we don't do this,
|
||||
// the URL lib will parse our entire domain as the path.
|
||||
rawURL = "//" + i
|
||||
}
|
||||
|
||||
u, err := url.Parse(rawURL)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse host: %w", err)
|
||||
}
|
||||
|
||||
if u.Host == "" {
|
||||
return nil, fmt.Errorf("missing host in url: %s", i)
|
||||
}
|
||||
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (v *DomainValidator) getHostname(hostname string) (string, error) {
|
||||
hostname = strings.ToLower(hostname)
|
||||
hostname = strings.TrimSuffix(hostname, ".")
|
||||
if net.ParseIP(hostname) != nil {
|
||||
return "", fmt.Errorf("ip addresses are not supported")
|
||||
}
|
||||
hostname, err := idna.Lookup.ToASCII(hostname)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to convert hostname to ascii: %w", err)
|
||||
}
|
||||
return hostname, nil
|
||||
}
|
||||
|
||||
// Validate ensures that two domains are exact matches with the
|
||||
// options defined in the DomainValidatorOptions. It ensures that the
|
||||
// inputs are proper URLs and contain a host. It lowercases the hostnames
|
||||
// and removes the trailing dot. Finally, it checks that the hostnames are
|
||||
// equal unless WithScheme or WithPort is set to true where it also
|
||||
// validates the scheme and port respectively.
|
||||
func (v *DomainValidator) Validate(expected, actual string) error {
|
||||
eu, err := v.getURL(expected)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
au, err := v.getURL(actual)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if v.opts.WithScheme {
|
||||
if eu.Scheme != au.Scheme {
|
||||
return ErrSchemeMismatch
|
||||
}
|
||||
}
|
||||
|
||||
if v.opts.WithPort {
|
||||
if eu.Port() != au.Port() {
|
||||
return ErrPortMismatch
|
||||
}
|
||||
}
|
||||
|
||||
euf, err := v.getHostname(eu.Hostname())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
auf, err := v.getHostname(au.Hostname())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if euf != auf {
|
||||
return ErrHostnameMismatch
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SafeHostname uses the internal validation for domains that the validator uses
|
||||
// to parse a hostname. It ensures the input URL is a valid URL, that a host
|
||||
// is present and that the hostname is lowercased and without a trailing dot.
|
||||
func (v *DomainValidator) SafeHostname(input string) (string, error) {
|
||||
u, err := v.getURL(input)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return v.getHostname(u.Hostname())
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDomainValidator_SafeHostname(t *testing.T) {
|
||||
type testCase struct {
|
||||
description string
|
||||
options DomainValidatorOptions
|
||||
input string
|
||||
expected string
|
||||
errorFunc func(t *testing.T, e error)
|
||||
}
|
||||
|
||||
tests := []testCase{
|
||||
{
|
||||
description: "Empty url fails",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "url cannot be empty")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "URL without host fails",
|
||||
input: "/foo",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "missing host in url")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Invalid url fails",
|
||||
input: "foo:foo",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "failed to parse host")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "With scheme and invalid url should fail",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https"}},
|
||||
input: "https://foo:foo",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "failed to parse input url")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Scheme disabled with scheme should pass",
|
||||
input: "https://example.com",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "Domain without scheme should parse if scheme is disabled",
|
||||
input: "example.com",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "Domain without scheme should not parse if scheme is enabled",
|
||||
options: DomainValidatorOptions{WithScheme: true},
|
||||
input: "example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "invalid scheme")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Domain with scheme and disallowed scheme should fail",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https"}},
|
||||
input: "foo://example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "invalid scheme")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Domain with scheme and allowed scheme should pass",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https"}},
|
||||
input: "https://example.com",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "Domain should get lowercased",
|
||||
input: "EXAMPLE.COM",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "DNS dot should be removed",
|
||||
input: "example.com.",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "IPv4 address should fail",
|
||||
input: "127.0.0.1",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "ip addresses are not supported")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "IPv6 address should fail",
|
||||
input: "[::1]",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "ip addresses are not supported")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Domains with unicode characters should be allowed",
|
||||
input: "bücher.example.com",
|
||||
expected: "xn--bcher-kva.example.com",
|
||||
},
|
||||
{
|
||||
description: "Invalid IDNA domain should fail",
|
||||
input: "ab--cd.example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "invalid label")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "With port enabled without any port should work",
|
||||
options: DomainValidatorOptions{WithPort: true},
|
||||
input: "example.com",
|
||||
expected: "example.com",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.description, func(t *testing.T) {
|
||||
v := NewDomainValidator(test.options)
|
||||
res, err := v.SafeHostname(test.input)
|
||||
if test.errorFunc != nil {
|
||||
test.errorFunc(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.expected, res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainValidator_Validate(t *testing.T) {
|
||||
type testCase struct {
|
||||
description string
|
||||
options DomainValidatorOptions
|
||||
expected string
|
||||
actual string
|
||||
errorFunc func(t *testing.T, e error)
|
||||
}
|
||||
|
||||
tests := []testCase{
|
||||
{
|
||||
description: "Invalid expected domain fails checks",
|
||||
expected: "foo:foo",
|
||||
actual: "bar.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "failed to parse host:")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Invalid check domain fails checks",
|
||||
expected: "example.com",
|
||||
actual: "foo:foo",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "failed to parse host:")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Valid domains with non-matching schemes should fail",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https", "http"}},
|
||||
expected: "https://example.com",
|
||||
actual: "http://example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorIs(t, e, ErrSchemeMismatch)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Valid domains with matching schemes should pass",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https", "http"}},
|
||||
expected: "https://example.com",
|
||||
actual: "https://example.com",
|
||||
},
|
||||
{
|
||||
description: "Port validation with ports enabled and empty ports should work",
|
||||
options: DomainValidatorOptions{WithPort: true},
|
||||
expected: "example.com",
|
||||
actual: "example.com",
|
||||
},
|
||||
{
|
||||
description: "Port validation should pass with same port",
|
||||
options: DomainValidatorOptions{WithPort: true},
|
||||
expected: "example.com:8080",
|
||||
actual: "example.com:8080",
|
||||
},
|
||||
{
|
||||
description: "Port enabled with scheme and matching port should pass",
|
||||
options: DomainValidatorOptions{WithPort: true},
|
||||
expected: "https://example.com:443",
|
||||
actual: "https://example.com:443",
|
||||
},
|
||||
{
|
||||
description: "Failure to format expected domain should fail",
|
||||
expected: "ab--cd.example.com",
|
||||
actual: "example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "idna: invalid label")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Failure to format check domain should fail",
|
||||
expected: "example.com",
|
||||
actual: "ab--cd.example.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorContains(t, e, "idna: invalid label")
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Valid domains with matching schemes and ports should pass",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https", "http"}, WithPort: true},
|
||||
expected: "https://example.com:8080",
|
||||
actual: "https://example.com:8080",
|
||||
},
|
||||
{
|
||||
description: "Valid domains with matching schemes should pass",
|
||||
options: DomainValidatorOptions{WithScheme: true, AllowedSchemes: []string{"https", "http"}},
|
||||
expected: "https://example.com",
|
||||
actual: "https://example.com",
|
||||
},
|
||||
{
|
||||
description: "Valid domains with non matching ports should fail",
|
||||
options: DomainValidatorOptions{WithPort: true},
|
||||
expected: "example.com:8080",
|
||||
actual: "example.com:8085",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorIs(t, e, ErrPortMismatch)
|
||||
},
|
||||
},
|
||||
{
|
||||
description: "Valid domains without ports or schemes should pass",
|
||||
actual: "example.com",
|
||||
expected: "example.com",
|
||||
},
|
||||
{
|
||||
description: "Unicode valid domains should pass",
|
||||
expected: "xn--bcher-kva.example.com",
|
||||
actual: "bücher.example.com",
|
||||
},
|
||||
{
|
||||
description: "Unicode valid domains should pass (reverse)",
|
||||
expected: "bücher.example.com",
|
||||
actual: "xn--bcher-kva.example.com",
|
||||
},
|
||||
{
|
||||
description: "Non matching hostnames should fail",
|
||||
expected: "example.com",
|
||||
actual: "foo.com",
|
||||
errorFunc: func(t *testing.T, e error) {
|
||||
assert.ErrorIs(t, e, ErrHostnameMismatch)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.description, func(t *testing.T) {
|
||||
v := NewDomainValidator(test.options)
|
||||
err := v.Validate(test.expected, test.actual)
|
||||
if test.errorFunc != nil {
|
||||
test.errorFunc(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user