This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
authentik/internal/outpost/ak/api.go

224 lines
5.7 KiB
Go
Raw Permalink Normal View History

package ak
import (
"context"
"fmt"
"math/rand"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/getsentry/sentry-go"
"github.com/google/uuid"
"github.com/gorilla/websocket"
outposts/proxyv2 (#1365) * outposts/proxyv2: initial commit Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add rs256 Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> more stuff Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add forward auth an sign_out Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> match cookie name Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> re-add support for rs256 for backwards compat Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add error handler Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> ensure unique user-agent is used Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> set cookie duration based on id_token expiry Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> build proxy v2 Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add ssl Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add basic auth and custom header support Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add application cert loading Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> implement whitelist Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add redis Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> migrate embedded outpost to v2 Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> remove old proxy Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> providers/proxy: make token expiration configurable Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> add metrics Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> fix tests Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * providers/proxy: only allow one redirect URI Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * fix docker build for proxy Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * remove default port offset Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * add AUTHENTIK_HOST_BROWSER Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * tests: fix e2e/integration tests not using proper tags Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * remove references of old port Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * fix user_attributes not being loaded correctly Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * cleanup dependencies Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org> * cleanup Signed-off-by: Jens Langhammer <jens.langhammer@beryju.org>
2021-09-08 18:04:56 +00:00
"github.com/prometheus/client_golang/prometheus"
"goauthentik.io/api/v3"
"goauthentik.io/internal/constants"
"goauthentik.io/internal/utils/web"
log "github.com/sirupsen/logrus"
)
type WSHandler func(ctx context.Context, args map[string]interface{})
const ConfigLogLevel = "log_level"
// APIController main controller which connects to the authentik api via http and ws
type APIController struct {
Client *api.APIClient
Outpost api.Outpost
GlobalConfig *api.Config
Server Outpost
token string
logger *log.Entry
reloadOffset time.Duration
wsConn *websocket.Conn
lastWsReconnect time.Time
wsIsReconnecting bool
wsBackoffMultiplier int
wsHandlers []WSHandler
refreshHandlers []func()
instanceUUID uuid.UUID
}
// NewAPIController initialise new API Controller instance from URL and API token
func NewAPIController(akURL url.URL, token string) *APIController {
rsp := sentry.StartSpan(context.Background(), "authentik.outposts.init")
config := api.NewConfiguration()
config.Host = akURL.Host
config.Scheme = akURL.Scheme
config.HTTPClient = &http.Client{
Transport: web.NewUserAgentTransport(
constants.OutpostUserAgent(),
web.NewTracingTransport(
rsp.Context(),
GetTLSTransport(),
),
),
}
config.AddDefaultHeader("Authorization", fmt.Sprintf("Bearer %s", token))
// create the API client, with the transport
apiClient := api.NewAPIClient(config)
log := log.WithField("logger", "authentik.outpost.ak-api-controller")
// Because we don't know the outpost UUID, we simply do a list and pick the first
// The service account this token belongs to should only have access to a single outpost
outposts, _, err := apiClient.OutpostsApi.OutpostsInstancesList(context.Background()).Execute()
if err != nil {
log.WithError(err).Error("Failed to fetch outpost configuration, retrying in 3 seconds")
time.Sleep(time.Second * 3)
return NewAPIController(akURL, token)
}
if len(outposts.Results) < 1 {
panic("No outposts found with given token, ensure the given token corresponds to an authenitk Outpost")
}
outpost := outposts.Results[0]
log.WithField("name", outpost.Name).Debug("Fetched outpost configuration")
akConfig, _, err := apiClient.RootApi.RootConfigRetrieve(context.Background()).Execute()
if err != nil {
log.WithError(err).Error("Failed to fetch global configuration")
return nil
}
log.Debug("Fetched global configuration")
// doGlobalSetup is called by the OnRefresh handler, which ticks on start
// doGlobalSetup(outpost, akConfig)
ac := &APIController{
Client: apiClient,
GlobalConfig: akConfig,
token: token,
logger: log,
reloadOffset: time.Duration(rand.Intn(10)) * time.Second,
instanceUUID: uuid.New(),
Outpost: outpost,
wsHandlers: []WSHandler{},
wsBackoffMultiplier: 1,
refreshHandlers: make([]func(), 0),
}
ac.logger.WithField("offset", ac.reloadOffset.String()).Debug("HA Reload offset")
err = ac.initWS(akURL, outpost.Pk)
if err != nil {
go ac.reconnectWS()
}
ac.configureRefreshSignal()
return ac
}
// Start Starts all handlers, non-blocking
func (a *APIController) Start() error {
err := a.Server.Refresh()
if err != nil {
return err
}
err = a.StartBackgroundTasks()
if err != nil {
return err
}
go func() {
err := a.Server.Start()
if err != nil {
panic(err)
}
}()
return nil
}
func (a *APIController) configureRefreshSignal() {
s := make(chan os.Signal, 1)
go func() {
for {
<-s
err := a.OnRefresh()
if err != nil {
a.logger.WithError(err).Warning("failed to refresh")
}
}
}()
signal.Notify(s, syscall.SIGUSR1)
a.logger.Debug("Enabled USR1 hook to reload")
}
func (a *APIController) AddRefreshHandler(handler func()) {
a.refreshHandlers = append(a.refreshHandlers, handler)
}
enterprise/providers: Add RAC [AUTH-15] (#7291) * add basic guacamole Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make everything mostly work Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add rac build to CI Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix resize, fix web lint, sendSize correctly Signed-off-by: Jens Langhammer <jens@goauthentik.io> * pre-send connection from client, format Signed-off-by: Jens Langhammer <jens@goauthentik.io> * improve throughput Signed-off-by: Jens Langhammer <jens@goauthentik.io> * cleanup Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework TokenOutpostConsumer into middleware Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix some layout issues Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add outpost controllers Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start testing audio things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix a bunch of things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix to work with outpost group Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add simple loadbalancing Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add simple reconnect Signed-off-by: Jens Langhammer <jens@goauthentik.io> * show reconnecting text Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix error when checking ports Signed-off-by: Jens Langhammer <jens@goauthentik.io> * move to providers Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add flow check to interface Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix go lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix rac app label Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix audio Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add logging Signed-off-by: Jens Langhammer <jens@goauthentik.io> * cleanup Signed-off-by: Jens Langhammer <jens@goauthentik.io> * allow overriding all settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix duplicate keyboard, debug high DPI Signed-off-by: Jens Langhammer <jens@goauthentik.io> * re-add deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix missing __init__.py breaking model loading I love python Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * bump successful ws connection to info Signed-off-by: Jens Langhammer <jens@goauthentik.io> * hide cursor since guac draws that Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add clipboard support (bidirectional) Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make codespell not want to break the code Signed-off-by: Jens Langhammer <jens@goauthentik.io> * run pr comment in separate task Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start endpoint and property mapping stuff Signed-off-by: Jens Langhammer <jens@goauthentik.io> * more endpoint things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * unrelated: fix event model_pk filtering with ints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * unrelated: improve event display for changelog Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rebuild endpoint stuff again Signed-off-by: Jens Langhammer <jens@goauthentik.io> * idk special url Signed-off-by: Jens Langhammer <jens@goauthentik.io> * more stuff, connect token with session Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add disconnect Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework disconnect cleanly disconnect from guacd instead of just letting the connection timeout Signed-off-by: Jens Langhammer <jens@goauthentik.io> * clear cache when creating outpost Signed-off-by: Jens Langhammer <jens@goauthentik.io> * support host:port and fix protocol Signed-off-by: Jens Langhammer <jens@goauthentik.io> * center smaller viewport Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework connection to wait more and stop after some time Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add policy control to endpoints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * remove provider protocol Signed-off-by: Jens Langhammer <jens@goauthentik.io> * don't switch to different outpost connection when already chosen Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start using property mappings, add static settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add some RAC mapping settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start adding tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add tests for event changes Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add tests and fix issues found by said tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add preview banner, move endpoints to main page Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add locale Signed-off-by: Jens Langhammer <jens@goauthentik.io> * auto-select endpoint if only one is available Signed-off-by: Jens Langhammer <jens@goauthentik.io> * backport https://github.com/goauthentik/authentik/pull/7831 to rac Signed-off-by: Jens Langhammer <jens@goauthentik.io> * dont select property mappings on endpoints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make table modal only load when opened Signed-off-by: Jens Langhammer <jens@goauthentik.io> * only auto-redirect when open Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix web deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * check for token expiry and terminate session Signed-off-by: Jens Langhammer <jens@goauthentik.io> * re-add endpoint name to title Signed-off-by: Jens Langhammer <jens@goauthentik.io> * disconnect connection when token is manually deleted Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add initial RAC docs Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add connection expiry setting to provider Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix flaky tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> --------- Signed-off-by: Jens Langhammer <jens@goauthentik.io>
2023-12-30 20:33:14 +00:00
func (a *APIController) Token() string {
return a.token
}
func (a *APIController) OnRefresh() error {
// Because we don't know the outpost UUID, we simply do a list and pick the first
// The service account this token belongs to should only have access to a single outpost
outposts, _, err := a.Client.OutpostsApi.OutpostsInstancesList(context.Background()).Execute()
if err != nil {
log.WithError(err).Error("Failed to fetch outpost configuration")
return err
}
a.Outpost = outposts.Results[0]
a.logger.WithField("name", a.Outpost.Name).Debug("Fetched outpost configuration")
doGlobalSetup(a.Outpost, a.GlobalConfig)
err = a.Server.Refresh()
for _, handler := range a.refreshHandlers {
handler()
}
return err
}
enterprise/providers: Add RAC [AUTH-15] (#7291) * add basic guacamole Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make everything mostly work Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add rac build to CI Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix resize, fix web lint, sendSize correctly Signed-off-by: Jens Langhammer <jens@goauthentik.io> * pre-send connection from client, format Signed-off-by: Jens Langhammer <jens@goauthentik.io> * improve throughput Signed-off-by: Jens Langhammer <jens@goauthentik.io> * cleanup Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework TokenOutpostConsumer into middleware Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix some layout issues Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add outpost controllers Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start testing audio things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix a bunch of things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix to work with outpost group Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add simple loadbalancing Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add simple reconnect Signed-off-by: Jens Langhammer <jens@goauthentik.io> * show reconnecting text Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix error when checking ports Signed-off-by: Jens Langhammer <jens@goauthentik.io> * move to providers Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add flow check to interface Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix go lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix rac app label Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix audio Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add logging Signed-off-by: Jens Langhammer <jens@goauthentik.io> * cleanup Signed-off-by: Jens Langhammer <jens@goauthentik.io> * allow overriding all settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix duplicate keyboard, debug high DPI Signed-off-by: Jens Langhammer <jens@goauthentik.io> * re-add deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix missing __init__.py breaking model loading I love python Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * bump successful ws connection to info Signed-off-by: Jens Langhammer <jens@goauthentik.io> * hide cursor since guac draws that Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add clipboard support (bidirectional) Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make codespell not want to break the code Signed-off-by: Jens Langhammer <jens@goauthentik.io> * run pr comment in separate task Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start endpoint and property mapping stuff Signed-off-by: Jens Langhammer <jens@goauthentik.io> * more endpoint things Signed-off-by: Jens Langhammer <jens@goauthentik.io> * unrelated: fix event model_pk filtering with ints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * unrelated: improve event display for changelog Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rebuild endpoint stuff again Signed-off-by: Jens Langhammer <jens@goauthentik.io> * idk special url Signed-off-by: Jens Langhammer <jens@goauthentik.io> * more stuff, connect token with session Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add disconnect Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework disconnect cleanly disconnect from guacd instead of just letting the connection timeout Signed-off-by: Jens Langhammer <jens@goauthentik.io> * clear cache when creating outpost Signed-off-by: Jens Langhammer <jens@goauthentik.io> * support host:port and fix protocol Signed-off-by: Jens Langhammer <jens@goauthentik.io> * center smaller viewport Signed-off-by: Jens Langhammer <jens@goauthentik.io> * rework connection to wait more and stop after some time Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add policy control to endpoints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * remove provider protocol Signed-off-by: Jens Langhammer <jens@goauthentik.io> * don't switch to different outpost connection when already chosen Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start using property mappings, add static settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add some RAC mapping settings Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix lint Signed-off-by: Jens Langhammer <jens@goauthentik.io> * start adding tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add tests for event changes Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add tests and fix issues found by said tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add preview banner, move endpoints to main page Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add locale Signed-off-by: Jens Langhammer <jens@goauthentik.io> * auto-select endpoint if only one is available Signed-off-by: Jens Langhammer <jens@goauthentik.io> * backport https://github.com/goauthentik/authentik/pull/7831 to rac Signed-off-by: Jens Langhammer <jens@goauthentik.io> * dont select property mappings on endpoints Signed-off-by: Jens Langhammer <jens@goauthentik.io> * make table modal only load when opened Signed-off-by: Jens Langhammer <jens@goauthentik.io> * only auto-redirect when open Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix web deps Signed-off-by: Jens Langhammer <jens@goauthentik.io> * check for token expiry and terminate session Signed-off-by: Jens Langhammer <jens@goauthentik.io> * re-add endpoint name to title Signed-off-by: Jens Langhammer <jens@goauthentik.io> * disconnect connection when token is manually deleted Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add initial RAC docs Signed-off-by: Jens Langhammer <jens@goauthentik.io> * add connection expiry setting to provider Signed-off-by: Jens Langhammer <jens@goauthentik.io> * fix flaky tests Signed-off-by: Jens Langhammer <jens@goauthentik.io> --------- Signed-off-by: Jens Langhammer <jens@goauthentik.io>
2023-12-30 20:33:14 +00:00
func (a *APIController) getWebsocketPingArgs() map[string]interface{} {
args := map[string]interface{}{
"version": constants.VERSION,
"buildHash": constants.BUILD("tagged"),
"uuid": a.instanceUUID.String(),
}
hostname, err := os.Hostname()
if err == nil {
args["hostname"] = hostname
}
return args
}
func (a *APIController) StartBackgroundTasks() error {
OutpostInfo.With(prometheus.Labels{
"outpost_name": a.Outpost.Name,
"outpost_type": a.Server.Type(),
"uuid": a.instanceUUID.String(),
"version": constants.VERSION,
"build": constants.BUILD("tagged"),
}).Set(1)
go func() {
a.logger.Debug("Starting WS Handler...")
a.startWSHandler()
}()
go func() {
a.logger.Debug("Starting WS Health notifier...")
a.startWSHealth()
}()
go func() {
a.logger.Debug("Starting Interval updater...")
a.startIntervalUpdater()
}()
go func() {
a.logger.Debug("Starting periodical timer...")
a.startPeriodicalTasks()
}()
return nil
}