A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): check the api can connect to the SSO provider (#3689)
Hampusa12d20b2003c
diff --git a/fluxer_docs/src/content/docs/operator/sign-in.mdx b/fluxer_docs/src/content/docs/operator/sign-in.mdxindex 57b76c172..d69fffac7 100644--- a/fluxer_docs/src/content/docs/operator/sign-in.mdx+++ b/fluxer_docs/src/content/docs/operator/sign-in.mdx@@ -26,6 +26,17 @@ On an email instance, and whenever "Allowed Email Domains" is filled in, FluxerEvery URL for your provider has to use https and a public address. If your provider runs on your own network or in Docker next to Fluxer, run `rexctl config set sso.allow_private_addresses true`. The URLs still have to use https.+The browser opens your provider's sign-in page, and the API then connects to your provider from inside its container. When your provider runs on the same machine behind the same reverse proxy, the browser part can work while the API can't connect to the provider's public hostname, often because of hairpin NAT or IPv6 in Docker. Sign-in then fails after about 10 seconds, and the API logs say `fetch failed`. `sso.allow_private_addresses` doesn't help here. `rexctl doctor` checks that the API can load your provider's discovery document and connect to its token endpoint, and says which host failed and why. To fix it, run `rexctl config edit` and send the provider's hostname to this machine for the `api` service.++```yaml+services:+ api:+ extra_hosts:+ - "id.example.com:host-gateway"+```++Your reverse proxy has to accept connections from Docker, for example by listening on every interface. You can also make the provider's hostname resolve to an address that the API container can connect to.+With "Automatically provision users on first SSO login" on, the first sign-in from someone new creates their account. This happens even when registration is closed or needs an invite, and if new accounts need your approval, they still wait for it. To choose who gets in, limit access to Fluxer at your provider or fill in "Allowed Email Domains". In single-community mode, "Community Roles From Groups" maps groups at your provider to roles in the community, and each SSO sign-in adds or removes those roles. If the provider leaves out the groups claim, the person loses every mapped role. Keycloak leaves the claim out when someone is in no groups. Entra leaves it out when someone is in too many groups. Limit the token to the groups you map.When your provider's discovery document lists `client_secret_post`, Fluxer sends the client secret in the request body. When it lists no methods, or lists `client_secret_basic` and not `client_secret_post`, Fluxer uses HTTP Basic authentication first. If the provider turns the first attempt down with a 400 or 401 for any reason other than `invalid_grant`, Fluxer tries the other method once and remembers what worked. Fluxer doesn't follow redirects from your provider's discovery, token, userinfo or keys URLs, and each URL you enter has to be the one that answers. Fluxer can't use signed userinfo responses (`application/jwt`), and sign-in fails with `SSO_USER_INFO_SIGNED_RESPONSE_UNSUPPORTED` until you turn off userinfo signing for the client at your provider. When a sign-in fails at the provider, the API logs say what the provider sent back.diff --git a/fluxer_rexctl/internal/checks/checks.go b/fluxer_rexctl/internal/checks/checks.goindex 24aaef15d..a6af31e6e 100644--- a/fluxer_rexctl/internal/checks/checks.go+++ b/fluxer_rexctl/internal/checks/checks.go@@ -110,6 +110,7 @@ var order = []string{"postgres-scram","livekit-ip","client-ip",+ "sso-provider","backup-age",}diff --git a/fluxer_rexctl/internal/checks/sso_provider.go b/fluxer_rexctl/internal/checks/sso_provider.gonew file mode 100644index 000000000..c69f2102d--- /dev/null+++ b/fluxer_rexctl/internal/checks/sso_provider.go@@ -0,0 +1,217 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "encoding/json"+ "fmt"+ "net/url"+ "strings"+)++const ssoProbeSeconds = 8++func init() {+ Register(Check{ID: "sso-provider", Phases: Installed, Run: runSSOProvider})+}++type execFunc func(ctx context.Context, service, stdin string, command ...string) (string, error)++type ssoProbeInput struct {+ Discovery string `json:"discovery"`+ Token string `json:"token"`+ Timeout int `json:"timeout_ms"`+}++type ssoProbeOutput struct {+ OK bool `json:"ok"`+ Stage string `json:"stage"`+ Host string `json:"host"`+ Code string `json:"code"`+ Message string `json:"message"`+ Status int `json:"status"`+ Token string `json:"token_host"`+}++const ssoProbeScript = `+const net = require("node:net");+const tls = require("node:tls");+const input = JSON.parse(require("node:fs").readFileSync(0, "utf8"));+const done = (r) => { process.stdout.write(JSON.stringify(r) + "\n"); process.exit(0); };+const host = (u) => u.hostname.replace(/^\[|\]$/g, "");+const why = (e) => {+ let c = e;+ const code = (x) => (x && typeof x.code === "string" ? x.code : "");+ while (c && !code(c) && (c.cause || (c.errors && c.errors.length))) c = c.cause || c.errors[0];+ return { code: code(c) || (c && c.name) || (e && e.name) || "", message: String((c && c.message) || (c && c.errors && c.errors[0] && c.errors[0].message) || e) };+};+const connect = (u) => new Promise((resolve, reject) => {+ const h = host(u);+ const https = u.protocol === "https:";+ const port = Number(u.port) || (https ? 443 : 80);+ const opts = { host: h, port, timeout: input.timeout_ms };+ if (https && net.isIP(h) === 0) opts.servername = h;+ const s = https ? tls.connect(opts, () => { s.destroy(); resolve(); }) : net.connect(opts, () => { s.destroy(); resolve(); });+ s.on("timeout", () => { const e = new Error("connection timed out"); e.code = "ETIMEDOUT"; s.destroy(e); });+ s.on("error", reject);+});+(async () => {+ let token = input.token;+ let discoveryHost = "";+ if (input.discovery) {+ const u = new URL(input.discovery);+ discoveryHost = host(u);+ let res;+ try {+ res = await fetch(u, { redirect: "manual", headers: { accept: "application/json" }, signal: AbortSignal.timeout(input.timeout_ms) });+ } catch (e) {+ done({ ok: false, stage: "discovery", host: discoveryHost, ...why(e) });+ }+ if (res.status < 200 || res.status >= 300) done({ ok: false, stage: "discovery", host: discoveryHost, status: res.status });+ let doc;+ try { doc = await res.json(); } catch (e) { doc = null; }+ if (!doc || typeof doc !== "object" || typeof doc.issuer !== "string") done({ ok: false, stage: "discovery", host: discoveryHost, code: "NOT_DISCOVERY" });+ if (!token && typeof doc.token_endpoint === "string") token = doc.token_endpoint;+ }+ if (!token) done({ ok: true, host: discoveryHost });+ let t;+ try { t = new URL(token); } catch (e) { done({ ok: true, host: discoveryHost }); }+ try {+ await connect(t);+ } catch (e) {+ done({ ok: false, stage: "token", host: host(t), ...why(e) });+ }+ done({ ok: true, host: discoveryHost, token_host: host(t) });+})().catch((e) => done({ ok: false, stage: "probe", ...why(e) }));+`++func runSSOProvider(ctx context.Context, e *Env) Result {+ return ssoProvider(ctx, e, e.exec)+}++func ssoProvider(ctx context.Context, e *Env, run execFunc) Result {+ if e.Admin == nil || !e.running(ctx, "api") {+ return skip("")+ }+ cfg, err := e.Admin.Config(ctx)+ if err != nil || !cfg.Sso.Enabled {+ return skip("")+ }+ issuer := trimmed(cfg.Sso.Issuer)+ if issuer == "" {+ return skip("")+ }+ in := ssoProbeInput{Token: trimmed(cfg.Sso.TokenUrl), Timeout: ssoProbeSeconds * 1000}+ if trimmed(cfg.Sso.AuthorizationUrl) == "" || in.Token == "" || trimmed(cfg.Sso.JwksUrl) == "" || trimmed(cfg.Sso.UserinfoUrl) == "" {+ in.Discovery = discoveryURL(issuer)+ if in.Discovery == "" {+ return skip("")+ }+ }+ payload, err := json.Marshal(in)+ if err != nil {+ return skip("")+ }+ out, err := run(ctx, "api", string(payload), "node", "-e", ssoProbeScript)+ if err != nil {+ return skip("")+ }+ start := strings.Index(out, "{")+ if start < 0 {+ return skip("")+ }+ var p ssoProbeOutput+ if json.NewDecoder(strings.NewReader(out[start:])).Decode(&p) != nil {+ return skip("")+ }+ return ssoProbeResult(p, in.Discovery)+}++func trimmed(s *string) string {+ if s == nil {+ return ""+ }+ return strings.TrimSpace(*s)+}++func discoveryURL(issuer string) string {+ u, err := url.Parse(issuer)+ if err != nil || u.Scheme == "" || u.Host == "" {+ return ""+ }+ return strings.TrimSuffix(u.String(), "/") + "/.well-known/openid-configuration"+}++func ssoProbeResult(p ssoProbeOutput, discovery string) Result {+ if p.OK {+ if p.Token != "" && p.Host != "" && !strings.EqualFold(p.Token, p.Host) {+ return pass(fmt.Sprintf("The API connects to your SSO provider at %s and its token endpoint at %s.", p.Host, p.Token))+ }+ h := p.Host+ if h == "" {+ h = p.Token+ }+ return pass(fmt.Sprintf("The API connects to your SSO provider at %s.", h))+ }+ if p.Stage == "probe" || p.Host == "" {+ return skip("")+ }+ what := "your SSO provider"+ key := "sso.issuer"+ if p.Stage == "token" {+ what = "your SSO provider's token endpoint"+ key = "sso.token_url"+ }+ network := fmt.Sprintf("Make %s resolve to an address the API container can connect to. Add %q to extra_hosts for the api service with rexctl config edit, and make your reverse proxy accept connections from Docker.", p.Host, p.Host+":host-gateway")+ docFix := fmt.Sprintf("Check %s with rexctl config get %s. Your provider has to serve its discovery document at %s.", key, key, discovery)+ var r Result+ switch {+ case p.Status != 0:+ r = fail(fmt.Sprintf("%s at %s answered the API with HTTP %d.", capital(what), p.Host, p.Status),+ docFix)+ case p.Code == "NOT_DISCOVERY":+ r = fail(fmt.Sprintf("%s at %s didn't send the API a discovery document.", capital(what), p.Host),+ docFix)+ case p.Code == "ENOTFOUND" || p.Code == "EAI_AGAIN":+ r = fail(fmt.Sprintf("The API can't look up the address of %s at %s (%s).", what, p.Host, p.Code), network)+ case p.Code == "ECONNREFUSED" || p.Code == "ECONNRESET":+ r = fail(fmt.Sprintf("The API can't connect to %s at %s because the connection was refused (%s).", what, p.Host, p.Code), network)+ case p.Code == "TimeoutError" || p.Code == "AbortError" || p.Code == "ETIMEDOUT" || p.Code == "UND_ERR_CONNECT_TIMEOUT":+ r = fail(fmt.Sprintf("The API can't connect to %s at %s because the connection timed out after %d seconds.", what, p.Host, ssoProbeSeconds), network)+ case p.Code == "ENETUNREACH" || p.Code == "EHOSTUNREACH":+ r = fail(fmt.Sprintf("The API can't connect to %s at %s because there is no network route to it (%s).", what, p.Host, p.Code), network)+ case tlsCode(p.Code):+ r = fail(fmt.Sprintf("The API doesn't trust the certificate of %s at %s (%s).", what, p.Host, p.Code),+ fmt.Sprintf("Give %s a certificate for that name from a public certificate authority, or check that extra_hosts for the api service sends %s to the proxy that serves it.", p.Host, p.Host))+ default:+ code := p.Code+ if code == "" {+ code = "unknown error"+ }+ r = fail(fmt.Sprintf("The API can't connect to %s at %s (%s).", what, p.Host, code), network)+ }+ if p.Message != "" {+ r.Details = []string{p.Message}+ }+ return r+}++func tlsCode(code string) bool {+ if code == "EPROTO" || code == "DEPTH_ZERO_SELF_SIGNED_CERT" || code == "SELF_SIGNED_CERT_IN_CHAIN" {+ return true+ }+ for _, prefix := range []string{"CERT_", "UNABLE_TO_", "ERR_TLS_", "ERR_SSL_"} {+ if strings.HasPrefix(code, prefix) {+ return true+ }+ }+ return false+}++func capital(s string) string {+ if s == "" {+ return s+ }+ return strings.ToUpper(s[:1]) + s[1:]+}diff --git a/fluxer_rexctl/internal/checks/sso_provider_test.go b/fluxer_rexctl/internal/checks/sso_provider_test.gonew file mode 100644index 000000000..c78e85720--- /dev/null+++ b/fluxer_rexctl/internal/checks/sso_provider_test.go@@ -0,0 +1,223 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package checks++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/adminapi"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"+)++type fakeAdmin struct {+ sso map[string]any+ err error+}++func (f fakeAdmin) Do(_ context.Context, req adminapi.Request) (*adminapi.Response, error) {+ if f.err != nil {+ return nil, f.err+ }+ if req.Path != "/admin/instance/config" {+ return &adminapi.Response{Status: 404, Body: json.RawMessage(`{}`)}, nil+ }+ body, err := json.Marshal(map[string]any{"sso": f.sso})+ if err != nil {+ return nil, err+ }+ return &adminapi.Response{Status: 200, Body: body}, nil+}++type fakeExec struct {+ out string+ err error+ called bool+ service string+ stdin ssoProbeInput+ command []string+}++func (f *fakeExec) run(_ context.Context, service, stdin string, command ...string) (string, error) {+ f.called, f.service, f.command = true, service, command+ if err := json.Unmarshal([]byte(stdin), &f.stdin); err != nil {+ return "", err+ }+ return f.out, f.err+}++func ssoEnv(sso map[string]any, apiState string) *Env {+ e := &Env{prepared: true, psDone: true}+ if sso != nil {+ e.Admin = adminapi.New(fakeAdmin{sso: sso}, "")+ }+ if apiState != "" {+ e.ps = []engine.Container{{Service: "api", State: apiState}}+ }+ return e+}++func ssoOn() map[string]any {+ return map[string]any{"enabled": true, "issuer": "https://id.example.com/"}+}++func TestSSOProviderSkips(t *testing.T) {+ cases := map[string]struct {+ env *Env+ exec fakeExec+ }{+ "no admin API": {env: ssoEnv(nil, "running")},+ "api not running": {env: ssoEnv(ssoOn(), "exited")},+ "SSO off": {env: ssoEnv(map[string]any{"enabled": false, "issuer": "https://id.example.com"}, "running")},+ "no issuer": {env: ssoEnv(map[string]any{"enabled": true, "issuer": nil}, "running")},+ "blank issuer": {env: ssoEnv(map[string]any{"enabled": true, "issuer": " "}, "running")},+ "exec fails": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{err: errors.New("container gone")}},+ "no probe output": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{out: "node: not found"}},+ "probe threw": {env: ssoEnv(ssoOn(), "running"), exec: fakeExec{out: `{"ok":false,"stage":"probe","code":"TypeError"}`}},+ "admin API failed": {env: &Env{prepared: true, psDone: true, ps: []engine.Container{{Service: "api", State: "running"}}, Admin: adminapi.New(fakeAdmin{err: errors.New("relay down")}, "")}},+ }+ for name, c := range cases {+ t.Run(name, func(t *testing.T) {+ exec := c.exec+ r := ssoProvider(context.Background(), c.env, exec.run)+ if r.Status != Skip || r.Message != "" {+ t.Fatalf("got %+v, want a quiet skip", r)+ }+ })+ }+}++func TestSSOProviderPass(t *testing.T) {+ exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"auth.example.com"}`}+ r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)+ if r.Status != Pass {+ t.Fatalf("got %+v, want pass", r)+ }+ if want := "The API connects to your SSO provider at id.example.com and its token endpoint at auth.example.com."; r.Message != want {+ t.Fatalf("message %q, want %q", r.Message, want)+ }+ if exec.service != "api" || len(exec.command) != 3 || exec.command[0] != "node" || exec.command[1] != "-e" {+ t.Fatalf("ran %s %v, want node -e in api", exec.service, exec.command)+ }+ if want := "https://id.example.com/.well-known/openid-configuration"; exec.stdin.Discovery != want {+ t.Fatalf("discovery %q, want %q", exec.stdin.Discovery, want)+ }+ if exec.stdin.Token != "" || exec.stdin.Timeout != ssoProbeSeconds*1000 {+ t.Fatalf("got input %+v", exec.stdin)+ }+}++func TestSSOProviderPassOneHost(t *testing.T) {+ exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"id.example.com"}`}+ r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)+ if want := "The API connects to your SSO provider at id.example.com."; r.Status != Pass || r.Message != want {+ t.Fatalf("got %+v, want pass with %q", r, want)+ }+}++func TestSSOProviderUsesSetEndpoints(t *testing.T) {+ sso := ssoOn()+ sso["token_url"] = "https://auth.example.com/token"+ exec := &fakeExec{out: `{"ok":true,"host":"id.example.com","token_host":"auth.example.com"}`}+ ssoProvider(context.Background(), ssoEnv(sso, "running"), exec.run)+ if exec.stdin.Token != "https://auth.example.com/token" || exec.stdin.Discovery == "" {+ t.Fatalf("got input %+v, want discovery and the set token URL", exec.stdin)+ }+ sso["authorization_url"] = "https://id.example.com/authorize"+ sso["jwks_url"] = "https://id.example.com/jwks"+ sso["userinfo_url"] = "https://id.example.com/userinfo"+ exec = &fakeExec{out: `{"ok":true,"host":"","token_host":"auth.example.com"}`}+ r := ssoProvider(context.Background(), ssoEnv(sso, "running"), exec.run)+ if exec.stdin.Discovery != "" {+ t.Fatalf("got input %+v, want no discovery when every endpoint is set", exec.stdin)+ }+ if want := "The API connects to your SSO provider at auth.example.com."; r.Status != Pass || r.Message != want {+ t.Fatalf("got %+v, want pass with %q", r, want)+ }+}++func TestSSOProviderFailures(t *testing.T) {+ network := `Make id.example.com resolve to an address the API container can connect to. Add "id.example.com:host-gateway" to extra_hosts for the api service with rexctl config edit, and make your reverse proxy accept connections from Docker.`+ cases := []struct {+ name string+ out string+ message string+ fix string+ }{+ {+ name: "not found",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ENOTFOUND","message":"getaddrinfo ENOTFOUND id.example.com"}`,+ message: "The API can't look up the address of your SSO provider at id.example.com (ENOTFOUND).",+ fix: network,+ },+ {+ name: "refused",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ECONNREFUSED","message":"connect ECONNREFUSED 203.0.113.7:443"}`,+ message: "The API can't connect to your SSO provider at id.example.com because the connection was refused (ECONNREFUSED).",+ fix: network,+ },+ {+ name: "fetch timeout",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"TimeoutError","message":"The operation was aborted due to timeout"}`,+ message: "The API can't connect to your SSO provider at id.example.com because the connection timed out after 8 seconds.",+ fix: network,+ },+ {+ name: "no route",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"ENETUNREACH","message":"connect ENETUNREACH 2001:db8::7:443"}`,+ message: "The API can't connect to your SSO provider at id.example.com because there is no network route to it (ENETUNREACH).",+ fix: network,+ },+ {+ name: "certificate",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"CERT_HAS_EXPIRED","message":"certificate has expired"}`,+ message: "The API doesn't trust the certificate of your SSO provider at id.example.com (CERT_HAS_EXPIRED).",+ fix: "Give id.example.com a certificate for that name from a public certificate authority, or check that extra_hosts for the api service sends id.example.com to the proxy that serves it.",+ },+ {+ name: "HTTP status",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","status":404}`,+ message: "Your SSO provider at id.example.com answered the API with HTTP 404.",+ fix: "Check sso.issuer with rexctl config get sso.issuer. Your provider has to serve its discovery document at https://id.example.com/.well-known/openid-configuration.",+ },+ {+ name: "not a discovery document",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"NOT_DISCOVERY"}`,+ message: "Your SSO provider at id.example.com didn't send the API a discovery document.",+ fix: "Check sso.issuer with rexctl config get sso.issuer. Your provider has to serve its discovery document at https://id.example.com/.well-known/openid-configuration.",+ },+ {+ name: "token endpoint timeout",+ out: `{"ok":false,"stage":"token","host":"auth.example.com","code":"ETIMEDOUT","message":"connection timed out"}`,+ message: "The API can't connect to your SSO provider's token endpoint at auth.example.com because the connection timed out after 8 seconds.",+ fix: `Make auth.example.com resolve to an address the API container can connect to. Add "auth.example.com:host-gateway" to extra_hosts for the api service with rexctl config edit, and make your reverse proxy accept connections from Docker.`,+ },+ {+ name: "other cause",+ out: `{"ok":false,"stage":"discovery","host":"id.example.com","code":"EPIPE","message":"write EPIPE"}`,+ message: "The API can't connect to your SSO provider at id.example.com (EPIPE).",+ fix: network,+ },+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ exec := &fakeExec{out: "(node:1) ExperimentalWarning\n" + c.out + "\n"}+ r := ssoProvider(context.Background(), ssoEnv(ssoOn(), "running"), exec.run)+ if r.Status != Fail || r.Fixable {+ t.Fatalf("got %+v, want a failure rexctl can't fix", r)+ }+ if r.Message != c.message {+ t.Errorf("message %q, want %q", r.Message, c.message)+ }+ if r.Fix != c.fix {+ t.Errorf("fix %q, want %q", r.Fix, c.fix)+ }+ if strings.Contains(c.out, `"message"`) && len(r.Details) != 1 {+ t.Errorf("details %v, want the probe's error", r.Details)+ }+ })+ }+}