diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7df86d..8246872 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,13 @@ APIs change between minors without a deprecation period.
administration page and changes nothing, `operator` also runs the cluster
from them, `billing` sees usage and quotas. Set with `llmgw users role` or
the console's **Staff role…**.
+- **Single sign-on through OpenID Connect** (`auth.oidc`). A "Sign in
+ with …" button sends people to the identity provider and back, with PKCE,
+ state and nonce. The ID token is verified, and the account is found by
+ the verified email address, or made when `create_accounts` is on. Groups
+ give staff roles (`roles`, set at every sign-in) and places in the tree
+ (`memberships`). `no_passwords` leaves the provider as the only way in,
+ except for administrators.
### Guardrails
diff --git a/docs/install.md b/docs/install.md
index 64aa014..93190ec 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1080,6 +1080,44 @@ thing to get right is the health check: point it at `/ready`, not `/health`.
so a load balancer using it would send half the traffic to something that
refuses every request.
+## Single sign-on
+
+People can sign in through your identity provider — Keycloak, Entra ID,
+Google, Okta, Authentik, anything that speaks OpenID Connect.
+
+1. Register a client there with the redirect address
+ `https:///login/oidc/callback`.
+2. Put its secret in a file only root reads.
+3. Add to `server.yaml`:
+
+```yaml
+auth:
+ oidc:
+ issuer: https://login.example.com/realms/acme
+ client_id: llmgw
+ client_secret_file: /etc/llmgw/secrets/oidc-client-secret
+ label: Acme SSO # the button says "Sign in with Acme SSO"
+ create_accounts: true # make an active account for someone new
+ roles: # staff roles from groups, set at each sign-in
+ admin: [llmgw-admins]
+ operator: [llmgw-ops]
+ memberships: # groups to places in the tree, joined at sign-in
+ ml-engineers: "team:Acme/ml"
+ no_passwords: true # the provider only; administrators keep a password way in
+```
+
+How the sign-in works:
+
+- **Request:** it uses PKCE, a state and a nonce.
+- **Identity:** the ID token is verified against the provider's keys, and
+ the account is found by the verified email address.
+- **Unknown addresses:** without `create_accounts`, only people who already
+ have an account can sign in.
+- **Roles:** a person taken out of a group loses the role the next time
+ they sign in.
+- **Memberships:** they are added, never taken away.
+- **Audit:** each sign-in is recorded in the audit log.
+
## The firewall
`server init`, `node add`, `server add` and `mirror init` each keep that
diff --git a/docs/reference.md b/docs/reference.md
index 337a519..4eb3ba3 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -33,6 +33,7 @@ rather than repeated.
| `default_rpm` | `int` | [Auth](#auth) |
| `default_tpm` | `int` | [Auth](#auth) |
| `signup_open` | `bool` | [Auth](#auth) |
+| `oidc` | `OIDC` | [Auth](#auth) |
| `personal` | `Personal` | [Auth](#auth) |
| `pricing` | `map[string]Price` | [Auth](#auth) |
| `default_price` | `Price` | [Auth](#auth) |
@@ -106,6 +107,17 @@ rather than repeated.
| `prometheus` | `string` | [Monitoring](#monitoring) |
| `window` | `time.Duration` | [Monitoring](#monitoring) |
| `timeout` | `time.Duration` | [Monitoring](#monitoring) |
+| `issuer` | `string` | [OIDC](#oidc) |
+| `client_id` | `string` | [OIDC](#oidc) |
+| `client_secret_file` | `string` | [OIDC](#oidc) |
+| `redirect_url` | `string` | [OIDC](#oidc) |
+| `label` | `string` | [OIDC](#oidc) |
+| `scopes` | `[]string` | [OIDC](#oidc) |
+| `groups_claim` | `string` | [OIDC](#oidc) |
+| `create_accounts` | `bool` | [OIDC](#oidc) |
+| `roles` | `map[string][]string` | [OIDC](#oidc) |
+| `memberships` | `map[string]string` | [OIDC](#oidc) |
+| `no_passwords` | `bool` | [OIDC](#oidc) |
| `nvidia_smi` | `string` | [Options](#options) |
| `ib_root` | `string` | [Options](#options) |
| `prefer_nvml` | `bool` | [Options](#options) |
@@ -413,6 +425,14 @@ SignupOpen serves the signup form. Accounts it creates are pending until
an operator approves them, so this is not a way in — but turning it off
means accounts are made with `llmgw users create` instead.
+### `oidc`
+
+`OIDC`
+
+OIDC is sign-in through an identity provider.
+
+Takes a [OIDC](#oidc) block.
+
### `personal`
`Personal`
@@ -959,6 +979,85 @@ Window is how far back the charts look. Zero takes an hour.
Timeout bounds one query. It runs while somebody waits for a page, so a
monitoring system that is slow today is skipped rather than waited for.
+## OIDC
+
+### `issuer`
+
+`string`
+
+Issuer is the provider's address; its /.well-known/openid-configuration
+says the rest.
+
+### `client_id`
+
+`string`
+
+ClientID and the file holding its secret, as registered with the
+provider.
+
+### `client_secret_file`
+
+`string`
+
+### `redirect_url`
+
+`string`
+
+RedirectURL is where the provider sends people back:
+https:///login/oidc/callback. Empty works it out from the
+request, which is right unless a proxy changes the address.
+
+### `label`
+
+`string`
+
+Label is what the sign-in button says: "Sign in with ".
+
+### `scopes`
+
+`[]string`
+
+Scopes asked for besides openid; empty is email and profile, and
+groups when Roles or Memberships use them.
+
+### `groups_claim`
+
+`string`
+
+GroupsClaim names the ID token claim holding groups; empty is
+"groups".
+
+### `create_accounts`
+
+`bool`
+
+CreateAccounts makes an account, active, for a person the provider
+vouches for and the gateway does not know. Off, only existing accounts
+sign in this way.
+
+### `roles`
+
+`map[string][]string`
+
+Roles maps a staff role (viewer, operator, billing, admin) to the
+groups that give it. Set at every sign-in: someone taken out of the
+group loses the role the next time.
+
+### `memberships`
+
+`map[string]string`
+
+Memberships maps a group to a place in the tree — org:NAME,
+team:ORG/TEAM, project:ORG/TEAM/PROJECT — joined at sign-in.
+
+### `no_passwords`
+
+`bool`
+
+PasswordSignIn off refuses passwords on the sign-in form: people come
+in through the provider only. Administrators still can, so a broken
+provider does not lock everybody out.
+
## Options
### `nvidia_smi`
diff --git a/go.mod b/go.mod
index a4c5193..10cba6a 100644
--- a/go.mod
+++ b/go.mod
@@ -10,6 +10,8 @@ require (
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/charmbracelet/x/ansi v0.11.6
+ github.com/coreos/go-oidc/v3 v3.21.0
+ github.com/go-jose/go-jose/v4 v4.1.4
github.com/jackc/pgx/v5 v5.11.0
github.com/knadh/koanf/parsers/yaml v1.1.1
github.com/knadh/koanf/providers/env/v2 v2.0.1
@@ -28,7 +30,9 @@ require (
go.yaml.in/yaml/v3 v3.0.5
golang.org/x/crypto v0.57.0
golang.org/x/net v0.59.0
+ golang.org/x/oauth2 v0.37.0
golang.org/x/sync v0.23.0
+ golang.org/x/text v0.42.0
google.golang.org/protobuf v1.36.12
modernc.org/sqlite v1.59.0
)
@@ -79,7 +83,6 @@ require (
go.opentelemetry.io/otel/metric v1.46.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
golang.org/x/sys v0.48.0 // indirect
- golang.org/x/text v0.42.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260819154853-08b0e4226688 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260819154853-08b0e4226688 // indirect
google.golang.org/grpc v1.83.1 // indirect
diff --git a/go.sum b/go.sum
index f7c7f26..6211a65 100644
--- a/go.sum
+++ b/go.sum
@@ -36,6 +36,8 @@ github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfa
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
+github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
+github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
@@ -44,6 +46,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
+github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
+github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -169,6 +173,8 @@ golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
+golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
+golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
diff --git a/internal/config/config.go b/internal/config/config.go
index c03c568..fa43c38 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -290,6 +290,9 @@ type Auth struct {
// means accounts are made with `llmgw users create` instead.
SignupOpen bool `koanf:"signup_open"`
+ // OIDC is sign-in through an identity provider.
+ OIDC OIDC `koanf:"oidc"`
+
// Personal is what a person may do on their own, outside any project: make
// personal keys and use the chat page personally, within these limits.
Personal Personal `koanf:"personal"`
@@ -649,6 +652,9 @@ func (s Server) Validate() error {
if err := s.Guard.Validate(); err != nil {
return err
}
+ if err := s.Auth.OIDC.Validate(); err != nil {
+ return err
+ }
if err := s.AgentTLS.Validate(); err != nil {
return err
}
diff --git a/internal/config/engines_test.go b/internal/config/engines_test.go
index 8f79a94..2d39245 100644
--- a/internal/config/engines_test.go
+++ b/internal/config/engines_test.go
@@ -36,3 +36,21 @@ func TestEachNodeGetsTheEnginesItsOverridesSay(t *testing.T) {
}
}
}
+
+func TestOIDCSettingsAreCheckedBeforeAProviderIsAsked(t *testing.T) {
+ ok := OIDC{Issuer: "https://login.example.com/realms/acme", ClientID: "llmgw",
+ Roles: map[string][]string{"admin": {"g"}}, Memberships: map[string]string{"ml": "team:Acme/ml"}}
+ if err := ok.Validate(); err != nil {
+ t.Fatal(err)
+ }
+ for name, o := range map[string]OIDC{
+ "plain http": {Issuer: "http://login.example.com", ClientID: "x"},
+ "no client": {Issuer: "https://login.example.com"},
+ "unknown role": {Issuer: "https://l", ClientID: "x", Roles: map[string][]string{"god": {"g"}}},
+ "bad place": {Issuer: "https://l", ClientID: "x", Memberships: map[string]string{"g": "galaxy:x"}},
+ } {
+ if o.Validate() == nil {
+ t.Errorf("%s accepted", name)
+ }
+ }
+}
diff --git a/internal/config/oidc.go b/internal/config/oidc.go
new file mode 100644
index 0000000..b73bcac
--- /dev/null
+++ b/internal/config/oidc.go
@@ -0,0 +1,88 @@
+package config
+
+import (
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+)
+
+// OIDC is sign-in through an identity provider: Keycloak, Entra ID, Google,
+// Okta, Authentik — anything that speaks OpenID Connect.
+//
+// auth:
+// oidc:
+// issuer: https://login.example.com/realms/acme
+// client_id: llmgw
+// client_secret_file: /etc/llmgw/secrets/oidc-client-secret
+// label: Acme SSO
+// create_accounts: true
+// roles: {admin: [llmgw-admins], operator: [llmgw-ops]}
+// memberships: {ml-team: "team:Acme/ml"}
+type OIDC struct {
+ // Issuer is the provider's address; its /.well-known/openid-configuration
+ // says the rest.
+ Issuer string `koanf:"issuer"`
+ // ClientID and the file holding its secret, as registered with the
+ // provider.
+ ClientID string `koanf:"client_id"`
+ ClientSecretFile string `koanf:"client_secret_file"`
+ // RedirectURL is where the provider sends people back:
+ // https:///login/oidc/callback. Empty works it out from the
+ // request, which is right unless a proxy changes the address.
+ RedirectURL string `koanf:"redirect_url"`
+ // Label is what the sign-in button says: "Sign in with ".
+ Label string `koanf:"label"`
+ // Scopes asked for besides openid; empty is email and profile, and
+ // groups when Roles or Memberships use them.
+ Scopes []string `koanf:"scopes"`
+ // GroupsClaim names the ID token claim holding groups; empty is
+ // "groups".
+ GroupsClaim string `koanf:"groups_claim"`
+ // CreateAccounts makes an account, active, for a person the provider
+ // vouches for and the gateway does not know. Off, only existing accounts
+ // sign in this way.
+ CreateAccounts bool `koanf:"create_accounts"`
+ // Roles maps a staff role (viewer, operator, billing, admin) to the
+ // groups that give it. Set at every sign-in: someone taken out of the
+ // group loses the role the next time.
+ Roles map[string][]string `koanf:"roles"`
+ // Memberships maps a group to a place in the tree — org:NAME,
+ // team:ORG/TEAM, project:ORG/TEAM/PROJECT — joined at sign-in.
+ Memberships map[string]string `koanf:"memberships"`
+ // PasswordSignIn off refuses passwords on the sign-in form: people come
+ // in through the provider only. Administrators still can, so a broken
+ // provider does not lock everybody out.
+ NoPasswords bool `koanf:"no_passwords"`
+}
+
+// Enabled reports whether OIDC sign-in is configured.
+func (o OIDC) Enabled() bool { return o.Issuer != "" }
+
+// Validate checks the settings before a provider is asked anything.
+func (o OIDC) Validate() error {
+ if !o.Enabled() {
+ return nil
+ }
+ u, err := url.Parse(o.Issuer)
+ if err != nil || u.Scheme != "https" && !(u.Scheme == "http" && (u.Hostname() == "localhost" || u.Hostname() == "127.0.0.1")) {
+ return fmt.Errorf("auth.oidc.issuer %q: an https address", o.Issuer)
+ }
+ if o.ClientID == "" {
+ return errors.New("auth.oidc.client_id is required")
+ }
+ for role := range o.Roles {
+ switch role {
+ case "viewer", "operator", "billing", "admin":
+ default:
+ return fmt.Errorf("auth.oidc.roles: %q is not viewer, operator, billing or admin", role)
+ }
+ }
+ for g, where := range o.Memberships {
+ kind, path, ok := strings.Cut(where, ":")
+ if !ok || path == "" || (kind != "org" && kind != "team" && kind != "project") {
+ return fmt.Errorf("auth.oidc.memberships.%s is %q: org:NAME, team:ORG/TEAM or project:ORG/TEAM/PROJECT", g, where)
+ }
+ }
+ return nil
+}
diff --git a/internal/docgen/reference_gen.go b/internal/docgen/reference_gen.go
index 71d1a4e..a724a1b 100644
--- a/internal/docgen/reference_gen.go
+++ b/internal/docgen/reference_gen.go
@@ -27,6 +27,7 @@ var Reference = []Block{
{Key: "default_rpm", Type: "int", Doc: "DefaultRPM and DefaultTPM apply to a key that no scope gives a limit to.\n\nUnlimited used to be the default, and a project created without limits is\nthe easy path — the \"default\" project on this cluster still is one. The\nfirst sign of that is the bill or the outage. Zero keeps the old\nbehaviour for anyone who wants it, but it should be a choice rather than\nan omission. A fallback, not a ceiling: an explicit limit at any scope\nwins, above or below.", Nested: ""},
{Key: "default_tpm", Type: "int", Doc: "", Nested: ""},
{Key: "signup_open", Type: "bool", Doc: "SignupOpen serves the signup form. Accounts it creates are pending until\nan operator approves them, so this is not a way in — but turning it off\nmeans accounts are made with `llmgw users create` instead.", Nested: ""},
+ {Key: "oidc", Type: "OIDC", Doc: "OIDC is sign-in through an identity provider.", Nested: "config.OIDC"},
{Key: "personal", Type: "Personal", Doc: "Personal is what a person may do on their own, outside any project: make\npersonal keys and use the chat page personally, within these limits.", Nested: "config.Personal"},
{Key: "pricing", Type: "map[string]Price", Doc: "Pricing is what each model costs, for budgets. A model absent from the\ntable costs whatever DefaultPrice says, which is nothing unless set.", Nested: ""},
{Key: "default_price", Type: "Price", Doc: "", Nested: "config.Price"},
@@ -125,6 +126,19 @@ var Reference = []Block{
{Key: "window", Type: "time.Duration", Doc: "Window is how far back the charts look. Zero takes an hour.", Nested: ""},
{Key: "timeout", Type: "time.Duration", Doc: "Timeout bounds one query. It runs while somebody waits for a page, so a\nmonitoring system that is slow today is skipped rather than waited for.", Nested: ""},
}},
+ {Package: "config", Name: "OIDC", Title: "OIDC", Doc: "", Fields: []Field{
+ {Key: "issuer", Type: "string", Doc: "Issuer is the provider's address; its /.well-known/openid-configuration\nsays the rest.", Nested: ""},
+ {Key: "client_id", Type: "string", Doc: "ClientID and the file holding its secret, as registered with the\nprovider.", Nested: ""},
+ {Key: "client_secret_file", Type: "string", Doc: "", Nested: ""},
+ {Key: "redirect_url", Type: "string", Doc: "RedirectURL is where the provider sends people back:\nhttps:///login/oidc/callback. Empty works it out from the\nrequest, which is right unless a proxy changes the address.", Nested: ""},
+ {Key: "label", Type: "string", Doc: "Label is what the sign-in button says: \"Sign in with \".", Nested: ""},
+ {Key: "scopes", Type: "[]string", Doc: "Scopes asked for besides openid; empty is email and profile, and\ngroups when Roles or Memberships use them.", Nested: ""},
+ {Key: "groups_claim", Type: "string", Doc: "GroupsClaim names the ID token claim holding groups; empty is\n\"groups\".", Nested: ""},
+ {Key: "create_accounts", Type: "bool", Doc: "CreateAccounts makes an account, active, for a person the provider\nvouches for and the gateway does not know. Off, only existing accounts\nsign in this way.", Nested: ""},
+ {Key: "roles", Type: "map[string][]string", Doc: "Roles maps a staff role (viewer, operator, billing, admin) to the\ngroups that give it. Set at every sign-in: someone taken out of the\ngroup loses the role the next time.", Nested: ""},
+ {Key: "memberships", Type: "map[string]string", Doc: "Memberships maps a group to a place in the tree — org:NAME,\nteam:ORG/TEAM, project:ORG/TEAM/PROJECT — joined at sign-in.", Nested: ""},
+ {Key: "no_passwords", Type: "bool", Doc: "PasswordSignIn off refuses passwords on the sign-in form: people come\nin through the provider only. Administrators still can, so a broken\nprovider does not lock everybody out.", Nested: ""},
+ }},
{Package: "discovery", Name: "Options", Title: "Options", Doc: "", Fields: []Field{
{Key: "nvidia_smi", Type: "string", Doc: "NvidiaSMI is the path to nvidia-smi; empty means look it up on PATH.\nWorth configuring on nodes where the driver lives outside the default\npaths, which containerized driver installs often do.", Nested: ""},
{Key: "ib_root", Type: "string", Doc: "IBRoot is the sysfs InfiniBand directory.", Nested: ""},
diff --git a/internal/docgen/render.go b/internal/docgen/render.go
index e529608..ef9a1c7 100644
--- a/internal/docgen/render.go
+++ b/internal/docgen/render.go
@@ -28,6 +28,7 @@ var Sources = []string{
"internal/accounting/cost.go",
"internal/guard/policy.go",
"internal/guard/judge.go",
+ "internal/config/oidc.go",
}
// notReference are files with koanf tags that an operator never writes.
diff --git a/internal/router/handlers.go b/internal/router/handlers.go
index 9fd938e..f735ac5 100644
--- a/internal/router/handlers.go
+++ b/internal/router/handlers.go
@@ -182,6 +182,11 @@ func (r *Router) Handler() http.Handler {
pages.SetPersonalDefaults(r.personalDefaults)
if r.store != nil {
pages.SetAudit(r.store)
+ if r.oidc.Enabled() {
+ if err := pages.RegisterOIDC(mux, r.oidc, r.store); err != nil {
+ r.log.Error("single sign-on is off", "err", err)
+ }
+ }
}
if pol, ok := r.guard.(interface {
Policy(guard.Subject) (guard.Policy, string)
diff --git a/internal/router/router.go b/internal/router/router.go
index c897c86..940781f 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -93,6 +93,8 @@ type Router struct {
// is the policies it was built from, for the pages that show them.
guard guard.Guard
guardLibrary guard.Config
+ // oidc is sign-in through an identity provider.
+ oidc config.OIDC
// threads holds conversations and memory notes. It is store when auth is on,
// its own file when only the threads block is configured, and nil when
@@ -278,6 +280,7 @@ func New(cfg config.Server, log *slog.Logger) (*Router, error) {
st.SetDefaultLimits(defRPM, defTPM)
st.SetPersonalDefaults(personalLimits(cfg.Auth.Personal))
r.personalOff = cfg.Auth.Personal.Disabled
+ r.oidc = cfg.Auth.OIDC
r.personalDefaults = personalLimits(cfg.Auth.Personal)
r.llamaVersion = cfg.WantedEngines()["llamacpp"]
diff --git a/internal/web/account.go b/internal/web/account.go
index 96eef85..bd47ac3 100644
--- a/internal/web/account.go
+++ b/internal/web/account.go
@@ -66,6 +66,8 @@ type AccountPages struct {
hasMirror bool
// hasQuotas is set when /admin/quotas is registered.
hasQuotas bool
+ // oidc is sign-in through an identity provider; nil when there is none.
+ oidc *oidcLogin
// audit records every change made through these pages; nil records none.
audit audit.Sink
// hasGuard is set when /admin/guard is registered.
@@ -204,17 +206,27 @@ func (p *AccountPages) signup(w http.ResponseWriter, r *http.Request) {
// --- sign in and out ---
+// ssoLabel is what the sign-in button names, or "" without one.
+func (p *AccountPages) ssoLabel() string {
+ if p.oidc == nil {
+ return ""
+ }
+ return or(p.oidc.cfg.Label, "single sign-on")
+}
+
type loginData struct {
Email, Error string
SignupOpen bool
Version string
+ // SSO is the identity provider's label, when sign-in through one is on.
+ SSO string
// CSRF is the form's token, matched by a cookie.
CSRF string
}
func (p *AccountPages) loginForm(w http.ResponseWriter, r *http.Request) {
noStore(w)
- render(w, "login", loginData{SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)})
+ render(w, "login", loginData{SSO: p.ssoLabel(), SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)})
}
func (p *AccountPages) login(w http.ResponseWriter, r *http.Request) {
@@ -223,7 +235,7 @@ func (p *AccountPages) login(w http.ResponseWriter, r *http.Request) {
if !loginTokenOK(r) {
// Not this site's form: another one posting a visitor into an
// account of its choosing, or a form left open past its hour.
- renderStatus(w, http.StatusBadRequest, "login", loginData{Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version,
+ renderStatus(w, http.StatusBadRequest, "login", loginData{SSO: p.ssoLabel(), Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version,
Error: "the form had expired; sign in again", CSRF: setLoginToken(w, r)})
return
}
@@ -231,7 +243,7 @@ func (p *AccountPages) login(w http.ResponseWriter, r *http.Request) {
ctx := account.WithClient(r.Context(), clientAddr(r))
token, csrf, err := p.accounts.SignIn(ctx, email, r.FormValue("password"))
if err != nil {
- d := loginData{Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)}
+ d := loginData{SSO: p.ssoLabel(), Email: email, SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r)}
switch {
case errors.Is(err, account.ErrBadCredentials),
errors.Is(err, account.ErrNotApproved),
@@ -246,6 +258,17 @@ func (p *AccountPages) login(w http.ResponseWriter, r *http.Request) {
renderStatus(w, http.StatusUnauthorized, "login", d)
return
}
+ // Through the provider only, except an administrator's way in for when
+ // the provider itself is broken.
+ if p.oidc != nil && p.oidc.cfg.NoPasswords {
+ if _, u, err := p.accounts.Resolve(ctx, token); err != nil || !u.IsAdmin {
+ _ = p.accounts.SignOut(ctx, token)
+ renderStatus(w, http.StatusForbidden, "login", loginData{SSO: p.ssoLabel(), Email: email,
+ SignupOpen: p.accounts.SignupOpen(), Version: p.version, CSRF: setLoginToken(w, r),
+ Error: "this gateway signs people in with " + p.ssoLabel() + ", not passwords"})
+ return
+ }
+ }
setSessionCookie(w, r, token)
setCSRFCookie(w, r, csrf)
diff --git a/internal/web/oidc.go b/internal/web/oidc.go
new file mode 100644
index 0000000..5f76fa7
--- /dev/null
+++ b/internal/web/oidc.go
@@ -0,0 +1,366 @@
+package web
+
+import (
+ "context"
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/coreos/go-oidc/v3/oidc"
+ "golang.org/x/oauth2"
+
+ "gitea.mynodes.xyz/ilker/llmgw/internal/audit"
+ "gitea.mynodes.xyz/ilker/llmgw/internal/config"
+ "gitea.mynodes.xyz/ilker/llmgw/internal/store"
+)
+
+// OIDCStore is what signing in through a provider needs of the store.
+type OIDCStore interface {
+ UserByEmail(ctx context.Context, email string) (store.User, error)
+ CreateUser(ctx context.Context, u store.User) error
+ SetStaffRole(ctx context.Context, id, role string) error
+ AddMembership(ctx context.Context, user string, scope store.Scope, id, role, by string, at time.Time) error
+ AllOrgs(ctx context.Context) ([]store.Org, error)
+ AllTeams(ctx context.Context) ([]store.TeamPath, error)
+ AllProjects(ctx context.Context) ([]store.ProjectPath, error)
+}
+
+// oidcLogin is sign-in through an identity provider.
+type oidcLogin struct {
+ cfg config.OIDC
+ secret string
+ st OIDCStore
+ key []byte // signs the cookie that carries a sign-in across the provider
+
+ mu sync.Mutex
+ provider *oidc.Provider
+}
+
+const oidcCookie = "llmgw_oidc"
+
+// RegisterOIDC mounts /login/oidc and its callback, and puts the button on
+// the sign-in page.
+func (p *AccountPages) RegisterOIDC(mux *http.ServeMux, cfg config.OIDC, st OIDCStore) error {
+ secret := ""
+ if cfg.ClientSecretFile != "" {
+ b, err := os.ReadFile(cfg.ClientSecretFile)
+ if err != nil {
+ return fmt.Errorf("auth.oidc.client_secret_file: %w", err)
+ }
+ secret = strings.TrimSpace(string(b))
+ }
+ key := make([]byte, 32)
+ if _, err := rand.Read(key); err != nil {
+ return err
+ }
+ o := &oidcLogin{cfg: cfg, secret: secret, st: st, key: key}
+ p.oidc = o
+ mux.HandleFunc("GET /login/oidc", p.oidcStart)
+ mux.HandleFunc("GET /login/oidc/callback", p.oidcCallback)
+ return nil
+}
+
+// providerFor discovers the provider the first time it is needed, and again
+// after a failure: a provider down when the gateway started is no reason for
+// sign-in never to work.
+func (o *oidcLogin) providerFor(ctx context.Context) (*oidc.Provider, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if o.provider != nil {
+ return o.provider, nil
+ }
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ pr, err := oidc.NewProvider(ctx, o.cfg.Issuer)
+ if err != nil {
+ return nil, err
+ }
+ o.provider = pr
+ return pr, nil
+}
+
+func (o *oidcLogin) oauth(pr *oidc.Provider, r *http.Request) *oauth2.Config {
+ redirect := o.cfg.RedirectURL
+ if redirect == "" {
+ redirect = baseURL(r) + "/login/oidc/callback"
+ }
+ scopes := []string{oidc.ScopeOpenID}
+ if len(o.cfg.Scopes) > 0 {
+ scopes = append(scopes, o.cfg.Scopes...)
+ } else {
+ scopes = append(scopes, "email", "profile")
+ if len(o.cfg.Roles) > 0 || len(o.cfg.Memberships) > 0 {
+ scopes = append(scopes, "groups")
+ }
+ }
+ return &oauth2.Config{ClientID: o.cfg.ClientID, ClientSecret: o.secret, Endpoint: pr.Endpoint(),
+ RedirectURL: redirect, Scopes: scopes}
+}
+
+// The cookie: state, nonce and PKCE verifier, and when, signed.
+func (o *oidcLogin) seal(parts ...string) string {
+ v := strings.Join(parts, ".")
+ m := hmac.New(sha256.New, o.key)
+ m.Write([]byte(v))
+ return v + "." + hex.EncodeToString(m.Sum(nil))
+}
+
+func (o *oidcLogin) open(c string) ([]string, bool) {
+ i := strings.LastIndex(c, ".")
+ if i < 0 {
+ return nil, false
+ }
+ v, sig := c[:i], c[i+1:]
+ m := hmac.New(sha256.New, o.key)
+ m.Write([]byte(v))
+ want := hex.EncodeToString(m.Sum(nil))
+ if !hmac.Equal([]byte(sig), []byte(want)) {
+ return nil, false
+ }
+ return strings.Split(v, "."), true
+}
+
+func randomToken() string {
+ b := make([]byte, 24)
+ _, _ = rand.Read(b)
+ return base64.RawURLEncoding.EncodeToString(b)
+}
+
+func (p *AccountPages) oidcStart(w http.ResponseWriter, r *http.Request) {
+ noStore(w)
+ o := p.oidc
+ pr, err := o.providerFor(r.Context())
+ if err != nil {
+ p.log.Warn("the identity provider did not answer", "issuer", o.cfg.Issuer, "err", err)
+ renderStatus(w, http.StatusBadGateway, "login", loginData{SignupOpen: p.accounts.SignupOpen(), Version: p.version,
+ CSRF: setLoginToken(w, r), SSO: o.cfg.Label, Error: "the sign-in service did not answer; try again shortly"})
+ return
+ }
+ state, nonce, verifier := randomToken(), randomToken(), oauth2.GenerateVerifier()
+ http.SetCookie(w, &http.Cookie{Name: oidcCookie, Value: o.seal(state, nonce, verifier,
+ fmt.Sprint(time.Now().Unix())), Path: "/login/oidc", MaxAge: 600, HttpOnly: true,
+ Secure: isHTTPS(r), SameSite: http.SameSiteLaxMode})
+ http.Redirect(w, r, o.oauth(pr, r).AuthCodeURL(state, oidc.Nonce(nonce), oauth2.S256ChallengeOption(verifier)),
+ http.StatusFound)
+}
+
+// errOIDC is a sign-in through the provider that did not work, said plainly.
+var errOIDC = errors.New("signing in through the provider did not work; start again")
+
+func (p *AccountPages) oidcCallback(w http.ResponseWriter, r *http.Request) {
+ noStore(w)
+ o := p.oidc
+ fail := func(why string, err error) {
+ p.log.Warn("an OIDC sign-in was refused", "why", why, "err", err)
+ http.SetCookie(w, &http.Cookie{Name: oidcCookie, Path: "/login/oidc", MaxAge: -1})
+ msg := errOIDC.Error()
+ if errors.Is(err, errOIDCAccount) {
+ msg = err.Error()
+ }
+ renderStatus(w, http.StatusForbidden, "login", loginData{SignupOpen: p.accounts.SignupOpen(),
+ Version: p.version, CSRF: setLoginToken(w, r), SSO: o.cfg.Label, Error: msg})
+ }
+ c, err := r.Cookie(oidcCookie)
+ if err != nil {
+ fail("no sign-in under way", err)
+ return
+ }
+ parts, ok := o.open(c.Value)
+ if !ok || len(parts) != 4 || r.URL.Query().Get("state") != parts[0] {
+ fail("state", nil)
+ return
+ }
+ if e := r.URL.Query().Get("error"); e != "" {
+ fail("the provider said "+e, nil)
+ return
+ }
+ pr, err := o.providerFor(r.Context())
+ if err != nil {
+ fail("provider", err)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
+ defer cancel()
+ tok, err := o.oauth(pr, r).Exchange(ctx, r.URL.Query().Get("code"), oauth2.VerifierOption(parts[2]))
+ if err != nil {
+ fail("code exchange", err)
+ return
+ }
+ raw, _ := tok.Extra("id_token").(string)
+ idt, err := pr.Verifier(&oidc.Config{ClientID: o.cfg.ClientID}).Verify(ctx, raw)
+ if err != nil {
+ fail("id token", err)
+ return
+ }
+ if idt.Nonce != parts[1] {
+ fail("nonce", nil)
+ return
+ }
+ var claims map[string]any
+ if err := idt.Claims(&claims); err != nil {
+ fail("claims", err)
+ return
+ }
+ user, err := p.oidcUser(ctx, claims)
+ if err != nil {
+ fail("account", err)
+ return
+ }
+ token, csrf, err := p.accounts.OpenSession(ctx, user.ID)
+ if err != nil {
+ fail("session", err)
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: oidcCookie, Path: "/login/oidc", MaxAge: -1})
+ setSessionCookie(w, r, token)
+ setCSRFCookie(w, r, csrf)
+ audit.Write(r.Context(), p.audit, p.log, store.AuditEvent{At: time.Now(), Actor: user.Email, Source: "web",
+ Action: "sign in through " + o.cfg.Issuer, Status: http.StatusSeeOther,
+ Detail: audit.Redact(map[string]any{"role": user.StaffRole()})})
+ http.Redirect(w, r, "/profile", http.StatusSeeOther)
+}
+
+// errOIDCAccount is a provider's person the gateway will not let in, with why.
+var errOIDCAccount = errors.New("")
+
+type accountError string
+
+func (e accountError) Error() string { return string(e) }
+func (e accountError) Is(t error) bool { return t == errOIDCAccount }
+
+// oidcUser is the account a provider's person signs in as: found by their
+// verified email, made when the gateway makes accounts this way, with the
+// staff role and the memberships their groups give.
+func (p *AccountPages) oidcUser(ctx context.Context, claims map[string]any) (store.User, error) {
+ o := p.oidc
+ email, _ := claims["email"].(string)
+ email = store.NormalizeEmail(email)
+ if email == "" {
+ return store.User{}, accountError("the provider gave no email address; ask it to send the email claim")
+ }
+ if v, ok := claims["email_verified"].(bool); ok && !v {
+ return store.User{}, accountError("the provider has not verified " + email)
+ }
+ u, err := o.st.UserByEmail(ctx, email)
+ switch {
+ case errors.Is(err, store.ErrNotFound) && o.cfg.CreateAccounts:
+ name, _ := claims["name"].(string)
+ if name == "" {
+ name = email
+ }
+ u = store.User{ID: "usr-" + strings.ToLower(randomToken()[:16]), Email: email, Name: name,
+ // No password works: this account signs in through the provider.
+ PasswordHash: "!oidc", State: store.UserActive, CreatedAt: time.Now()}
+ if err := o.st.CreateUser(ctx, u); err != nil {
+ return store.User{}, err
+ }
+ p.log.Info("an account was made for a person the identity provider vouched for", "email", email)
+ case errors.Is(err, store.ErrNotFound):
+ return store.User{}, accountError("there is no account for " + email + " on this gateway; ask an administrator for one")
+ case err != nil:
+ return store.User{}, err
+ }
+ if !u.CanSignIn() {
+ return store.User{}, accountError("the account for " + email + " is " + string(u.State))
+ }
+
+ groups := claimStrings(claims[or(o.cfg.GroupsClaim, "groups")])
+ if len(o.cfg.Roles) > 0 {
+ role := ""
+ for _, r := range []string{store.RoleAdmin, store.RoleOperator, store.RoleBilling, store.RoleViewer} {
+ if slices.ContainsFunc(o.cfg.Roles[r], func(g string) bool { return slices.Contains(groups, g) }) {
+ role = r
+ break
+ }
+ }
+ if role != u.StaffRole() {
+ if err := o.st.SetStaffRole(ctx, u.ID, role); err != nil {
+ return store.User{}, err
+ }
+ u.IsAdmin, u.Role = role == store.RoleAdmin, role
+ if role == store.RoleAdmin {
+ u.Role = ""
+ }
+ }
+ }
+ for _, g := range groups {
+ where, ok := o.cfg.Memberships[g]
+ if !ok {
+ continue
+ }
+ scope, id, err := p.oidcPlace(ctx, where)
+ if err != nil {
+ p.log.Warn("a group maps to a place the tree does not have", "group", g, "place", where, "err", err)
+ continue
+ }
+ if err := o.st.AddMembership(ctx, u.ID, scope, id, store.RoleMember, "oidc", time.Now()); err != nil {
+ p.log.Warn("could not add a membership from a group", "group", g, "err", err)
+ }
+ }
+ return u, nil
+}
+
+// oidcPlace finds org:NAME, team:ORG/TEAM, project:ORG/TEAM/PROJECT.
+func (p *AccountPages) oidcPlace(ctx context.Context, where string) (store.Scope, string, error) {
+ kind, path, _ := strings.Cut(where, ":")
+ same := func(a string) bool { return strings.EqualFold(a, path) }
+ switch kind {
+ case "org":
+ orgs, err := p.oidc.st.AllOrgs(ctx)
+ for _, o := range orgs {
+ if same(o.Name) {
+ return store.ScopeOrg, o.ID, nil
+ }
+ }
+ return "", "", errors.Join(err, errors.New("no such organization"))
+ case "team":
+ teams, err := p.oidc.st.AllTeams(ctx)
+ for _, t := range teams {
+ if same(t.OrgName + "/" + t.Name) {
+ return store.ScopeTeam, t.ID, nil
+ }
+ }
+ return "", "", errors.Join(err, errors.New("no such team"))
+ default:
+ projects, err := p.oidc.st.AllProjects(ctx)
+ for _, pp := range projects {
+ if same(pp.Path) {
+ return store.ScopeProject, pp.ID, nil
+ }
+ }
+ return "", "", errors.Join(err, errors.New("no such project"))
+ }
+}
+
+func claimStrings(v any) []string {
+ switch t := v.(type) {
+ case []any:
+ var out []string
+ for _, x := range t {
+ if s, ok := x.(string); ok {
+ out = append(out, s)
+ }
+ }
+ return out
+ case string:
+ return []string{t}
+ }
+ return nil
+}
+
+func or(s, def string) string {
+ if s == "" {
+ return def
+ }
+ return s
+}
diff --git a/internal/web/oidc_test.go b/internal/web/oidc_test.go
new file mode 100644
index 0000000..b98ce5e
--- /dev/null
+++ b/internal/web/oidc_test.go
@@ -0,0 +1,171 @@
+package web
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/rsa"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ jose "github.com/go-jose/go-jose/v4"
+ "github.com/go-jose/go-jose/v4/jwt"
+
+ "gitea.mynodes.xyz/ilker/llmgw/internal/config"
+ "gitea.mynodes.xyz/ilker/llmgw/internal/store"
+)
+
+// fakeIdP is an OpenID provider that issues an ID token with whatever
+// claims the test sets.
+type fakeIdP struct {
+ srv *httptest.Server
+ key *rsa.PrivateKey
+ claims map[string]any
+ nonce string
+}
+
+func newFakeIdP(t *testing.T) *fakeIdP {
+ t.Helper()
+ k, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f := &fakeIdP{key: k}
+ mux := http.NewServeMux()
+ f.srv = httptest.NewServer(mux)
+ t.Cleanup(f.srv.Close)
+ mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"issuer": f.srv.URL,
+ "authorization_endpoint": f.srv.URL + "/authorize", "token_endpoint": f.srv.URL + "/token",
+ "jwks_uri": f.srv.URL + "/jwks", "id_token_signing_alg_values_supported": []string{"RS256"}})
+ })
+ mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) {
+ _ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{
+ {Key: &k.PublicKey, KeyID: "k1", Algorithm: "RS256", Use: "sig"}}})
+ })
+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ if r.Form.Get("code_verifier") == "" {
+ http.Error(w, "pkce", 400)
+ return
+ }
+ signer, _ := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: k},
+ (&jose.SignerOptions{}).WithHeader("kid", "k1"))
+ c := map[string]any{"iss": f.srv.URL, "aud": "llmgw", "sub": "s1", "nonce": f.nonce,
+ "iat": time.Now().Unix(), "exp": time.Now().Add(time.Minute).Unix()}
+ for k, v := range f.claims {
+ c[k] = v
+ }
+ tok, _ := jwt.Signed(signer).Claims(c).Serialize()
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "a", "token_type": "Bearer", "id_token": tok})
+ })
+ return f
+}
+
+type oidcStoreMem struct {
+ users map[string]store.User
+ roles map[string]string
+ joined []string
+}
+
+func (m *oidcStoreMem) UserByEmail(_ context.Context, e string) (store.User, error) {
+ if u, ok := m.users[e]; ok {
+ return u, nil
+ }
+ return store.User{}, store.ErrNotFound
+}
+func (m *oidcStoreMem) CreateUser(_ context.Context, u store.User) error { m.users[u.Email] = u; return nil }
+func (m *oidcStoreMem) SetStaffRole(_ context.Context, id, role string) error {
+ m.roles[id] = role
+ return nil
+}
+func (m *oidcStoreMem) AddMembership(_ context.Context, user string, scope store.Scope, id, _, _ string, _ time.Time) error {
+ m.joined = append(m.joined, user+"@"+string(scope)+":"+id)
+ return nil
+}
+func (m *oidcStoreMem) AllOrgs(context.Context) ([]store.Org, error) { return nil, nil }
+func (m *oidcStoreMem) AllTeams(context.Context) ([]store.TeamPath, error) {
+ return []store.TeamPath{{ID: "t1", Name: "ml", OrgName: "Acme"}}, nil
+}
+func (m *oidcStoreMem) AllProjects(context.Context) ([]store.ProjectPath, error) { return nil, nil }
+
+type sessionAccounts struct{ fakeAccounts }
+
+func (sessionAccounts) OpenSession(context.Context, string) (string, string, error) {
+ return "sess", "csrf", nil
+}
+
+// signIn goes through /login/oidc and back, as a browser would.
+func signIn(t *testing.T, mux http.Handler, idp *fakeIdP, tamper bool) *httptest.ResponseRecorder {
+ t.Helper()
+ start := httptest.NewRecorder()
+ mux.ServeHTTP(start, httptest.NewRequest("GET", "/login/oidc", nil))
+ if start.Code != http.StatusFound {
+ t.Fatalf("start: %d %s", start.Code, start.Body.String())
+ }
+ to, _ := url.Parse(start.Header().Get("Location"))
+ if !strings.HasPrefix(to.String(), idp.srv.URL+"/authorize") || to.Query().Get("code_challenge") == "" {
+ t.Fatalf("redirected to %s", to)
+ }
+ idp.nonce = to.Query().Get("nonce")
+ state := to.Query().Get("state")
+ if tamper {
+ state = "someone-elses"
+ }
+ cb := httptest.NewRequest("GET", "/login/oidc/callback?code=c1&state="+state, nil)
+ for _, c := range start.Result().Cookies() {
+ cb.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, cb)
+ return rec
+}
+
+func TestSigningInThroughAProvider(t *testing.T) {
+ idp := newFakeIdP(t)
+ st := &oidcStoreMem{users: map[string]store.User{}, roles: map[string]string{}}
+ p := NewAccountPages(sessionAccounts{}, nil, nil, "v0", slog.New(slog.NewTextHandler(io.Discard, nil)))
+ mux := http.NewServeMux()
+ if err := p.RegisterOIDC(mux, config.OIDC{Issuer: idp.srv.URL, ClientID: "llmgw", CreateAccounts: true,
+ Roles: map[string][]string{"operator": {"ops"}, "admin": {"root"}},
+ Memberships: map[string]string{"ml": "team:Acme/ml"}}, st); err != nil {
+ t.Fatal(err)
+ }
+
+ idp.claims = map[string]any{"email": "Ann@Example.com", "email_verified": true, "name": "Ann", "groups": []string{"ops", "ml"}}
+ rec := signIn(t, mux, idp, false)
+ if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/profile" {
+ t.Fatalf("callback: %d %s", rec.Code, rec.Body.String())
+ }
+ u, ok := st.users["ann@example.com"]
+ if !ok || u.State != store.UserActive || st.roles[u.ID] != "operator" || len(st.joined) != 1 || !strings.HasSuffix(st.joined[0], "team:t1") {
+ t.Errorf("account %+v roles %v joined %v", u, st.roles, st.joined)
+ }
+ if !strings.Contains(rec.Header().Get("Set-Cookie")+strings.Join(rec.Header().Values("Set-Cookie"), ";"), "sess") {
+ t.Error("no session cookie")
+ }
+
+ // Refused: a state that is not this browser's, an unverified address,
+ // and nobody the gateway knows when it does not make accounts.
+ if rec := signIn(t, mux, idp, true); rec.Code != http.StatusForbidden {
+ t.Errorf("a tampered state: %d", rec.Code)
+ }
+ idp.claims = map[string]any{"email": "bob@example.com", "email_verified": false}
+ if rec := signIn(t, mux, idp, false); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "not verified") {
+ t.Errorf("unverified: %d", rec.Code)
+ }
+ p2 := NewAccountPages(sessionAccounts{}, nil, nil, "v0", slog.New(slog.NewTextHandler(io.Discard, nil)))
+ mux2 := http.NewServeMux()
+ _ = p2.RegisterOIDC(mux2, config.OIDC{Issuer: idp.srv.URL, ClientID: "llmgw"}, st)
+ idp.claims = map[string]any{"email": "carol@example.com"}
+ if rec := signIn(t, mux2, idp, false); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), "no account for carol@example.com") {
+ t.Errorf("unknown without create_accounts: %d %s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/internal/web/templates/account.html b/internal/web/templates/account.html
index 9d023cb..550bdd1 100644
--- a/internal/web/templates/account.html
+++ b/internal/web/templates/account.html
@@ -46,6 +46,7 @@ an operator to reset it.
Password
Sign in
+{{if .SSO}}Sign in with {{.SSO}}
{{end}}
{{if .SignupOpen}}No account? Sign up .
{{end}}