From 83dbe09ab59b52c6b8ef25208e16204f75c0747d Mon Sep 17 00:00:00 2001 From: William Petit Date: Fri, 12 Apr 2024 16:41:11 +0200 Subject: [PATCH] feat: new openid connect authentication layer --- go.mod | 18 +- go.sum | 37 ++- internal/admin/bootstrap.go | 16 +- internal/admin/proxy_route.go | 19 +- internal/admin/util.go | 29 ++ internal/config/bootstrap.go | 11 +- internal/proxy/director/context.go | 19 +- internal/proxy/director/director.go | 4 +- .../director/layer/authn/authenticator.go | 27 ++ .../director/layer/authn/layer-options.json | 49 +++ internal/proxy/director/layer/authn/layer.go | 104 +++++++ .../director/layer/authn/layer_options.go | 66 ++++ .../layer/authn/oidc/authenticator.go | 136 +++++++++ .../proxy/director/layer/authn/oidc/client.go | 282 ++++++++++++++++++ .../layer/authn/oidc/client_options.go | 76 +++++ .../layer/authn/oidc/layer-options.json | 35 +++ .../proxy/director/layer/authn/oidc/layer.go | 12 + .../layer/authn/oidc/layer_options.go | 48 +++ .../proxy/director/layer/authn/oidc/schema.go | 8 + .../director/layer/authn/redis/adapter.go | 58 ++++ internal/proxy/director/layer/authn/schema.go | 8 + internal/proxy/director/layer/authn/store.go | 179 +++++++++++ internal/proxy/director/layer/authn/user.go | 17 ++ internal/schema/extend.go | 39 +++ internal/setup/authn_oidc_layer.go | 27 ++ 25 files changed, 1281 insertions(+), 43 deletions(-) create mode 100644 internal/admin/util.go create mode 100644 internal/proxy/director/layer/authn/authenticator.go create mode 100644 internal/proxy/director/layer/authn/layer-options.json create mode 100644 internal/proxy/director/layer/authn/layer.go create mode 100644 internal/proxy/director/layer/authn/layer_options.go create mode 100644 internal/proxy/director/layer/authn/oidc/authenticator.go create mode 100644 internal/proxy/director/layer/authn/oidc/client.go create mode 100644 internal/proxy/director/layer/authn/oidc/client_options.go create mode 100644 internal/proxy/director/layer/authn/oidc/layer-options.json create mode 100644 internal/proxy/director/layer/authn/oidc/layer.go create mode 100644 internal/proxy/director/layer/authn/oidc/layer_options.go create mode 100644 internal/proxy/director/layer/authn/oidc/schema.go create mode 100644 internal/proxy/director/layer/authn/redis/adapter.go create mode 100644 internal/proxy/director/layer/authn/schema.go create mode 100644 internal/proxy/director/layer/authn/store.go create mode 100644 internal/proxy/director/layer/authn/user.go create mode 100644 internal/schema/extend.go create mode 100644 internal/setup/authn_oidc_layer.go diff --git a/go.mod b/go.mod index e17b607..2bd8c24 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,8 @@ require ( github.com/Masterminds/sprig/v3 v3.2.3 github.com/bsm/redislock v0.9.4 github.com/btcsuite/btcd/btcutil v1.1.3 + github.com/coreos/go-oidc/v3 v3.10.0 + github.com/dchest/uniuri v1.2.0 github.com/drone/envsubst v1.0.3 github.com/getsentry/sentry-go v0.22.0 github.com/go-chi/chi/v5 v5.0.8 @@ -19,6 +21,7 @@ require ( github.com/prometheus/client_golang v1.16.0 github.com/qri-io/jsonschema v0.2.1 github.com/redis/go-redis/v9 v9.0.4 + golang.org/x/oauth2 v0.13.0 k8s.io/api v0.29.3 k8s.io/apimachinery v0.29.3 k8s.io/client-go v0.29.3 @@ -42,15 +45,20 @@ require ( github.com/docker/go-connections v0.4.0 // indirect github.com/docker/go-units v0.4.0 // indirect github.com/emicklei/go-restful/v3 v3.11.0 // indirect + github.com/go-chi/chi v4.0.2+incompatible // indirect + github.com/go-jose/go-jose/v4 v4.0.1 // indirect github.com/go-logr/logr v1.3.0 // indirect github.com/go-openapi/jsonpointer v0.19.6 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.3 // indirect + github.com/go-redis/redis v6.15.5+incompatible // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/gnostic-models v0.6.8 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/gorilla/sessions v1.2.2 // indirect github.com/huandu/xstrings v1.3.3 // indirect github.com/imdario/mergo v0.3.12 // indirect github.com/josharian/intern v1.0.0 // indirect @@ -71,6 +79,7 @@ require ( github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/qri-io/jsonpointer v0.1.1 // indirect + github.com/rbcervilla/redisstore v1.1.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/segmentio/asm v1.2.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect @@ -80,10 +89,9 @@ require ( github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect golang.org/x/net v0.19.0 // indirect - golang.org/x/oauth2 v0.10.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.3.0 // indirect - google.golang.org/appengine v1.6.7 // indirect + google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20220314164441-57ef72a4c106 // indirect google.golang.org/protobuf v1.33.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect @@ -126,10 +134,10 @@ require ( github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect gitlab.com/wpetit/goweb v0.0.0-20230419082146-a94d9ed7202b go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.17.0 // indirect + golang.org/x/crypto v0.19.0 // indirect golang.org/x/mod v0.14.0 // indirect - golang.org/x/sys v0.15.0 // indirect - golang.org/x/term v0.15.0 // indirect + golang.org/x/sys v0.17.0 // indirect + golang.org/x/term v0.17.0 // indirect golang.org/x/tools v0.16.1 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect gopkg.in/go-playground/validator.v9 v9.29.1 // indirect diff --git a/go.sum b/go.sum index 99aee0e..9cae3eb 100644 --- a/go.sum +++ b/go.sum @@ -132,6 +132,8 @@ github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWH github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= +github.com/coreos/go-oidc/v3 v3.10.0 h1:tDnXHnLyiTVyT/2zLDGj09pFPkhND8Gl8lnTRhoEaJU= +github.com/coreos/go-oidc/v3 v3.10.0/go.mod h1:5j11xcw0D3+SGxn6Z/WFADsgcWVMyNAlSQupk0KK3ac= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= @@ -146,6 +148,8 @@ github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dchest/uniuri v1.2.0 h1:koIcOUdrTIivZgSLhHQvKgqdWZq5d7KdMEWF1Ud6+5g= +github.com/dchest/uniuri v1.2.0/go.mod h1:fSzm4SLHzNZvWLvWJew423PhAzkpNQYq+uNLq4kxhkY= github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs= @@ -189,6 +193,7 @@ github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4 github.com/getsentry/sentry-go v0.22.0 h1:XNX9zKbv7baSEI65l+H1GEJgSeIC1c7EN5kluWaP6dM= github.com/getsentry/sentry-go v0.22.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs= github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= github.com/go-chi/chi/v5 v5.0.8 h1:lD+NLqFcAi1ovnVZpsnObHGW4xb4J8lNmoYVfECH1Y0= github.com/go-chi/chi/v5 v5.0.8/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= @@ -199,6 +204,8 @@ github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3Bop github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-jose/go-jose/v4 v4.0.1 h1:QVEPDE3OluqXBQZDcnNvQrInro2h0e4eqNbnZSWqS6U= +github.com/go-jose/go-jose/v4 v4.0.1/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY= github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY= github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= @@ -213,6 +220,8 @@ github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa github.com/go-playground/universal-translator v0.16.0/go.mod h1:1AnU7NaIRDWWzGEKwgtJRd2xk99HeFyHw3yid4rvQIY= github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= +github.com/go-redis/redis v6.15.5+incompatible h1:pLky8I0rgiblWfa8C1EV7fPEUv0aH6vKRaYHc/YRHVk= +github.com/go-redis/redis v6.15.5+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= @@ -317,7 +326,11 @@ github.com/gorilla/csrf v1.6.0/go.mod h1:7tSf8kmjNYr7IWDCYhd3U8Ck34iQ/Yw5CJu7bAk github.com/gorilla/handlers v1.4.1/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY= +github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -414,6 +427,7 @@ github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU= github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= @@ -421,6 +435,7 @@ github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4 github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.29.0 h1:KIA/t2t5UBzoirT4H9tsML45GEbo3ouUnBHsCfD2tVg= @@ -459,6 +474,8 @@ github.com/qri-io/jsonpointer v0.1.1 h1:prVZBZLL6TW5vsSB9fFHFAMBLI4b0ri5vribQlTJ github.com/qri-io/jsonpointer v0.1.1/go.mod h1:DnJPaYgiKu56EuDp8TU5wFLdZIcAnb/uH9v37ZaMV64= github.com/qri-io/jsonschema v0.2.1 h1:NNFoKms+kut6ABPf6xiKNM5214jzxAhDBrPHCJ97Wg0= github.com/qri-io/jsonschema v0.2.1/go.mod h1:g7DPkiOsK1xv6T/Ao5scXRkd+yTFygcANPBaaqW+VrI= +github.com/rbcervilla/redisstore v1.1.0 h1:feH+JE0epVC+b8OzzPdA71t5HAOQCFI7tUWgDHpGwU0= +github.com/rbcervilla/redisstore v1.1.0/go.mod h1:mvjjXRPkE7/JSjPmAM+1ogezLA48ochb25Aq5d9t9gM= github.com/redis/go-redis/v9 v9.0.4 h1:FC82T+CHJ/Q/PdyLW++GeCO+Ol59Y4T7R4jbgjvktgc= github.com/redis/go-redis/v9 v9.0.4/go.mod h1:WqMKv5vnQbRuZstUwxQI195wHy+t4PuXDOjzMvcuQHk= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= @@ -547,8 +564,8 @@ golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= -golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= -golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -647,8 +664,8 @@ golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8= -golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI= +golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY= +golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -734,13 +751,13 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= -golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= -golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4= -golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0= +golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -750,6 +767,7 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= @@ -857,8 +875,9 @@ google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7 google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= +google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= diff --git a/internal/admin/bootstrap.go b/internal/admin/bootstrap.go index 0e49f1e..a4de73b 100644 --- a/internal/admin/bootstrap.go +++ b/internal/admin/bootstrap.go @@ -28,17 +28,27 @@ func (s *Server) bootstrapProxies(ctx context.Context) error { logger.Info(ctx, "bootstrapping proxies") for proxyName, proxyConfig := range s.bootstrapConfig.Proxies { + loopCtx := logger.With(ctx, logger.F("proxyName", proxyName)) + _, err := s.proxyRepository.GetProxy(ctx, proxyName) if !errors.Is(err, store.ErrNotFound) { if err != nil { return errors.WithStack(err) } - logger.Info(ctx, "ignoring existing proxy", logger.F("proxyName", proxyName)) - continue + if proxyConfig.Recreate { + logger.Info(loopCtx, "force recreating proxy") + + if err := s.deleteProxyAndLayers(ctx, proxyName); err != nil { + return errors.WithStack(err) + } + } else { + logger.Info(loopCtx, "ignoring existing proxy") + continue + } } - logger.Info(ctx, "creating proxy", logger.F("proxyName", proxyName)) + logger.Info(loopCtx, "creating proxy") if _, err := proxyRepo.CreateProxy(ctx, proxyName, string(proxyConfig.To), proxyConfig.From...); err != nil { return errors.WithStack(err) diff --git a/internal/admin/proxy_route.go b/internal/admin/proxy_route.go index e052c89..5ac304e 100644 --- a/internal/admin/proxy_route.go +++ b/internal/admin/proxy_route.go @@ -101,7 +101,7 @@ func (s *Server) deleteProxy(w http.ResponseWriter, r *http.Request) { ctx := r.Context() - if err := s.proxyRepository.DeleteProxy(ctx, proxyName); err != nil { + if err := s.deleteProxyAndLayers(ctx, proxyName); err != nil { if errors.Is(err, store.ErrNotFound) { api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil) @@ -114,23 +114,6 @@ func (s *Server) deleteProxy(w http.ResponseWriter, r *http.Request) { return } - layers, err := s.layerRepository.QueryLayers(ctx, proxyName) - if err != nil { - logAndCaptureError(ctx, "could not query proxy's layers", errors.WithStack(err)) - api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil) - - return - } - - for _, layer := range layers { - if err := s.layerRepository.DeleteLayer(ctx, proxyName, layer.Name); err != nil { - logAndCaptureError(ctx, "could not delete layer", errors.WithStack(err)) - api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil) - - return - } - } - api.DataResponse(w, http.StatusOK, DeleteProxyResponse{ ProxyName: proxyName, }) diff --git a/internal/admin/util.go b/internal/admin/util.go new file mode 100644 index 0000000..34d081f --- /dev/null +++ b/internal/admin/util.go @@ -0,0 +1,29 @@ +package admin + +import ( + "context" + + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/pkg/errors" +) + +func (s *Server) deleteProxyAndLayers(ctx context.Context, proxyName store.ProxyName) error { + if err := s.proxyRepository.DeleteProxy(ctx, proxyName); err != nil { + if !errors.Is(err, store.ErrNotFound) { + return errors.WithStack(err) + } + } + + layers, err := s.layerRepository.QueryLayers(ctx, proxyName) + if err != nil { + return errors.WithStack(err) + } + + for _, layer := range layers { + if err := s.layerRepository.DeleteLayer(ctx, proxyName, layer.Name); err != nil { + return errors.WithStack(err) + } + } + + return nil +} diff --git a/internal/config/bootstrap.go b/internal/config/bootstrap.go index c113250..e1a2b67 100644 --- a/internal/config/bootstrap.go +++ b/internal/config/bootstrap.go @@ -47,11 +47,12 @@ func (c *BootstrapConfig) UnmarshalYAML(unmarshal func(interface{}) error) error } type BootstrapProxyConfig struct { - Enabled InterpolatedBool `yaml:"enabled"` - Weight InterpolatedInt `yaml:"weight"` - To InterpolatedString `yaml:"to"` - From InterpolatedStringSlice `yaml:"from"` - Layers map[store.LayerName]BootstrapLayerConfig `yaml:"layers"` + Enabled InterpolatedBool `yaml:"enabled"` + Weight InterpolatedInt `yaml:"weight"` + To InterpolatedString `yaml:"to"` + From InterpolatedStringSlice `yaml:"from"` + Layers map[store.LayerName]BootstrapLayerConfig `yaml:"layers"` + Recreate InterpolatedBool `yaml:"recreate"` } type BootstrapLayerConfig struct { diff --git a/internal/proxy/director/context.go b/internal/proxy/director/context.go index 1b00a5e..3dc1868 100644 --- a/internal/proxy/director/context.go +++ b/internal/proxy/director/context.go @@ -2,6 +2,7 @@ package director import ( "context" + "net/url" "forge.cadoles.com/cadoles/bouncer/internal/store" "github.com/pkg/errors" @@ -10,8 +11,9 @@ import ( type contextKey string const ( - contextKeyProxy contextKey = "proxy" - contextKeyLayers contextKey = "layers" + contextKeyProxy contextKey = "proxy" + contextKeyLayers contextKey = "layers" + contextKeyOriginalURL contextKey = "originalURL" ) var ( @@ -19,6 +21,19 @@ var ( errUnexpectedContextValue = errors.New("unexpected context value") ) +func withOriginalURL(ctx context.Context, url *url.URL) context.Context { + return context.WithValue(ctx, contextKeyOriginalURL, url) +} + +func OriginalURL(ctx context.Context) (*url.URL, error) { + url, err := ctxValue[*url.URL](ctx, contextKeyOriginalURL) + if err != nil { + return nil, errors.WithStack(err) + } + + return url, nil +} + func withProxy(ctx context.Context, proxy *store.Proxy) context.Context { return context.WithValue(ctx, contextKeyProxy, proxy) } diff --git a/internal/proxy/director/director.go b/internal/proxy/director/director.go index 2bc4096..5deab83 100644 --- a/internal/proxy/director/director.go +++ b/internal/proxy/director/director.go @@ -28,7 +28,9 @@ func (d *Director) rewriteRequest(r *http.Request) (*http.Request, error) { } url := getRequestURL(r) - ctx = logger.With(r.Context(), logger.F("url", url.String())) + + ctx = withOriginalURL(ctx, url) + ctx = logger.With(ctx, logger.F("url", url.String())) var match *store.Proxy diff --git a/internal/proxy/director/layer/authn/authenticator.go b/internal/proxy/director/layer/authn/authenticator.go new file mode 100644 index 0000000..e476b12 --- /dev/null +++ b/internal/proxy/director/layer/authn/authenticator.go @@ -0,0 +1,27 @@ +package authn + +import ( + "net/http" + + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/gorilla/sessions" + "github.com/pkg/errors" +) + +var ( + ErrUnauthorized = errors.New("unauthorized") + ErrForbidden = errors.New("forbidden") + ErrSkipRequest = errors.New("skip request") +) + +type Authenticator interface { + Authenticate(w http.ResponseWriter, r *http.Request, layer *store.Layer, sess *sessions.Session) (*User, error) +} + +type PreAuthentication interface { + PreAuthentication(w http.ResponseWriter, r *http.Request, layer *store.Layer, sess *sessions.Session) error +} + +type PostAuthentication interface { + PostAuthentication(w http.ResponseWriter, r *http.Request, layer *store.Layer, sess *sessions.Session, user *User) error +} diff --git a/internal/proxy/director/layer/authn/layer-options.json b/internal/proxy/director/layer/authn/layer-options.json new file mode 100644 index 0000000..d062095 --- /dev/null +++ b/internal/proxy/director/layer/authn/layer-options.json @@ -0,0 +1,49 @@ +{ + "$id": "https://forge.cadoles.com/cadoles/bouncer/schemas/authn-options", + "title": "Authentication layer options", + "type": "object", + "properties": { + "matchURLs": { + "type": "array", + "items": { + "type": "string" + } + }, + "cookie": { + "type": "object", + "properties": { + "domain": { + "type": "string" + }, + "name": { + "type": "string" + }, + "path": { + "type": "string" + }, + "sameSite": { + "type": "string" + }, + "httpOnly": { + "type": "boolean" + }, + "secure": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "session": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "ttl": { + "type": "string" + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/internal/proxy/director/layer/authn/layer.go b/internal/proxy/director/layer/authn/layer.go new file mode 100644 index 0000000..92d723a --- /dev/null +++ b/internal/proxy/director/layer/authn/layer.go @@ -0,0 +1,104 @@ +package authn + +import ( + "net/http" + + "forge.cadoles.com/Cadoles/go-proxy" + "forge.cadoles.com/Cadoles/go-proxy/wildcard" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director" + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/gorilla/sessions" + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/logger" +) + +type Layer struct { + layerType store.LayerType + auth Authenticator + store sessions.Store +} + +func (l *Layer) Middleware(layer *store.Layer) proxy.Middleware { + return func(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + options, err := fromStoreOptions(layer.Options) + if err != nil { + logger.Error(ctx, "could not parse layer options", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + + sess, err := l.store.Get(r, options.Session.Name) + if err != nil { + logger.Error(ctx, "could not retrieve session", logger.E(errors.WithStack(err))) + } + + if preAuth, ok := l.auth.(PreAuthentication); ok { + if err := preAuth.PreAuthentication(w, r, layer, sess); err != nil { + if errors.Is(err, ErrSkipRequest) { + return + } + + logger.Error(ctx, "could not execute pre-auth hook", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + } + + matches := wildcard.MatchAny(r.URL.String(), options.MatchURLs...) + if !matches { + next.ServeHTTP(w, r) + + return + } + + user, err := l.auth.Authenticate(w, r, layer, sess) + if err != nil { + if errors.Is(err, ErrSkipRequest) { + return + } + + logger.Error(ctx, "could not authenticate user", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + + if postAuth, ok := l.auth.(PostAuthentication); ok { + if err := postAuth.PostAuthentication(w, r, layer, sess, user); err != nil { + if errors.Is(err, ErrSkipRequest) { + return + } + + logger.Error(ctx, "could not execute post-auth hook", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + } + + next.ServeHTTP(w, r) + } + + return http.HandlerFunc(fn) + } +} + +// LayerType implements director.MiddlewareLayer +func (l *Layer) LayerType() store.LayerType { + return l.layerType +} + +func NewLayer(layerType store.LayerType, auth Authenticator, adapter StoreAdapter) *Layer { + return &Layer{ + layerType: layerType, + auth: auth, + store: NewStore(adapter), + } +} + +var _ director.MiddlewareLayer = &Layer{} diff --git a/internal/proxy/director/layer/authn/layer_options.go b/internal/proxy/director/layer/authn/layer_options.go new file mode 100644 index 0000000..426589f --- /dev/null +++ b/internal/proxy/director/layer/authn/layer_options.go @@ -0,0 +1,66 @@ +package authn + +import ( + "time" + + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" +) + +const DefaultSessionName = "bouncer-authn" + +type LayerOptions struct { + MatchURLs []string `mapstructure:"matchURLs"` + Cookie CookieOptions `mapstructure:"cookie"` + Session SessionOptions `mapstructure:"session"` +} + +type CookieOptions struct { + Domain string `mapstructure:"domain"` + Name string `mapstructure:"name"` + Path string `mapstructure:"path"` + SameSite bool `mapstructure:"sameSite"` + Secure bool `mapstructure:"secure"` + HTTPOnly bool `mapstructure:"httpOnly"` + MaxAge time.Duration `mapstructure:"maxAge"` +} + +type SessionOptions struct { + Name string `mapstructure:"name"` + TTL time.Duration `mapstructure:"ttl"` +} + +func DefaultLayerOptions() LayerOptions { + return LayerOptions{ + MatchURLs: []string{"*"}, + Cookie: CookieOptions{ + Path: "/", + HTTPOnly: true, + MaxAge: time.Hour, + }, + Session: SessionOptions{ + Name: DefaultSessionName, + TTL: time.Hour, + }, + } +} + +func fromStoreOptions(storeOptions store.LayerOptions) (*LayerOptions, error) { + layerOptions := DefaultLayerOptions() + + config := mapstructure.DecoderConfig{ + Result: &layerOptions, + } + + decoder, err := mapstructure.NewDecoder(&config) + if err != nil { + return nil, err + } + + if err := decoder.Decode(storeOptions); err != nil { + return nil, errors.WithStack(err) + } + + return &layerOptions, nil +} diff --git a/internal/proxy/director/layer/authn/oidc/authenticator.go b/internal/proxy/director/layer/authn/oidc/authenticator.go new file mode 100644 index 0000000..aafaacc --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/authenticator.go @@ -0,0 +1,136 @@ +package oidc + +import ( + "context" + "fmt" + "net/http" + "net/url" + + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/coreos/go-oidc/v3/oidc" + "github.com/gorilla/sessions" + "github.com/pkg/errors" +) + +type Authenticator struct{} + +func (a *Authenticator) PreAuthentication(w http.ResponseWriter, r *http.Request, layer *store.Layer, sess *sessions.Session) error { + ctx := r.Context() + + originalURL, err := director.OriginalURL(ctx) + if err != nil { + return errors.WithStack(err) + } + + options, err := fromStoreOptions(layer.Options) + if err != nil { + return errors.WithStack(err) + } + + redirectURL := a.getRedirectURL(layer.Name, originalURL, options) + logoutURL := a.getLogoutURL(layer.Name, originalURL, options) + + client, err := a.getClient(options, redirectURL.String()) + if err != nil { + return errors.WithStack(err) + } + + switch r.URL.Path { + case redirectURL.Path: + if err := client.HandleCallback(w, r, sess); err != nil { + return errors.WithStack(err) + } + + case logoutURL.Path: + if err := client.HandleLogout(w, r, sess, options.OIDC.PostLogoutRedirectURL); err != nil { + return errors.WithStack(err) + } + } + + return nil +} + +// Authenticate implements authn.Authenticator. +func (a *Authenticator) Authenticate(w http.ResponseWriter, r *http.Request, layer *store.Layer, sess *sessions.Session) (*authn.User, error) { + ctx := r.Context() + + originalURL, err := director.OriginalURL(ctx) + if err != nil { + return nil, errors.WithStack(err) + } + + options, err := fromStoreOptions(layer.Options) + if err != nil { + return nil, errors.WithStack(err) + } + + redirectURL := a.getRedirectURL(layer.Name, originalURL, options) + + client, err := a.getClient(options, redirectURL.String()) + if err != nil { + return nil, errors.WithStack(err) + } + + idToken, err := client.Authenticate(w, r, sess) + if err != nil { + if errors.Is(err, ErrLoginRequired) { + return nil, errors.WithStack(authn.ErrSkipRequest) + } + + return nil, errors.WithStack(err) + } + + var claims map[string]any + + if err := idToken.Claims(&claims); err != nil { + return nil, errors.WithStack(err) + } + + user := authn.NewUser(idToken.Subject, claims) + + return user, nil +} + +func (a *Authenticator) getRedirectURL(layerName store.LayerName, u *url.URL, options *LayerOptions) *url.URL { + return &url.URL{ + Scheme: u.Scheme, + Host: u.Host, + Path: fmt.Sprintf(options.OIDC.LoginCallbackPath, layerName), + } +} + +func (a *Authenticator) getLogoutURL(layerName store.LayerName, u *url.URL, options *LayerOptions) *url.URL { + return &url.URL{ + Scheme: u.Scheme, + Host: u.Host, + Path: fmt.Sprintf(options.OIDC.LogoutPath, layerName), + } +} + +func (a *Authenticator) getClient(options *LayerOptions, redirectURL string) (*Client, error) { + ctx := context.Background() + + if options.OIDC.SkipIssuerVerification { + ctx = oidc.InsecureIssuerURLContext(ctx, options.OIDC.IssuerURL) + } + + provider, err := oidc.NewProvider(ctx, options.OIDC.IssuerURL) + if err != nil { + return nil, errors.Wrap(err, "could not create oidc provider") + } + + client := NewClient( + WithCredentials(options.OIDC.ClientID, options.OIDC.ClientSecret), + WithProvider(provider), + WithRedirectURL(redirectURL), + ) + + return client, nil +} + +var ( + _ authn.PreAuthentication = &Authenticator{} + _ authn.Authenticator = &Authenticator{} +) diff --git a/internal/proxy/director/layer/authn/oidc/client.go b/internal/proxy/director/layer/authn/oidc/client.go new file mode 100644 index 0000000..9655fef --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/client.go @@ -0,0 +1,282 @@ +package oidc + +import ( + "bytes" + "net/http" + "net/url" + "strings" + + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director" + "github.com/coreos/go-oidc/v3/oidc" + "github.com/dchest/uniuri" + "github.com/gorilla/sessions" + "github.com/pkg/errors" + "gitlab.com/wpetit/goweb/logger" + "golang.org/x/oauth2" +) + +const ( + DefaultSessionName = "authn-oidc" + + sessionKeyIDToken = "id-token" + sessionKeyPostLoginRedirectURL = "post-login-redirect-url" + sessionKeyLoginState = "login-state" + sessionKeyLoginNonce = "login-nonce" +) + +var ( + ErrLoginRequired = errors.New("login required") +) + +type Client struct { + oauth2 *oauth2.Config + provider *oidc.Provider + verifier *oidc.IDTokenVerifier + acrValues string +} + +func (c *Client) Verifier() *oidc.IDTokenVerifier { + return c.verifier +} + +func (c *Client) Provider() *oidc.Provider { + return c.provider +} + +func (c *Client) Authenticate(w http.ResponseWriter, r *http.Request, sess *sessions.Session) (*oidc.IDToken, error) { + idToken, err := c.getIDToken(r, sess) + if err != nil { + logger.Error(r.Context(), "could not retrieve idtoken", logger.E(errors.WithStack(err))) + + c.login(w, r, sess) + + return nil, errors.WithStack(ErrLoginRequired) + } + + return idToken, nil +} + +func (c *Client) login(w http.ResponseWriter, r *http.Request, sess *sessions.Session) { + ctx := r.Context() + + state := uniuri.New() + nonce := uniuri.New() + + originalURL, err := director.OriginalURL(ctx) + if err != nil { + logger.Error(ctx, "could not retrieve original url", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + + sess.Values[sessionKeyLoginState] = state + sess.Values[sessionKeyLoginNonce] = nonce + sess.Values[sessionKeyPostLoginRedirectURL] = originalURL.String() + + if err := sess.Save(r, w); err != nil { + logger.Error(ctx, "could not save session", logger.E(errors.WithStack(err))) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + + return + } + + authCodeOptions := []oauth2.AuthCodeOption{} + authCodeOptions = append(authCodeOptions, oidc.Nonce(nonce)) + if c.acrValues != "" { + authCodeOptions = append(authCodeOptions, oauth2.SetAuthURLParam("acr_values", c.acrValues)) + } + + authCodeURL := c.oauth2.AuthCodeURL( + state, + authCodeOptions..., + ) + + http.Redirect(w, r, authCodeURL, http.StatusFound) +} + +func (c *Client) HandleLogout(w http.ResponseWriter, r *http.Request, sess *sessions.Session, postLogoutRedirectURL string) error { + ctx := r.Context() + + rawIDToken, err := c.getRawIDToken(r, sess) + if err != nil { + logger.Error(ctx, "could not retrieve raw id token", logger.E(errors.WithStack(err))) + } + + if rawIDToken == "" { + http.Redirect(w, r, postLogoutRedirectURL, http.StatusFound) + return nil + } + + state := uniuri.New() + sess.Values[sessionKeyLoginState] = state + + sess.Values[sessionKeyIDToken] = nil + + if err := sess.Save(r, w); err != nil { + return errors.Wrap(err, "could not save session") + } + + sessionEndURL, err := c.sessionEndURL(rawIDToken, state, postLogoutRedirectURL) + if err != nil { + return errors.Wrap(err, "could not retrieve session end url") + } + + if sessionEndURL != "" { + http.Redirect(w, r, sessionEndURL, http.StatusFound) + } else { + http.Redirect(w, r, postLogoutRedirectURL, http.StatusFound) + } + + return nil +} + +func (c *Client) sessionEndURL(idTokenHint, state, postLogoutRedirectURL string) (string, error) { + sessionEndEndpoint := &struct { + URL string `json:"end_session_endpoint"` + }{} + + if err := c.provider.Claims(&sessionEndEndpoint); err != nil { + return "", errors.Wrap(err, "could not unmarshal claims") + } + + if sessionEndEndpoint.URL == "" { + return "", nil + } + + var buf bytes.Buffer + buf.WriteString(sessionEndEndpoint.URL) + + v := url.Values{} + + if idTokenHint != "" { + v.Set("id_token_hint", idTokenHint) + } + + if postLogoutRedirectURL != "" { + v.Set("post_logout_redirect_uri", postLogoutRedirectURL) + } + + if state != "" { + v.Set("state", state) + } + + if strings.Contains(sessionEndEndpoint.URL, "?") { + buf.WriteByte('&') + } else { + buf.WriteByte('?') + } + + buf.WriteString(v.Encode()) + + return buf.String(), nil +} + +func (c *Client) validate(r *http.Request, sess *sessions.Session) (*oidc.IDToken, string, error) { + ctx := r.Context() + + rawStoredState := sess.Values[sessionKeyLoginState] + receivedState := r.URL.Query().Get("state") + + storedState, ok := rawStoredState.(string) + if !ok { + return nil, "", errors.New("could not find state in session") + } + + if receivedState != storedState { + return nil, "", errors.New("state mismatch") + } + + code := r.URL.Query().Get("code") + + token, err := c.oauth2.Exchange(ctx, code) + if err != nil { + return nil, "", errors.Wrap(err, "could not exchange token") + } + + rawIDToken, ok := token.Extra("id_token").(string) + if !ok { + return nil, "", errors.New("could not find id token") + } + + idToken, err := c.verifier.Verify(ctx, rawIDToken) + if err != nil { + return nil, "", errors.Wrap(err, "could not verify id token") + } + + return idToken, rawIDToken, nil +} + +func (c *Client) getRawIDToken(r *http.Request, sess *sessions.Session) (string, error) { + rawIDToken, ok := sess.Values[sessionKeyIDToken].(string) + if !ok || rawIDToken == "" { + return "", errors.New("invalid id token") + } + + return rawIDToken, nil +} + +func (c *Client) getIDToken(r *http.Request, sess *sessions.Session) (*oidc.IDToken, error) { + rawIDToken, err := c.getRawIDToken(r, sess) + if err != nil { + return nil, errors.Wrap(err, "could not retrieve raw idtoken") + } + + idToken, err := c.verifier.Verify(r.Context(), rawIDToken) + if err != nil { + return nil, errors.Wrap(err, "could not verify id token") + } + + return idToken, nil +} + +func (c *Client) HandleCallback(w http.ResponseWriter, r *http.Request, sess *sessions.Session) error { + _, rawIDToken, err := c.validate(r, sess) + if err != nil { + return errors.Wrap(err, "could not validate oidc token") + } + + sess.Values[sessionKeyIDToken] = rawIDToken + + if err := sess.Save(r, w); err != nil { + return errors.WithStack(err) + } + + rawPostLoginRedirectURL, exists := sess.Values[sessionKeyPostLoginRedirectURL] + if !exists { + return errors.Wrap(err, "could not find post login redirect url") + } + + postLoginRedirectURL, ok := rawPostLoginRedirectURL.(string) + if !ok { + return errors.Wrapf(err, "unexpected value '%v' for post login redirect url", rawPostLoginRedirectURL) + } + + http.Redirect(w, r, postLoginRedirectURL, http.StatusTemporaryRedirect) + + return nil +} + +func NewClient(funcs ...ClientOptionFunc) *Client { + opts := NewClientOptions(funcs...) + + oauth2 := &oauth2.Config{ + ClientID: opts.ClientID, + ClientSecret: opts.ClientSecret, + Endpoint: opts.Provider.Endpoint(), + RedirectURL: opts.RedirectURL, + Scopes: opts.Scopes, + } + + verifier := opts.Provider.Verifier(&oidc.Config{ + ClientID: opts.ClientID, + SkipIssuerCheck: opts.SkipIssuerCheck, + }) + + return &Client{ + oauth2: oauth2, + provider: opts.Provider, + verifier: verifier, + acrValues: opts.AcrValues, + } +} diff --git a/internal/proxy/director/layer/authn/oidc/client_options.go b/internal/proxy/director/layer/authn/oidc/client_options.go new file mode 100644 index 0000000..29dc73d --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/client_options.go @@ -0,0 +1,76 @@ +package oidc + +import ( + "context" + + "github.com/coreos/go-oidc/v3/oidc" +) + +type ClientOptions struct { + Provider *oidc.Provider + ClientID string + ClientSecret string + RedirectURL string + Scopes []string + AcrValues string + SkipIssuerCheck bool +} + +type ClientOptionFunc func(*ClientOptions) + +func WithRedirectURL(url string) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.RedirectURL = url + } +} + +func WithCredentials(clientID, clientSecret string) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.ClientID = clientID + opt.ClientSecret = clientSecret + } +} + +func WithScopes(scopes ...string) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.Scopes = scopes + } +} + +func WithAcrValues(acrValues string) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.AcrValues = acrValues + } +} + +func WithSkipIssuerCheck(skip bool) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.SkipIssuerCheck = skip + } +} + +func NewProvider(ctx context.Context, issuer string, skipIssuerVerification bool) (*oidc.Provider, error) { + if skipIssuerVerification { + ctx = oidc.InsecureIssuerURLContext(ctx, issuer) + } + + return oidc.NewProvider(ctx, issuer) +} + +func WithProvider(provider *oidc.Provider) ClientOptionFunc { + return func(opt *ClientOptions) { + opt.Provider = provider + } +} + +func NewClientOptions(funcs ...ClientOptionFunc) *ClientOptions { + opt := &ClientOptions{ + Scopes: []string{oidc.ScopeOpenID, "profile"}, + } + + for _, f := range funcs { + f(opt) + } + + return opt +} diff --git a/internal/proxy/director/layer/authn/oidc/layer-options.json b/internal/proxy/director/layer/authn/oidc/layer-options.json new file mode 100644 index 0000000..7406841 --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/layer-options.json @@ -0,0 +1,35 @@ +{ + "$id": "https://forge.cadoles.com/cadoles/bouncer/schemas/authn-oidc-layer-options", + "title": "OIDC authentication layer options", + "type": "object", + "properties": { + "oidc": { + "type": "object", + "properties": { + "clientId": { + "type": "string" + }, + "clientSecret": { + "type": "string" + }, + "issuerURL": { + "type": "string" + }, + "postLogoutRedirectURL": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "clientId", + "clientSecret", + "issuerURL", + "postLogoutRedirectURL" + ] + } + }, + "additionalProperties": false, + "required": [ + "oidc" + ] +} \ No newline at end of file diff --git a/internal/proxy/director/layer/authn/oidc/layer.go b/internal/proxy/director/layer/authn/oidc/layer.go new file mode 100644 index 0000000..d11cc91 --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/layer.go @@ -0,0 +1,12 @@ +package oidc + +import ( + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" + "forge.cadoles.com/cadoles/bouncer/internal/store" +) + +const LayerType store.LayerType = "authn-oidc" + +func NewLayer(adapter authn.StoreAdapter) *authn.Layer { + return authn.NewLayer(LayerType, &Authenticator{}, adapter) +} diff --git a/internal/proxy/director/layer/authn/oidc/layer_options.go b/internal/proxy/director/layer/authn/oidc/layer_options.go new file mode 100644 index 0000000..1e76c67 --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/layer_options.go @@ -0,0 +1,48 @@ +package oidc + +import ( + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" + "forge.cadoles.com/cadoles/bouncer/internal/store" + "github.com/mitchellh/mapstructure" + "github.com/pkg/errors" +) + +type LayerOptions struct { + authn.LayerOptions + OIDC OIDCOptions `mapstructure:"oidc"` +} + +type OIDCOptions struct { + ClientID string `mapstructure:"clientId"` + ClientSecret string `mapstructure:"clientSecret"` + LoginCallbackPath string `mapstructure:"loginCallbackPath"` + LogoutPath string `mapstructure:"logoutPath"` + IssuerURL string `mapstructure:"issuerURL"` + SkipIssuerVerification bool `mapstructure:"skipIssuerVerification"` + PostLogoutRedirectURL string `mapstructure:"postLogoutRedirectURL"` +} + +func fromStoreOptions(storeOptions store.LayerOptions) (*LayerOptions, error) { + layerOptions := LayerOptions{ + LayerOptions: authn.DefaultLayerOptions(), + OIDC: OIDCOptions{ + LoginCallbackPath: "/.bouncer/authn/oidc/%s/callback", + LogoutPath: "/.bouncer/authn/oidc/%s/logout", + }, + } + + config := mapstructure.DecoderConfig{ + Result: &layerOptions, + } + + decoder, err := mapstructure.NewDecoder(&config) + if err != nil { + return nil, err + } + + if err := decoder.Decode(storeOptions); err != nil { + return nil, errors.WithStack(err) + } + + return &layerOptions, nil +} diff --git a/internal/proxy/director/layer/authn/oidc/schema.go b/internal/proxy/director/layer/authn/oidc/schema.go new file mode 100644 index 0000000..a020e6d --- /dev/null +++ b/internal/proxy/director/layer/authn/oidc/schema.go @@ -0,0 +1,8 @@ +package oidc + +import ( + _ "embed" +) + +//go:embed layer-options.json +var RawLayerOptionsSchema []byte diff --git a/internal/proxy/director/layer/authn/redis/adapter.go b/internal/proxy/director/layer/authn/redis/adapter.go new file mode 100644 index 0000000..9a04a32 --- /dev/null +++ b/internal/proxy/director/layer/authn/redis/adapter.go @@ -0,0 +1,58 @@ +package redis + +import ( + "context" + "time" + + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +type StoreAdapter struct { + client redis.UniversalClient +} + +// Del implements authn.StoreAdapter. +func (s *StoreAdapter) Del(ctx context.Context, key string) error { + if err := s.client.Del(ctx, key).Err(); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Get implements authn.StoreAdapter. +func (s *StoreAdapter) Get(ctx context.Context, key string) ([]byte, error) { + cmd := s.client.Get(ctx, key) + + if err := cmd.Err(); err != nil { + return nil, errors.WithStack(err) + } + + data, err := cmd.Bytes() + if err != nil { + return nil, errors.WithStack(err) + } + + return data, nil +} + +// Set implements authn.StoreAdapter. +func (s *StoreAdapter) Set(ctx context.Context, key string, data []byte, ttl time.Duration) error { + if err := s.client.Set(ctx, key, data, ttl).Err(); err != nil { + return errors.WithStack(err) + } + + return nil +} + +func NewStoreAdapter(client redis.UniversalClient) *StoreAdapter { + return &StoreAdapter{ + client: client, + } +} + +var ( + _ authn.StoreAdapter = &StoreAdapter{} +) diff --git a/internal/proxy/director/layer/authn/schema.go b/internal/proxy/director/layer/authn/schema.go new file mode 100644 index 0000000..10d4a95 --- /dev/null +++ b/internal/proxy/director/layer/authn/schema.go @@ -0,0 +1,8 @@ +package authn + +import ( + _ "embed" +) + +//go:embed layer-options.json +var RawLayerOptionsSchema []byte diff --git a/internal/proxy/director/layer/authn/store.go b/internal/proxy/director/layer/authn/store.go new file mode 100644 index 0000000..f036ff3 --- /dev/null +++ b/internal/proxy/director/layer/authn/store.go @@ -0,0 +1,179 @@ +package authn + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/base32" + "encoding/gob" + "io" + "net/http" + "strings" + "time" + + "github.com/gorilla/sessions" + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +type StoreAdapter interface { + Set(ctx context.Context, key string, data []byte, ttl time.Duration) error + Del(ctx context.Context, key string) error + Get(ctx context.Context, key string) ([]byte, error) +} + +type Store struct { + adapter StoreAdapter + options sessions.Options + keyPrefix string + keyGen KeyGenFunc + serializer SessionSerializer +} + +type KeyGenFunc func() (string, error) + +func NewStore(adapter StoreAdapter) *Store { + rs := &Store{ + options: sessions.Options{ + Path: "/", + MaxAge: 86400 * 30, + }, + adapter: adapter, + keyPrefix: "session:", + keyGen: generateRandomKey, + serializer: GobSerializer{}, + } + + return rs +} + +func (s *Store) Get(r *http.Request, name string) (*sessions.Session, error) { + return sessions.GetRegistry(r).Get(s, name) +} + +func (s *Store) New(r *http.Request, name string) (*sessions.Session, error) { + session := sessions.NewSession(s, name) + opts := s.options + session.Options = &opts + session.IsNew = true + + c, err := r.Cookie(name) + if err != nil { + return session, nil + } + session.ID = c.Value + + err = s.load(r.Context(), session) + if err == nil { + session.IsNew = false + } else if err == redis.Nil { + err = nil // no data stored + } + return session, err +} + +func (s *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error { + if session.Options.MaxAge <= 0 { + if err := s.delete(r.Context(), session); err != nil { + return err + } + http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options)) + return nil + } + + if session.ID == "" { + id, err := s.keyGen() + if err != nil { + return errors.New("redisstore: failed to generate session id") + } + session.ID = id + } + if err := s.save(r.Context(), session); err != nil { + return err + } + + http.SetCookie(w, sessions.NewCookie(session.Name(), session.ID, session.Options)) + return nil +} + +func (s *Store) Options(opts sessions.Options) { + s.options = opts +} + +func (s *Store) KeyPrefix(keyPrefix string) { + s.keyPrefix = keyPrefix +} + +func (s *Store) KeyGen(f KeyGenFunc) { + s.keyGen = f +} + +func (s *Store) Serializer(ss SessionSerializer) { + s.serializer = ss +} + +func (s *Store) save(ctx context.Context, session *sessions.Session) error { + b, err := s.serializer.Serialize(session) + if err != nil { + return err + } + + if err := s.adapter.Set(ctx, s.keyPrefix+session.ID, b, time.Duration(session.Options.MaxAge)*time.Second); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// load reads session from Redis +func (s *Store) load(ctx context.Context, session *sessions.Session) error { + + data, err := s.adapter.Get(ctx, s.keyPrefix+session.ID) + if err != nil { + return errors.WithStack(err) + } + + return s.serializer.Deserialize(data, session) +} + +// delete deletes session in Redis +func (s *Store) delete(ctx context.Context, session *sessions.Session) error { + if err := s.adapter.Del(ctx, s.keyPrefix+session.ID); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// SessionSerializer provides an interface for serialize/deserialize a session +type SessionSerializer interface { + Serialize(s *sessions.Session) ([]byte, error) + Deserialize(b []byte, s *sessions.Session) error +} + +// Gob serializer +type GobSerializer struct{} + +func (gs GobSerializer) Serialize(s *sessions.Session) ([]byte, error) { + buf := new(bytes.Buffer) + enc := gob.NewEncoder(buf) + err := enc.Encode(s.Values) + if err == nil { + return buf.Bytes(), nil + } + return nil, err +} + +func (gs GobSerializer) Deserialize(d []byte, s *sessions.Session) error { + dec := gob.NewDecoder(bytes.NewBuffer(d)) + return dec.Decode(&s.Values) +} + +// generateRandomKey returns a new random key +func generateRandomKey() (string, error) { + k := make([]byte, 64) + if _, err := io.ReadFull(rand.Reader, k); err != nil { + return "", err + } + return strings.TrimRight(base32.StdEncoding.EncodeToString(k), "="), nil +} diff --git a/internal/proxy/director/layer/authn/user.go b/internal/proxy/director/layer/authn/user.go new file mode 100644 index 0000000..f04d22e --- /dev/null +++ b/internal/proxy/director/layer/authn/user.go @@ -0,0 +1,17 @@ +package authn + +type User struct { + Subject string `json:"subject"` + Attrs map[string]any `json:"attributes"` +} + +func NewUser(subject string, attrs map[string]any) *User { + if attrs == nil { + attrs = make(map[string]any) + } + + return &User{ + Subject: subject, + Attrs: attrs, + } +} diff --git a/internal/schema/extend.go b/internal/schema/extend.go new file mode 100644 index 0000000..2ea1dae --- /dev/null +++ b/internal/schema/extend.go @@ -0,0 +1,39 @@ +package schema + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +func Extend(base []byte, schema []byte) ([]byte, error) { + var ( + extension map[string]any + extended map[string]any + ) + + if err := json.Unmarshal(base, &extended); err != nil { + return nil, errors.WithStack(err) + } + + if err := json.Unmarshal(schema, &extension); err != nil { + return nil, errors.WithStack(err) + } + + extended["$id"] = extension["$id"] + extended["title"] = extension["title"] + + props := extension["properties"].(map[string]any) + extendedProps := extended["properties"].(map[string]any) + for key, val := range props { + extendedProps[key] = val + } + extended["properties"] = extendedProps + + data, err := json.MarshalIndent(extended, "", " ") + if err != nil { + return nil, errors.WithStack(err) + } + + return data, nil +} diff --git a/internal/setup/authn_oidc_layer.go b/internal/setup/authn_oidc_layer.go new file mode 100644 index 0000000..7879ebc --- /dev/null +++ b/internal/setup/authn_oidc_layer.go @@ -0,0 +1,27 @@ +package setup + +import ( + "forge.cadoles.com/cadoles/bouncer/internal/config" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn/oidc" + "forge.cadoles.com/cadoles/bouncer/internal/proxy/director/layer/authn/redis" + "forge.cadoles.com/cadoles/bouncer/internal/schema" + "github.com/pkg/errors" +) + +func init() { + extended, err := schema.Extend(authn.RawLayerOptionsSchema, oidc.RawLayerOptionsSchema) + if err != nil { + panic(errors.Wrap(err, "could not extend authn base layer options schema")) + } + + RegisterLayer(oidc.LayerType, setupAuthnOIDCLayer, extended) +} + +func setupAuthnOIDCLayer(conf *config.Config) (director.Layer, error) { + rdb := newRedisClient(conf.Redis) + adapter := redis.NewStoreAdapter(rdb) + + return oidc.NewLayer(adapter), nil +}