mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2026-03-14 10:42:03 +00:00
Compare commits
5 Commits
nightly
...
feat/proxy
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1feffaa4d2 | ||
|
|
c2a57b57b8 | ||
|
|
5b2fa47c0e | ||
|
|
13bb3ca682 | ||
|
|
81cb695d0b |
16
integration/.env
Normal file
16
integration/.env
Normal file
@@ -0,0 +1,16 @@
|
||||
# Nginx configuration
|
||||
NGINX_VERSION=1.29
|
||||
|
||||
# Whoami configuration
|
||||
WHOAMI_VERSION=latest
|
||||
|
||||
# Traefik configuration
|
||||
TRAEFIK_VERSION=v3.6
|
||||
TINYAUTH_HOST=tinyauth.127.0.0.1.sslip.io
|
||||
WHOAMI_HOST=whoami.127.0.0.1.sslip.io
|
||||
|
||||
# Envoy configuration
|
||||
ENVOY_VERSION=v1.33-latest
|
||||
|
||||
# Tinyauth configuration
|
||||
TINYAUTH_VERSION=dev
|
||||
15
integration/config.yml
Normal file
15
integration/config.yml
Normal file
@@ -0,0 +1,15 @@
|
||||
appUrl: http://tinyauth.127.0.0.1.sslip.io
|
||||
|
||||
auth:
|
||||
users: test:$2a$10$eG88kFow83l5YRSlTSL2o.sZimjxFHrpiKdaSUZqpLBGX7Y2.4PZG
|
||||
|
||||
log:
|
||||
json: true
|
||||
level: trace
|
||||
|
||||
apps:
|
||||
whoami:
|
||||
config:
|
||||
domain: whoami.127.0.0.1.sslip.io
|
||||
path:
|
||||
allow: /allow
|
||||
16
integration/docker-compose.envoy.yml
Normal file
16
integration/docker-compose.envoy.yml
Normal file
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
envoy:
|
||||
image: envoyproxy/envoy:${ENVOY_VERSION}
|
||||
ports:
|
||||
- 80:80
|
||||
volumes:
|
||||
- ./envoy.yml:/etc/envoy/envoy.yaml:ro
|
||||
|
||||
whoami:
|
||||
image: traefik/whoami:${WHOAMI_VERSION}
|
||||
|
||||
tinyauth:
|
||||
image: ghcr.io/steveiliop56/tinyauth:${TINYAUTH_VERSION}
|
||||
command: --experimental.configfile=/data/config.yml
|
||||
volumes:
|
||||
- ./config.yml:/data/config.yml:ro
|
||||
16
integration/docker-compose.nginx.yml
Normal file
16
integration/docker-compose.nginx.yml
Normal file
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:${NGINX_VERSION}
|
||||
ports:
|
||||
- 80:80
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
|
||||
whoami:
|
||||
image: traefik/whoami:${WHOAMI_VERSION}
|
||||
|
||||
tinyauth:
|
||||
image: ghcr.io/steveiliop56/tinyauth:${TINYAUTH_VERSION}
|
||||
command: --experimental.configfile=/data/config.yml
|
||||
volumes:
|
||||
- ./config.yml:/data/config.yml:ro
|
||||
28
integration/docker-compose.traefik.yml
Normal file
28
integration/docker-compose.traefik.yml
Normal file
@@ -0,0 +1,28 @@
|
||||
services:
|
||||
traefik:
|
||||
image: traefik:${TRAEFIK_VERSION}
|
||||
command: |
|
||||
--api.insecure=true
|
||||
--providers.docker
|
||||
--entryPoints.web.address=:80
|
||||
ports:
|
||||
- 80:80
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
whoami:
|
||||
image: traefik/whoami:${WHOAMI_VERSION}
|
||||
labels:
|
||||
traefik.enable: true
|
||||
traefik.http.routers.whoami.rule: Host(`${WHOAMI_HOST}`)
|
||||
traefik.http.routers.whoami.middlewares: tinyauth
|
||||
|
||||
tinyauth:
|
||||
image: ghcr.io/steveiliop56/tinyauth:${TINYAUTH_VERSION}
|
||||
command: --experimental.configfile=/data/config.yml
|
||||
volumes:
|
||||
- ./config.yml:/data/config.yml:ro
|
||||
labels:
|
||||
traefik.enable: true
|
||||
traefik.http.routers.tinyauth.rule: Host(`${TINYAUTH_HOST}`)
|
||||
traefik.http.middlewares.tinyauth.forwardauth.address: http://tinyauth:3000/api/auth/traefik
|
||||
105
integration/envoy.yml
Normal file
105
integration/envoy.yml
Normal file
@@ -0,0 +1,105 @@
|
||||
static_resources:
|
||||
listeners:
|
||||
- name: "listener_http"
|
||||
address:
|
||||
socket_address:
|
||||
address: "0.0.0.0"
|
||||
port_value: 80
|
||||
filter_chains:
|
||||
- filters:
|
||||
- name: "envoy.filters.network.http_connection_manager"
|
||||
typed_config:
|
||||
"@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
|
||||
stat_prefix: "ingress_http"
|
||||
use_remote_address: true
|
||||
skip_xff_append: false
|
||||
route_config:
|
||||
name: "local_route"
|
||||
virtual_hosts:
|
||||
- name: "whoami_service"
|
||||
domains: ["whoami.127.0.0.1.sslip.io"]
|
||||
routes:
|
||||
- match:
|
||||
prefix: "/"
|
||||
route:
|
||||
cluster: "whoami"
|
||||
- name: "tinyauth_service"
|
||||
domains: ["tinyauth.127.0.0.1.sslip.io"]
|
||||
typed_per_filter_config:
|
||||
envoy.filters.http.ext_authz:
|
||||
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute"
|
||||
disabled: true
|
||||
routes:
|
||||
- match:
|
||||
prefix: "/"
|
||||
route:
|
||||
cluster: "tinyauth"
|
||||
http_filters:
|
||||
- name: "envoy.filters.http.ext_authz"
|
||||
typed_config:
|
||||
"@type": "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz"
|
||||
transport_api_version: "v3"
|
||||
http_service:
|
||||
path_prefix: "/api/auth/envoy?path="
|
||||
server_uri:
|
||||
uri: "tinyauth:3000"
|
||||
cluster: "tinyauth"
|
||||
timeout: "0.25s"
|
||||
authorization_request:
|
||||
allowed_headers:
|
||||
patterns:
|
||||
- exact: "authorization"
|
||||
- exact: "accept"
|
||||
- exact: "cookie"
|
||||
headers_to_add:
|
||||
- key: "x-forwarded-proto"
|
||||
value: "%REQ(:SCHEME)%"
|
||||
- key: "x-forwarded-host"
|
||||
value: "%REQ(:AUTHORITY)%"
|
||||
- key: "x-forwarded-uri"
|
||||
value: "%REQ(:PATH)%"
|
||||
authorization_response:
|
||||
allowed_upstream_headers:
|
||||
patterns:
|
||||
- prefix: "remote-"
|
||||
allowed_client_headers:
|
||||
patterns:
|
||||
- exact: "set-cookie"
|
||||
- exact: "location"
|
||||
allowed_client_headers_on_success:
|
||||
patterns:
|
||||
- exact: "set-cookie"
|
||||
- exact: "location"
|
||||
failure_mode_allow: false
|
||||
- name: "envoy.filters.http.router"
|
||||
typed_config:
|
||||
"@type": "type.googleapis.com/envoy.extensions.filters.http.router.v3.Router"
|
||||
clusters:
|
||||
- name: "whoami"
|
||||
connect_timeout: "0.25s"
|
||||
type: "logical_dns"
|
||||
dns_lookup_family: "v4_only"
|
||||
lb_policy: "round_robin"
|
||||
load_assignment:
|
||||
cluster_name: "whoami"
|
||||
endpoints:
|
||||
- lb_endpoints:
|
||||
- endpoint:
|
||||
address:
|
||||
socket_address:
|
||||
address: "whoami"
|
||||
port_value: 80
|
||||
- name: "tinyauth"
|
||||
connect_timeout: "0.25s"
|
||||
type: "logical_dns"
|
||||
dns_lookup_family: "v4_only"
|
||||
lb_policy: "round_robin"
|
||||
load_assignment:
|
||||
cluster_name: "tinyauth"
|
||||
endpoints:
|
||||
- lb_endpoints:
|
||||
- endpoint:
|
||||
address:
|
||||
socket_address:
|
||||
address: "tinyauth"
|
||||
port_value: 3000
|
||||
62
integration/integrarion_tests.go
Normal file
62
integration/integrarion_tests.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func testUnauthorized(client *http.Client) error {
|
||||
req, err := http.NewRequest("GET", WhoamiURL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// nginx and envoy will throw us at the frontend
|
||||
if resp.StatusCode != http.StatusUnauthorized && !strings.Contains(string(body), "<div id=\"root\"></div>") {
|
||||
return fmt.Errorf("expected status code %d or to to contain '<div id=\"root\"></div>', got %d", http.StatusUnauthorized, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func testLoggedIn(client *http.Client) error {
|
||||
req, err := http.NewRequest("GET", WhoamiURL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.SetBasicAuth(DefaultUsername, DefaultPassword)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("expected status code %d, got %d", http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func testACLAllowed(client *http.Client) error {
|
||||
req, err := http.NewRequest("GET", WhoamiURL+"/allow", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("expected status code %d, got %d", http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
166
integration/integration.go
Normal file
166
integration/integration.go
Normal file
@@ -0,0 +1,166 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ProxiesToTest = []string{"traefik", "nginx", "envoy"}
|
||||
|
||||
const (
|
||||
EnvFile = ".env"
|
||||
ConfigFile = "config.yml"
|
||||
)
|
||||
|
||||
const (
|
||||
TinyauthURL = "http://tinyauth.127.0.0.1.sslip.io"
|
||||
WhoamiURL = "http://whoami.127.0.0.1.sslip.io"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultUsername = "test"
|
||||
DefaultPassword = "password"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logFlag := flag.Bool("log", false, "enable stack logging")
|
||||
flag.Parse()
|
||||
|
||||
for _, proxy := range ProxiesToTest {
|
||||
slog.Info("begin", "proxy", proxy)
|
||||
compose := fmt.Sprintf("docker-compose.%s.yml", proxy)
|
||||
if _, err := os.Stat(compose); err != nil {
|
||||
slog.Error("fail", "proxy", proxy, "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := createInstanceAndRunTests(compose, *logFlag, proxy); err != nil {
|
||||
slog.Error("fail", "proxy", proxy, "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
slog.Info("end", "proxy", proxy)
|
||||
}
|
||||
}
|
||||
|
||||
func runTests(client *http.Client, name string) error {
|
||||
if err := testUnauthorized(client); err != nil {
|
||||
slog.Error("fail unauthorized test", "name", name)
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("unauthorized test passed", "name", name)
|
||||
|
||||
if err := testLoggedIn(client); err != nil {
|
||||
slog.Error("fail logged in test", "name", name)
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("logged in test passed", "name", name)
|
||||
|
||||
if err := testACLAllowed(client); err != nil {
|
||||
slog.Error("fail acl test", "name", name)
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("acl test passed", "name", name)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func createInstanceAndRunTests(compose string, log bool, name string) error {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
cmdArgs := []string{"compose", "-f", compose, "--env-file", EnvFile, "up", "--build", "--force-recreate", "--remove-orphans"}
|
||||
cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
|
||||
|
||||
if log {
|
||||
setupCmdLogging(cmd)
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
cmd.Process.Signal(os.Interrupt)
|
||||
cmd.Wait()
|
||||
}()
|
||||
|
||||
slog.Info("instance created", "name", name)
|
||||
|
||||
if err := waitForHealthy(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("instance healthy", "name", name)
|
||||
|
||||
client := &http.Client{}
|
||||
|
||||
if err := runTests(client, name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
slog.Info("tests passed", "name", name)
|
||||
|
||||
cmd.Process.Signal(os.Interrupt)
|
||||
|
||||
if err := cmd.Wait(); cmd.ProcessState.ExitCode() != 130 && err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func setupCmdLogging(cmd *exec.Cmd) {
|
||||
stdout, _ := cmd.StdoutPipe()
|
||||
stderr, _ := cmd.StderrPipe()
|
||||
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(stdout)
|
||||
for scanner.Scan() {
|
||||
slog.Info("docker out", "stdout", scanner.Text())
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(stderr)
|
||||
for scanner.Scan() {
|
||||
slog.Error("docker out", "stderr", scanner.Text())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func waitForHealthy() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
ticker := time.NewTicker(10 * time.Second)
|
||||
client := http.Client{}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("tinyauth not healthy after 5 minutes")
|
||||
case <-ticker.C:
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", TinyauthURL+"/api/healthz", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := client.Do(req)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if res.StatusCode == http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
36
integration/nginx.conf
Normal file
36
integration/nginx.conf
Normal file
@@ -0,0 +1,36 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
|
||||
server_name tinyauth.127.0.0.1.sslip.io;
|
||||
|
||||
location / {
|
||||
proxy_pass http://tinyauth:3000;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
|
||||
server_name whoami.127.0.0.1.sslip.io;
|
||||
|
||||
location / {
|
||||
proxy_pass http://whoami;
|
||||
auth_request /tinyauth;
|
||||
error_page 401 = @tinyauth_login;
|
||||
}
|
||||
|
||||
location /tinyauth {
|
||||
internal;
|
||||
proxy_pass http://tinyauth:3000/api/auth/nginx;
|
||||
proxy_set_header x-original-url $scheme://$http_host$request_uri;
|
||||
proxy_set_header x-forwarded-proto $scheme;
|
||||
proxy_set_header x-forwarded-host $host;
|
||||
proxy_set_header x-forwarded-uri $request_uri;
|
||||
}
|
||||
|
||||
location @tinyauth_login {
|
||||
return 302 http://tinyauth.127.0.0.1.sslip.io/login?redirect_uri=$scheme://$http_host$request_uri;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/steveiliop56/tinyauth/internal/config"
|
||||
@@ -15,12 +17,31 @@ import (
|
||||
"github.com/google/go-querystring/query"
|
||||
)
|
||||
|
||||
type RequestType int
|
||||
|
||||
const (
|
||||
AuthRequest RequestType = iota
|
||||
ExtAuthz
|
||||
ForwardAuth
|
||||
)
|
||||
|
||||
var BrowserUserAgentRegex = regexp.MustCompile("Chrome|Gecko|AppleWebKit|Opera|Edge")
|
||||
|
||||
var SupportedProxies = []string{"nginx", "traefik", "caddy", "envoy"}
|
||||
|
||||
type Proxy struct {
|
||||
Proxy string `uri:"proxy" binding:"required"`
|
||||
}
|
||||
|
||||
type ProxyContext struct {
|
||||
Host string
|
||||
Proto string
|
||||
Path string
|
||||
Method string
|
||||
Type RequestType
|
||||
IsBrowser bool
|
||||
}
|
||||
|
||||
type ProxyControllerConfig struct {
|
||||
AppURL string
|
||||
}
|
||||
@@ -43,82 +64,30 @@ func NewProxyController(config ProxyControllerConfig, router *gin.RouterGroup, a
|
||||
|
||||
func (controller *ProxyController) SetupRoutes() {
|
||||
proxyGroup := controller.router.Group("/auth")
|
||||
// There is a later check to control allowed methods per proxy
|
||||
proxyGroup.Any("/:proxy", controller.proxyHandler)
|
||||
}
|
||||
|
||||
func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
var req Proxy
|
||||
// Load proxy context based on the request type
|
||||
proxyCtx, err := controller.getProxyContext(c)
|
||||
|
||||
err := c.BindUri(&req)
|
||||
if err != nil {
|
||||
tlog.App.Error().Err(err).Msg("Failed to bind URI")
|
||||
tlog.App.Warn().Err(err).Msg("Failed to get proxy context")
|
||||
c.JSON(400, gin.H{
|
||||
"status": 400,
|
||||
"message": "Bad Request",
|
||||
"message": "Bad request",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if !slices.Contains(SupportedProxies, req.Proxy) {
|
||||
tlog.App.Warn().Str("proxy", req.Proxy).Msg("Invalid proxy")
|
||||
c.JSON(400, gin.H{
|
||||
"status": 400,
|
||||
"message": "Bad Request",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Only allow GET for non-envoy proxies.
|
||||
// Envoy uses the original client method for the external auth request
|
||||
// so we allow Any standard HTTP method for /api/auth/envoy
|
||||
if req.Proxy != "envoy" && c.Request.Method != http.MethodGet {
|
||||
tlog.App.Warn().Str("method", c.Request.Method).Msg("Invalid method for proxy")
|
||||
c.Header("Allow", "GET")
|
||||
c.JSON(405, gin.H{
|
||||
"status": 405,
|
||||
"message": "Method Not Allowed",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
isBrowser := strings.Contains(c.Request.Header.Get("Accept"), "text/html")
|
||||
|
||||
if isBrowser {
|
||||
tlog.App.Debug().Msg("Request identified as (most likely) coming from a browser")
|
||||
} else {
|
||||
tlog.App.Debug().Msg("Request identified as (most likely) coming from a non-browser client")
|
||||
}
|
||||
|
||||
// We are not marking the URI as a required header because it may be missing
|
||||
// and we only use it for the auth enabled check which will simply not match
|
||||
// if the header is missing. For deployments like Kubernetes, we use the
|
||||
// x-original-uri header instead.
|
||||
uri, ok := controller.getHeader(c, "x-forwarded-uri")
|
||||
|
||||
if !ok {
|
||||
originalUri, ok := controller.getHeader(c, "x-original-uri")
|
||||
if ok {
|
||||
uri = originalUri
|
||||
}
|
||||
}
|
||||
|
||||
host, ok := controller.requireHeader(c, "x-forwarded-host")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
proto, ok := controller.requireHeader(c, "x-forwarded-proto")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
tlog.App.Trace().Interface("ctx", proxyCtx).Msg("Got proxy context")
|
||||
|
||||
// Get acls
|
||||
acls, err := controller.acls.GetAccessControls(host)
|
||||
acls, err := controller.acls.GetAccessControls(proxyCtx.Host)
|
||||
|
||||
if err != nil {
|
||||
tlog.App.Error().Err(err).Msg("Failed to get access controls for resource")
|
||||
controller.handleError(c, req, isBrowser)
|
||||
controller.handleError(c, proxyCtx)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -135,11 +104,11 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
authEnabled, err := controller.auth.IsAuthEnabled(uri, acls.Path)
|
||||
authEnabled, err := controller.auth.IsAuthEnabled(proxyCtx.Path, acls.Path)
|
||||
|
||||
if err != nil {
|
||||
tlog.App.Error().Err(err).Msg("Failed to check if auth is enabled for resource")
|
||||
controller.handleError(c, req, isBrowser)
|
||||
controller.handleError(c, proxyCtx)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -154,7 +123,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
if !controller.auth.CheckIP(acls.IP, clientIP) {
|
||||
if req.Proxy == "nginx" || !isBrowser {
|
||||
if !controller.useFriendlyError(proxyCtx) {
|
||||
c.JSON(401, gin.H{
|
||||
"status": 401,
|
||||
"message": "Unauthorized",
|
||||
@@ -163,7 +132,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
queries, err := query.Values(config.UnauthorizedQuery{
|
||||
Resource: strings.Split(host, ".")[0],
|
||||
Resource: strings.Split(proxyCtx.Host, ".")[0],
|
||||
IP: clientIP,
|
||||
})
|
||||
|
||||
@@ -196,9 +165,9 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
userAllowed := controller.auth.IsUserAllowed(c, userContext, acls)
|
||||
|
||||
if !userAllowed {
|
||||
tlog.App.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User not allowed to access resource")
|
||||
tlog.App.Warn().Str("user", userContext.Username).Str("resource", strings.Split(proxyCtx.Host, ".")[0]).Msg("User not allowed to access resource")
|
||||
|
||||
if req.Proxy == "nginx" || !isBrowser {
|
||||
if !controller.useFriendlyError(proxyCtx) {
|
||||
c.JSON(403, gin.H{
|
||||
"status": 403,
|
||||
"message": "Forbidden",
|
||||
@@ -207,7 +176,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
queries, err := query.Values(config.UnauthorizedQuery{
|
||||
Resource: strings.Split(host, ".")[0],
|
||||
Resource: strings.Split(proxyCtx.Host, ".")[0],
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -236,9 +205,9 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
if !groupOK {
|
||||
tlog.App.Warn().Str("user", userContext.Username).Str("resource", strings.Split(host, ".")[0]).Msg("User groups do not match resource requirements")
|
||||
tlog.App.Warn().Str("user", userContext.Username).Str("resource", strings.Split(proxyCtx.Host, ".")[0]).Msg("User groups do not match resource requirements")
|
||||
|
||||
if req.Proxy == "nginx" || !isBrowser {
|
||||
if !controller.useFriendlyError(proxyCtx) {
|
||||
c.JSON(403, gin.H{
|
||||
"status": 403,
|
||||
"message": "Forbidden",
|
||||
@@ -247,7 +216,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
queries, err := query.Values(config.UnauthorizedQuery{
|
||||
Resource: strings.Split(host, ".")[0],
|
||||
Resource: strings.Split(proxyCtx.Host, ".")[0],
|
||||
GroupErr: true,
|
||||
})
|
||||
|
||||
@@ -289,7 +258,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Proxy == "nginx" || !isBrowser {
|
||||
if !controller.useFriendlyError(proxyCtx) {
|
||||
c.JSON(401, gin.H{
|
||||
"status": 401,
|
||||
"message": "Unauthorized",
|
||||
@@ -298,7 +267,7 @@ func (controller *ProxyController) proxyHandler(c *gin.Context) {
|
||||
}
|
||||
|
||||
queries, err := query.Values(config.RedirectQuery{
|
||||
RedirectURI: fmt.Sprintf("%s://%s%s", proto, host, uri),
|
||||
RedirectURI: fmt.Sprintf("%s://%s%s", proxyCtx.Proto, proxyCtx.Host, proxyCtx.Path),
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -328,8 +297,8 @@ func (controller *ProxyController) setHeaders(c *gin.Context, acls config.App) {
|
||||
}
|
||||
}
|
||||
|
||||
func (controller *ProxyController) handleError(c *gin.Context, req Proxy, isBrowser bool) {
|
||||
if req.Proxy == "nginx" || !isBrowser {
|
||||
func (controller *ProxyController) handleError(c *gin.Context, proxyCtx ProxyContext) {
|
||||
if !controller.useFriendlyError(proxyCtx) {
|
||||
c.JSON(500, gin.H{
|
||||
"status": 500,
|
||||
"message": "Internal Server Error",
|
||||
@@ -340,20 +309,166 @@ func (controller *ProxyController) handleError(c *gin.Context, req Proxy, isBrow
|
||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
||||
}
|
||||
|
||||
func (controller *ProxyController) requireHeader(c *gin.Context, header string) (string, bool) {
|
||||
val, ok := controller.getHeader(c, header)
|
||||
if !ok {
|
||||
tlog.App.Error().Str("header", header).Msg("Header not found")
|
||||
c.JSON(400, gin.H{
|
||||
"status": 400,
|
||||
"message": "Bad Request",
|
||||
})
|
||||
return "", false
|
||||
}
|
||||
return val, true
|
||||
}
|
||||
|
||||
func (controller *ProxyController) getHeader(c *gin.Context, header string) (string, bool) {
|
||||
val := c.Request.Header.Get(header)
|
||||
return val, strings.TrimSpace(val) != ""
|
||||
}
|
||||
|
||||
func (controller *ProxyController) useFriendlyError(proxyCtx ProxyContext) bool {
|
||||
return (proxyCtx.Type == ForwardAuth || proxyCtx.Type == ExtAuthz) && proxyCtx.IsBrowser
|
||||
}
|
||||
|
||||
// Code below is inspired from https://github.com/authelia/authelia/blob/master/internal/handlers/handler_authz.go
|
||||
// and thus it may be subject to Apache 2.0 License
|
||||
func (controller *ProxyController) getForwardAuthContext(c *gin.Context) (ProxyContext, error) {
|
||||
host, ok := controller.getHeader(c, "x-forwarded-host")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("x-forwarded-host not found")
|
||||
}
|
||||
|
||||
uri, ok := controller.getHeader(c, "x-forwarded-uri")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("x-forwarded-uri not found")
|
||||
}
|
||||
|
||||
proto, ok := controller.getHeader(c, "x-forwarded-proto")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("x-forwarded-proto not found")
|
||||
}
|
||||
|
||||
method := c.Request.Method
|
||||
|
||||
if method != http.MethodGet {
|
||||
return ProxyContext{}, errors.New("method not allowed")
|
||||
}
|
||||
|
||||
return ProxyContext{
|
||||
Host: host,
|
||||
Proto: proto,
|
||||
Path: uri,
|
||||
Method: method,
|
||||
Type: ForwardAuth,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (controller *ProxyController) getAuthRequestContext(c *gin.Context) (ProxyContext, error) {
|
||||
xOriginalUrl, ok := controller.getHeader(c, "x-original-url")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("x-original-url not found")
|
||||
}
|
||||
|
||||
url, err := url.Parse(xOriginalUrl)
|
||||
|
||||
if err != nil {
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
|
||||
host := url.Host
|
||||
proto := url.Scheme
|
||||
path := url.Path
|
||||
method := c.Request.Method
|
||||
|
||||
if method != http.MethodGet {
|
||||
return ProxyContext{}, errors.New("method not allowed")
|
||||
}
|
||||
|
||||
return ProxyContext{
|
||||
Host: host,
|
||||
Proto: proto,
|
||||
Path: path,
|
||||
Method: method,
|
||||
Type: AuthRequest,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (controller *ProxyController) getExtAuthzContext(c *gin.Context) (ProxyContext, error) {
|
||||
proto, ok := controller.getHeader(c, "x-forwarded-proto")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("x-forwarded-proto not found")
|
||||
}
|
||||
|
||||
host, ok := controller.getHeader(c, "host")
|
||||
|
||||
if !ok {
|
||||
return ProxyContext{}, errors.New("host not found")
|
||||
}
|
||||
|
||||
// Seems like we can't get the path?
|
||||
|
||||
// For envoy we need to support every method
|
||||
method := c.Request.Method
|
||||
|
||||
return ProxyContext{
|
||||
Host: host,
|
||||
Proto: proto,
|
||||
Method: method,
|
||||
Type: ExtAuthz,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext, error) {
|
||||
var req Proxy
|
||||
|
||||
err := c.BindUri(&req)
|
||||
if err != nil {
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
|
||||
var ctx ProxyContext
|
||||
|
||||
switch req.Proxy {
|
||||
// For nginx we need to handle both forward_auth and auth_request extraction since it can be
|
||||
// used either with something line nginx proxy manager with advanced config or with
|
||||
// the kubernetes ingress controller
|
||||
case "nginx":
|
||||
tlog.App.Debug().Str("proxy", req.Proxy).Msg("Attempting forward_auth compatible extraction")
|
||||
forwardAuthCtx, err := controller.getForwardAuthContext(c)
|
||||
if err == nil {
|
||||
tlog.App.Debug().Str("proxy", req.Proxy).Msg("Extractions success using forward_auth")
|
||||
ctx = forwardAuthCtx
|
||||
} else {
|
||||
tlog.App.Debug().Str("proxy", req.Proxy).Msg("Extractions failed using forward_auth trying with auth_request")
|
||||
authRequestCtx, err := controller.getAuthRequestContext(c)
|
||||
if err != nil {
|
||||
tlog.App.Warn().Str("proxy", req.Proxy).Msg("Failed to determine required module for header extraction")
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
ctx = authRequestCtx
|
||||
}
|
||||
case "envoy":
|
||||
tlog.App.Debug().Str("proxy", req.Proxy).Msg("Attempting ext_authz compatible extraction")
|
||||
extAuthzCtx, err := controller.getExtAuthzContext(c)
|
||||
if err != nil {
|
||||
tlog.App.Warn().Str("proxy", req.Proxy).Msg("Failed to determine required module for header extraction")
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
ctx = extAuthzCtx
|
||||
// By default we fallback to the forward_auth module which supports most proxies like traefik or caddy
|
||||
default:
|
||||
tlog.App.Debug().Str("proxy", req.Proxy).Msg("Attempting forward_auth compatible extraction")
|
||||
forwardAuthCtx, err := controller.getForwardAuthContext(c)
|
||||
if err != nil {
|
||||
tlog.App.Warn().Str("proxy", req.Proxy).Msg("Failed to determine required module for header extraction")
|
||||
return ProxyContext{}, err
|
||||
}
|
||||
ctx = forwardAuthCtx
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
if isBrowser {
|
||||
tlog.App.Debug().Msg("Request identified as (most likely) coming from a browser")
|
||||
} else {
|
||||
tlog.App.Debug().Msg("Request identified as (most likely) coming from a non-browser client")
|
||||
}
|
||||
|
||||
ctx.IsBrowser = isBrowser
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user