Compare commits

..

No commits in common. "9084b6e05f6bdd47eb6fd66183c6b26577beff19" and "059af1b6ee96f8ac1a711cf070b0a158724509fa" have entirely different histories.

17 changed files with 93 additions and 128 deletions

View File

@ -4,16 +4,7 @@
# Bouncer
Serveur mandataire inverse (_"reverse proxy"_) avec fonctionnalités avancées pilotable par API REST.
## Fonctionnalités
- Authentification unique basée sur entêtes HTTP ("Trusted headers SSO") avec:
- Fournisseur d'identité OpenID Connect ;
- Basic Auth ;
- Origine réseau ;
- Gestion de files d'attente dynamiques pour maîtriser la charge sur les services protégés ;
- Réécriture dynamique des attributs (notamment entêtes HTTP) des requêtes/réponses via un DSL.
Serveur mandataire inverse (_"reverse proxy"_) filtrant avec gestion de files d'attente dynamiques.
## Documentation
@ -21,4 +12,4 @@ Serveur mandataire inverse (_"reverse proxy"_) avec fonctionnalités avancées p
## Licence
AGPL-3.0
AGPL-3.0

View File

@ -1,8 +1,7 @@
# Documentation
- [(FR) - Architecture générale](./fr/general-architecture.md)
- [(FR) - Terminologie](./fr/terminology.md)
- [(FR) - Premiers pas](./fr/getting-started.md)
- [(FR) - Architecture générale](./fr/general-architecture.md)
## Exemples

View File

@ -2,6 +2,31 @@
## Modèles de déploiement
### Mode mono-noeud
### Déploiement mono-noeud
![](../resources/deployment_single_node_fr.png)
![](../resources/deployment_fr.png)
## Terminologie
Voici une liste des termes utilisés dans le lexique Bouncer.
### Proxy
Un "proxy" est une entité logique définissant le relation suivante:
- Un ou plusieurs patrons de filtrage sous la forme d'un patron d'URL avec le caractère `*` comme caractère générique. Ceux ci identifient le ou les domaines/chemins associés à l'entité;
- Une URL cible qui servira de base pour la réécriture des requêtes.
Un "proxy" peut avoir zéro ou plusieurs "layers" associés.
Un "proxy" peut être activé ou désactivé.
Un "proxy" a un poids qui définit son niveau de priorité dans la pile de traitement (plus son poids est élevé plus il est prioritaire).
### Layer
Un "layer" (calque) est une entité logique définissant un traitement à appliquer aux requêtes et/ou aux réponses transitant par un proxy.
Un "layer" peut être activé ou désactivé.
Un "layer" a un poids qui définit son niveau de priorité dans la pile de traitement (plus son poids est élevé plus il est prioritaire).

View File

@ -1,29 +0,0 @@
# Terminologie
Voici une liste des termes utilisés dans le lexique Bouncer.
## Proxy
Un proxy est une entité logique définie par les propriétés suivantes:
- Il possède **un ou plusieurs filtres d'origine** sous la forme de motifs d'URL avec le caractère `*` comme joker. Ces filtres identifient le ou les URLs associées au proxy.
- Il peut avoir **zéro ou une URL cible**, qui servira de base pour la réécriture des requêtes. Si l'URL est absente, on parle alors de "passthrough" (voir note).
- Il peut avoir **zéro ou plusieurs "layers" associés**.
- Il peut être **activé ou désactivé**.
- Il a **un poids qui définit son niveau de priorité** dans la pile de traitement (plus son poids est élevé plus il est prioritaire).
Pour résumer un proxy répond à la question "_Quelle URL orienter vers quel serveur cible ?_".
> **Passthrough**
>
> Un proxy "passthrough" est un proxy n'ayant pas d'URL cible (champ vide). Dans ce cas si les motifs d'URLs correspondent à l'URL de la requête Bouncer appliquera les layers associés puis passera la main aux proxies suivants.
## Layer
Un layer est une entité logique définie par les propriétés suivantes:
- Il a **un type auquel est associé un schéma d'options** permettant de configurer son comportement.
- Il peut être **activé ou désactivé**.
- Il a **un poids qui définit son niveau de priorité** dans la pile de traitement (plus son poids est élevé plus il est prioritaire).
Pour résumer un layer répond à la question "_Quel traitement appliquer à la requête et/ou réponse ?_".

View File

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 35 KiB

2
go.mod
View File

@ -5,7 +5,7 @@ go 1.21
toolchain go1.22.0
require (
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20240626132607-e1db6466a926
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20230701194111-c6b3d482cca6
github.com/Masterminds/sprig/v3 v3.2.3
github.com/bsm/redislock v0.9.4
github.com/btcsuite/btcd/btcutil v1.1.3

2
go.sum
View File

@ -10,8 +10,6 @@ cloud.google.com/go/longrunning v0.5.1 h1:Fr7TXftcqTudoyRJa113hyaqlGdiBQkp0Gq7tE
cloud.google.com/go/longrunning v0.5.1/go.mod h1:spvimkwdz6SPWKEt/XBij79E9fiTkHSQl/fRUUQJYJc=
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20230701194111-c6b3d482cca6 h1:FTk0ZoaV5N8Tkps5Da5RrDMZZXSHZIuD67Hy1Y4fsos=
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20230701194111-c6b3d482cca6/go.mod h1:o8ZK5v/3J1dRmklFVn1l6WHAyQ3LgegyHjRIT8KLAFw=
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20240626132607-e1db6466a926 h1:gSTTuW2lqH66cGVrhplrVrqos62BY1/GxR3KYh2TElk=
forge.cadoles.com/Cadoles/go-proxy v0.0.0-20240626132607-e1db6466a926/go.mod h1:o8ZK5v/3J1dRmklFVn1l6WHAyQ3LgegyHjRIT8KLAFw=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=

View File

@ -121,7 +121,7 @@ func (s *Server) deleteProxy(w http.ResponseWriter, r *http.Request) {
type CreateProxyRequest struct {
Name string `json:"name" validate:"required"`
To string `json:"to"`
To string `json:"to" validate:"required"`
From []string `json:"from" validate:"required"`
}

View File

@ -2,7 +2,6 @@ package layer
import (
"os"
"slices"
"forge.cadoles.com/cadoles/bouncer/internal/client"
"forge.cadoles.com/cadoles/bouncer/internal/command/admin/apierr"
@ -53,16 +52,14 @@ func QueryCommand() *cli.Command {
client := client.New(baseFlags.ServerURL, client.WithToken(token))
layers, err := client.QueryLayer(ctx.Context, proxyName, options...)
proxies, err := client.QueryLayer(ctx.Context, proxyName, options...)
if err != nil {
return errors.WithStack(apierr.Wrap(err))
}
slices.SortFunc(layers, sortLayerssByWeight)
hints := layerHeaderHints(baseFlags.OutputMode)
if err := format.Write(baseFlags.Format, os.Stdout, hints, clientFlag.AsAnySlice(layers)...); err != nil {
if err := format.Write(baseFlags.Format, os.Stdout, hints, clientFlag.AsAnySlice(proxies)...); err != nil {
return errors.WithStack(err)
}
@ -70,13 +67,3 @@ func QueryCommand() *cli.Command {
},
}
}
func sortLayerssByWeight(a *store.LayerHeader, b *store.LayerHeader) int {
if a.Weight < b.Weight {
return 1
}
if a.Weight > b.Weight {
return -1
}
return 0
}

View File

@ -19,7 +19,7 @@ func CreateCommand() *cli.Command {
Name: "create",
Usage: "Create proxy",
Flags: proxyFlag.WithProxyFlags(
flag.ProxyTo(),
flag.ProxyTo(true),
flag.ProxyFrom(),
),
Action: func(ctx *cli.Context) error {

View File

@ -30,11 +30,12 @@ func ProxyName() cli.Flag {
const KeyProxyTo = "proxy-to"
func ProxyTo() cli.Flag {
func ProxyTo(required bool) cli.Flag {
return &cli.StringFlag{
Name: KeyProxyTo,
Usage: "Set `PROXY_TO` as proxy's destination url",
Value: "",
Name: KeyProxyTo,
Usage: "Set `PROXY_TO` as proxy's destination url",
Value: "",
Required: required,
}
}

View File

@ -2,7 +2,6 @@ package proxy
import (
"os"
"slices"
"forge.cadoles.com/cadoles/bouncer/internal/client"
"forge.cadoles.com/cadoles/bouncer/internal/command/admin/apierr"
@ -52,8 +51,6 @@ func QueryCommand() *cli.Command {
return errors.WithStack(apierr.Wrap(err))
}
slices.SortFunc(proxies, sortProxiesByWeight)
hints := proxyHeaderHints(baseFlags.OutputMode)
if err := format.Write(baseFlags.Format, os.Stdout, hints, clientFlag.AsAnySlice(proxies)...); err != nil {
@ -64,13 +61,3 @@ func QueryCommand() *cli.Command {
},
}
}
func sortProxiesByWeight(a *store.ProxyHeader, b *store.ProxyHeader) int {
if a.Weight < b.Weight {
return 1
}
if a.Weight > b.Weight {
return -1
}
return 0
}

View File

@ -19,7 +19,7 @@ func UpdateCommand() *cli.Command {
Name: "update",
Usage: "Update proxy",
Flags: proxyFlag.WithProxyFlags(
flag.ProxyTo(),
flag.ProxyTo(false),
flag.ProxyFrom(),
flag.ProxyEnabled(),
flag.ProxyWeight(),

View File

@ -34,6 +34,19 @@ func OriginalURL(ctx context.Context) (*url.URL, error) {
return url, nil
}
func withProxy(ctx context.Context, proxy *store.Proxy) context.Context {
return context.WithValue(ctx, contextKeyProxy, proxy)
}
func ctxProxy(ctx context.Context) (*store.Proxy, error) {
proxy, err := ctxValue[*store.Proxy](ctx, contextKeyProxy)
if err != nil {
return nil, errors.WithStack(err)
}
return proxy, nil
}
func withLayers(ctx context.Context, layers []*store.Layer) context.Context {
return context.WithValue(ctx, contextKeyLayers, layers)
}

View File

@ -36,15 +36,15 @@ func (d *Director) rewriteRequest(r *http.Request) (*http.Request, error) {
ctx = withOriginalURL(ctx, url)
ctx = logger.With(ctx, logger.F("url", url.String()))
layers := make([]*store.Layer, 0)
var match *store.Proxy
MAIN:
for _, p := range proxies {
for _, from := range p.From {
logger.Debug(
ctx, "matching request with proxy's from",
logger.F("from", from),
)
if matches := wildcard.Match(url.String(), from); !matches {
continue
}
@ -54,41 +54,44 @@ func (d *Director) rewriteRequest(r *http.Request) (*http.Request, error) {
logger.F("from", from),
)
ctx = logger.With(ctx,
logger.F("proxy", p.Name),
logger.F("host", r.Host),
logger.F("remoteAddr", r.RemoteAddr),
)
metricProxyRequestsTotal.With(prometheus.Labels{metricLabelProxy: string(p.Name)}).Add(1)
proxyLayers, err := d.getLayers(ctx, p.Name)
if err != nil {
return r, errors.WithStack(err)
}
layers = append(layers, proxyLayers...)
if p.To == "" {
continue
}
toURL, err := url.Parse(p.To)
if err != nil {
return r, errors.WithStack(err)
}
r.URL.Host = toURL.Host
r.URL.Scheme = toURL.Scheme
r.URL.Path = toURL.JoinPath(r.URL.Path).Path
ctx = withLayers(ctx, layers)
r = r.WithContext(ctx)
return r, nil
match = p
break MAIN
}
}
if match == nil {
return r, nil
}
toURL, err := url.Parse(match.To)
if err != nil {
return r, errors.WithStack(err)
}
r.URL.Host = toURL.Host
r.URL.Scheme = toURL.Scheme
r.URL.Path = toURL.JoinPath(r.URL.Path).Path
ctx = logger.With(ctx,
logger.F("proxy", match.Name),
logger.F("host", r.Host),
logger.F("remoteAddr", r.RemoteAddr),
)
logger.Debug(
ctx, "rewritten url",
logger.F("rewrittenURL", r.URL.String()),
)
metricProxyRequestsTotal.With(prometheus.Labels{metricLabelProxy: string(match.Name)}).Add(1)
ctx = withProxy(ctx, match)
layers, err := d.getLayers(ctx, match.Name)
if err != nil {
return r, errors.WithStack(err)
}
ctx = withLayers(ctx, layers)
r = r.WithContext(ctx)

View File

@ -157,7 +157,6 @@ func (s *Server) run(parentCtx context.Context, addrs chan net.Addr, errs chan e
director.ResponseTransformer(),
),
proxy.WithReverseProxyFactory(s.createReverseProxy),
proxy.WithDefaultHandler(http.HandlerFunc(s.handleDefault)),
)
r.Handle("/*", handler)
@ -186,21 +185,12 @@ func (s *Server) createReverseProxy(ctx context.Context, target *url.URL) *httpu
httpTransport.DialContext = dialer.DialContext
reverseProxy.Transport = httpTransport
reverseProxy.ErrorHandler = s.handleError
reverseProxy.ErrorHandler = s.errorHandler
return reverseProxy
}
func (s *Server) handleDefault(w http.ResponseWriter, r *http.Request) {
err := errors.Errorf("no proxy target found")
logger.Error(r.Context(), "proxy error", logger.E(err))
sentry.CaptureException(err)
s.renderErrorPage(w, r, err, http.StatusBadGateway, http.StatusText(http.StatusBadGateway))
}
func (s *Server) handleError(w http.ResponseWriter, r *http.Request, err error) {
func (s *Server) errorHandler(w http.ResponseWriter, r *http.Request, err error) {
err = errors.WithStack(err)
logger.Error(r.Context(), "proxy error", logger.E(err))