Provisioning through SCIM 2.0: accounts and groups kept in step by the identity provider
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
5cff456b9b
commit
14ea59d83f
11 files changed
+829
-2
No files matched your search
+6
-1
@@ -384,7 +384,12 @@ portal is not done — the page shows; the console and ctl change.
|
||||
before/after, source) written by the `adminAction`/`tenancyAction`
|
||||
wrappers and by every admin-API mutation; roles viewer / operator /
|
||||
tenant-admin / billing; `ctl audit`. Depends on A5 for a real actor.
|
||||
2. **OIDC/SSO login (M), then SCIM (M).** `internal/account/service.go`,
|
||||
2. **Done (branch `features-c`):** OIDC sign-in (`auth.oidc`, PKCE,
|
||||
verified email, roles and memberships from groups, `no_passwords`) and
|
||||
SCIM 2.0 (`/scim/v2` Users and Groups). Left: the sign-in cookie is
|
||||
signed with a per-process key, so with two control planes behind a
|
||||
balancer the callback must reach the one that started it (sticky
|
||||
sessions) until the key comes from the store. **OIDC/SSO login (M), then SCIM (M).** `internal/account/service.go`,
|
||||
`internal/web/account.go`; map IdP groups to org/team/admin.
|
||||
3. **Service accounts and key lifecycle (S).** Per-org maximum key TTL,
|
||||
`keys rotate` with overlap, last-used shown, project-owned service keys
|
||||
|
||||
@@ -43,6 +43,12 @@ APIs change between minors without a deprecation period.
|
||||
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.
|
||||
- **Provisioning through SCIM 2.0** (`auth.scim.token_file`, `/scim/v2`).
|
||||
- **Users:** the identity provider makes, suspends and reinstates
|
||||
accounts — the PATCH forms Entra ID and Okta send are both read.
|
||||
Deleting a user suspends the account.
|
||||
- **Groups:** joining and leaving the groups `auth.oidc` maps gives and
|
||||
takes away staff roles and places in the tree.
|
||||
|
||||
### Guardrails
|
||||
|
||||
|
||||
@@ -1118,6 +1118,25 @@ How the sign-in works:
|
||||
- **Memberships:** they are added, never taken away.
|
||||
- **Audit:** each sign-in is recorded in the audit log.
|
||||
|
||||
### Provisioning (SCIM)
|
||||
|
||||
The provider can also keep accounts in step: made when someone is assigned
|
||||
the application, suspended when they are removed or leave. Give it a token:
|
||||
|
||||
```yaml
|
||||
auth:
|
||||
scim:
|
||||
token_file: /etc/llmgw/secrets/scim-token # any long random string, root-only
|
||||
```
|
||||
|
||||
and point it at `https://<gateway>/scim/v2` with that token as the bearer.
|
||||
|
||||
- **Users:** the `userName` is the email address. Deleting a user
|
||||
suspends the account, and its keys and history stay.
|
||||
- **Groups:** `auth.oidc.roles` and `memberships` are applied as people
|
||||
join and leave them. Membership in a group is removed when someone leaves
|
||||
it.
|
||||
|
||||
## The firewall
|
||||
|
||||
`server init`, `node add`, `server add` and `mirror init` each keep that
|
||||
|
||||
@@ -34,6 +34,7 @@ rather than repeated.
|
||||
| `default_tpm` | `int` | [Auth](#auth) |
|
||||
| `signup_open` | `bool` | [Auth](#auth) |
|
||||
| `oidc` | `OIDC` | [Auth](#auth) |
|
||||
| `scim` | `SCIM` | [Auth](#auth) |
|
||||
| `personal` | `Personal` | [Auth](#auth) |
|
||||
| `pricing` | `map[string]Price` | [Auth](#auth) |
|
||||
| `default_price` | `Price` | [Auth](#auth) |
|
||||
@@ -197,6 +198,7 @@ rather than repeated.
|
||||
| `injection` | `string` | [Rules](#rules) |
|
||||
| `deny` | `[]Pattern` | [Rules](#rules) |
|
||||
| `max_chars` | `int` | [Rules](#rules) |
|
||||
| `token_file` | `string` | [SCIM](#scim) |
|
||||
| `python` | `string` | [SGLangConfig](#sglangconfig) |
|
||||
| `ttft_p99` | `time.Duration` | [SLO](#slo) |
|
||||
| `tpot_p99` | `time.Duration` | [SLO](#slo) |
|
||||
@@ -433,6 +435,14 @@ OIDC is sign-in through an identity provider.
|
||||
|
||||
Takes a [OIDC](#oidc) block.
|
||||
|
||||
### `scim`
|
||||
|
||||
`SCIM`
|
||||
|
||||
SCIM is account provisioning by the identity provider.
|
||||
|
||||
Takes a [SCIM](#scim) block.
|
||||
|
||||
### `personal`
|
||||
|
||||
`Personal`
|
||||
@@ -1591,6 +1601,15 @@ Deny are patterns, matched against the text as a model reads it.
|
||||
|
||||
MaxChars refuses text longer than this; zero is no limit.
|
||||
|
||||
## SCIM
|
||||
|
||||
### `token_file`
|
||||
|
||||
`string`
|
||||
|
||||
TokenFile holds the bearer token the provider sends. Empty turns
|
||||
provisioning off.
|
||||
|
||||
## SGLangConfig
|
||||
|
||||
### `python`
|
||||
|
||||
@@ -292,6 +292,8 @@ type Auth struct {
|
||||
|
||||
// OIDC is sign-in through an identity provider.
|
||||
OIDC OIDC `koanf:"oidc"`
|
||||
// SCIM is account provisioning by the identity provider.
|
||||
SCIM SCIM `koanf:"scim"`
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -86,3 +86,12 @@ func (o OIDC) Validate() error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SCIM lets an identity provider provision accounts (/scim/v2): made,
|
||||
// suspended and reinstated as they are there, with groups mapped by
|
||||
// auth.oidc's roles and memberships.
|
||||
type SCIM struct {
|
||||
// TokenFile holds the bearer token the provider sends. Empty turns
|
||||
// provisioning off.
|
||||
TokenFile string `koanf:"token_file"`
|
||||
}
|
||||
@@ -28,6 +28,7 @@ var Reference = []Block{
|
||||
{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: "scim", Type: "SCIM", Doc: "SCIM is account provisioning by the identity provider.", Nested: "config.SCIM"},
|
||||
{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"},
|
||||
@@ -240,6 +241,9 @@ var Reference = []Block{
|
||||
{Key: "deny", Type: "[]Pattern", Doc: "Deny are patterns, matched against the text as a model reads it.", Nested: ""},
|
||||
{Key: "max_chars", Type: "int", Doc: "MaxChars refuses text longer than this; zero is no limit.", Nested: ""},
|
||||
}},
|
||||
{Package: "config", Name: "SCIM", Title: "SCIM", Doc: "", Fields: []Field{
|
||||
{Key: "token_file", Type: "string", Doc: "TokenFile holds the bearer token the provider sends. Empty turns\nprovisioning off.", Nested: ""},
|
||||
}},
|
||||
{Package: "engines", Name: "SGLangConfig", Title: "SGLangConfig", Doc: "", Fields: []Field{
|
||||
{Key: "python", Type: "string", Doc: "Python is the interpreter of the SGLang virtualenv. SGLang is launched as\na module rather than a console script, which is the documented entry\npoint and avoids depending on the script being on PATH.", Nested: ""},
|
||||
}},
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -21,6 +22,7 @@ import (
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/accounting"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/auth"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/guard"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/scim"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/router/admission"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/router/proxy"
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
@@ -187,6 +189,14 @@ func (r *Router) Handler() http.Handler {
|
||||
r.log.Error("single sign-on is off", "err", err)
|
||||
}
|
||||
}
|
||||
if r.scim.TokenFile != "" {
|
||||
if b, err := os.ReadFile(r.scim.TokenFile); err != nil || strings.TrimSpace(string(b)) == "" {
|
||||
r.log.Error("provisioning (SCIM) is off: its token cannot be read", "file", r.scim.TokenFile, "err", err)
|
||||
} else {
|
||||
scim.New(r.store, strings.TrimSpace(string(b)),
|
||||
scim.Mapping{Roles: r.oidc.Roles, Memberships: r.oidc.Memberships}, r.log).Register(mux)
|
||||
}
|
||||
}
|
||||
}
|
||||
if pol, ok := r.guard.(interface {
|
||||
Policy(guard.Subject) (guard.Policy, string)
|
||||
|
||||
@@ -93,8 +93,10 @@ 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 is sign-in through an identity provider, and scim provisioning
|
||||
// by it.
|
||||
oidc config.OIDC
|
||||
scim config.SCIM
|
||||
|
||||
// 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
|
||||
@@ -281,6 +283,7 @@ func New(cfg config.Server, log *slog.Logger) (*Router, error) {
|
||||
st.SetPersonalDefaults(personalLimits(cfg.Auth.Personal))
|
||||
r.personalOff = cfg.Auth.Personal.Disabled
|
||||
r.oidc = cfg.Auth.OIDC
|
||||
r.scim = cfg.Auth.SCIM
|
||||
r.personalDefaults = personalLimits(cfg.Auth.Personal)
|
||||
r.llamaVersion = cfg.WantedEngines()["llamacpp"]
|
||||
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
// Package scim lets an identity provider keep the gateway's accounts in
|
||||
// step with its own (SCIM 2.0, RFC 7643/7644): people made, renamed,
|
||||
// suspended and reinstated as they are there, and the groups that give
|
||||
// staff roles and places in the tree followed as people join and leave them.
|
||||
//
|
||||
// What it takes of SCIM is what Entra ID, Okta and Keycloak send: Users by
|
||||
// userName (the email address), active, name; Groups by displayName, their
|
||||
// members changed with PATCH. Deleting a user suspends the account: its keys,
|
||||
// usage and history stay, and reinstating it gives it all back.
|
||||
package scim
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base32"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
)
|
||||
|
||||
// Store is what provisioning needs.
|
||||
type Store interface {
|
||||
Users(ctx context.Context, state store.UserState) ([]store.User, error)
|
||||
UserByID(ctx context.Context, id string) (store.User, error)
|
||||
UserByEmail(ctx context.Context, email string) (store.User, error)
|
||||
CreateUser(ctx context.Context, u store.User) error
|
||||
SetUserState(ctx context.Context, id string, state store.UserState) error
|
||||
DeleteUserSessions(ctx context.Context, userID string) 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
|
||||
RemoveMembership(ctx context.Context, user string, scope store.Scope, id string, at time.Time) (int, error)
|
||||
AllOrgs(ctx context.Context) ([]store.Org, error)
|
||||
AllTeams(ctx context.Context) ([]store.TeamPath, error)
|
||||
AllProjects(ctx context.Context) ([]store.ProjectPath, error)
|
||||
}
|
||||
|
||||
// Mapping says what a group stands for: staff roles by group, and places in
|
||||
// the tree by group — the same as single sign-on's.
|
||||
type Mapping struct {
|
||||
Roles map[string][]string
|
||||
Memberships map[string]string
|
||||
}
|
||||
|
||||
// Server answers /scim/v2.
|
||||
type Server struct {
|
||||
st Store
|
||||
token string
|
||||
m Mapping
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// New builds the server. token is what the provider sends as its bearer.
|
||||
func New(st Store, token string, m Mapping, log *slog.Logger) *Server {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
return &Server{st: st, token: token, m: m, log: log}
|
||||
}
|
||||
|
||||
const (
|
||||
userSchema = "urn:ietf:params:scim:schemas:core:2.0:User"
|
||||
groupSchema = "urn:ietf:params:scim:schemas:core:2.0:Group"
|
||||
listSchema = "urn:ietf:params:scim:api:messages:2.0:ListResponse"
|
||||
errSchema = "urn:ietf:params:scim:api:messages:2.0:Error"
|
||||
patchSchema = "urn:ietf:params:scim:api:messages:2.0:PatchOp"
|
||||
)
|
||||
|
||||
// Register mounts the endpoints.
|
||||
func (s *Server) Register(mux *http.ServeMux) {
|
||||
h := func(f http.HandlerFunc) http.HandlerFunc { return s.authed(f) }
|
||||
mux.HandleFunc("GET /scim/v2/ServiceProviderConfig", h(s.config))
|
||||
mux.HandleFunc("GET /scim/v2/Users", h(s.listUsers))
|
||||
mux.HandleFunc("POST /scim/v2/Users", h(s.createUser))
|
||||
mux.HandleFunc("GET /scim/v2/Users/{id}", h(s.getUser))
|
||||
mux.HandleFunc("PUT /scim/v2/Users/{id}", h(s.replaceUser))
|
||||
mux.HandleFunc("PATCH /scim/v2/Users/{id}", h(s.patchUser))
|
||||
mux.HandleFunc("DELETE /scim/v2/Users/{id}", h(s.deleteUser))
|
||||
mux.HandleFunc("GET /scim/v2/Groups", h(s.listGroups))
|
||||
mux.HandleFunc("POST /scim/v2/Groups", h(s.createGroup))
|
||||
mux.HandleFunc("GET /scim/v2/Groups/{id}", h(s.getGroup))
|
||||
mux.HandleFunc("PATCH /scim/v2/Groups/{id}", h(s.patchGroup))
|
||||
mux.HandleFunc("PUT /scim/v2/Groups/{id}", h(s.replaceGroup))
|
||||
mux.HandleFunc("DELETE /scim/v2/Groups/{id}", h(s.deleteGroup))
|
||||
}
|
||||
|
||||
func (s *Server) authed(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
got, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if !ok || s.token == "" || subtle.ConstantTimeCompare([]byte(strings.TrimSpace(got)), []byte(s.token)) != 1 {
|
||||
fail(w, http.StatusUnauthorized, "", "a bearer token is required")
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func write(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/scim+json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, code int, scimType, detail string) {
|
||||
e := map[string]any{"schemas": []string{errSchema}, "status": strconv.Itoa(code), "detail": detail}
|
||||
if scimType != "" {
|
||||
e["scimType"] = scimType
|
||||
}
|
||||
write(w, code, e)
|
||||
}
|
||||
|
||||
func (s *Server) config(w http.ResponseWriter, _ *http.Request) {
|
||||
write(w, http.StatusOK, map[string]any{
|
||||
"schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"},
|
||||
"patch": map[string]bool{"supported": true}, "bulk": map[string]any{"supported": false},
|
||||
"filter": map[string]any{"supported": true, "maxResults": 1000}, "changePassword": map[string]bool{"supported": false},
|
||||
"sort": map[string]bool{"supported": false}, "etag": map[string]bool{"supported": false},
|
||||
"authenticationSchemes": []map[string]string{{"type": "oauthbearertoken", "name": "Bearer token"}},
|
||||
})
|
||||
}
|
||||
|
||||
// --- users ---
|
||||
|
||||
type userIn struct {
|
||||
UserName string `json:"userName"`
|
||||
Name struct {
|
||||
Formatted string `json:"formatted"`
|
||||
GivenName string `json:"givenName"`
|
||||
FamilyName string `json:"familyName"`
|
||||
} `json:"name"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Emails []struct {
|
||||
Value string `json:"value"`
|
||||
Primary bool `json:"primary"`
|
||||
} `json:"emails"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
|
||||
func (u userIn) email() string {
|
||||
e := u.UserName
|
||||
if !strings.Contains(e, "@") {
|
||||
for _, m := range u.Emails {
|
||||
if m.Primary || e == "" || !strings.Contains(e, "@") {
|
||||
e = m.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
return store.NormalizeEmail(e)
|
||||
}
|
||||
|
||||
func (u userIn) name() string {
|
||||
switch {
|
||||
case u.Name.Formatted != "":
|
||||
return u.Name.Formatted
|
||||
case u.DisplayName != "":
|
||||
return u.DisplayName
|
||||
case u.Name.GivenName != "" || u.Name.FamilyName != "":
|
||||
return strings.TrimSpace(u.Name.GivenName + " " + u.Name.FamilyName)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func userOut(u store.User) map[string]any {
|
||||
return map[string]any{
|
||||
"schemas": []string{userSchema}, "id": u.ID, "userName": u.Email,
|
||||
"name": map[string]string{"formatted": u.Name},
|
||||
"emails": []map[string]any{{"value": u.Email, "primary": true}},
|
||||
"active": u.State == store.UserActive,
|
||||
"meta": map[string]any{"resourceType": "User", "created": u.CreatedAt.UTC().Format(time.RFC3339)},
|
||||
}
|
||||
}
|
||||
|
||||
var userNameEq = regexp.MustCompile(`(?i)^\s*userName\s+eq\s+"([^"]*)"\s*$`)
|
||||
|
||||
func page(r *http.Request, n int) (int, int) {
|
||||
start, _ := strconv.Atoi(r.URL.Query().Get("startIndex"))
|
||||
if start < 1 {
|
||||
start = 1
|
||||
}
|
||||
count, err := strconv.Atoi(r.URL.Query().Get("count"))
|
||||
if err != nil || count < 0 {
|
||||
count = 100
|
||||
}
|
||||
if start-1 > n {
|
||||
start = n + 1
|
||||
}
|
||||
return start, min(count, n-(start-1))
|
||||
}
|
||||
|
||||
func (s *Server) listUsers(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
var users []store.User
|
||||
if f := r.URL.Query().Get("filter"); f != "" {
|
||||
m := userNameEq.FindStringSubmatch(f)
|
||||
if m == nil {
|
||||
fail(w, http.StatusBadRequest, "invalidFilter", `only userName eq "…" is supported`)
|
||||
return
|
||||
}
|
||||
u, err := s.st.UserByEmail(ctx, store.NormalizeEmail(m[1]))
|
||||
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
users = []store.User{u}
|
||||
}
|
||||
} else {
|
||||
all, err := s.st.Users(ctx, "")
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
users = all
|
||||
}
|
||||
start, count := page(r, len(users))
|
||||
res := []map[string]any{}
|
||||
for _, u := range users[start-1 : start-1+count] {
|
||||
res = append(res, userOut(u))
|
||||
}
|
||||
write(w, http.StatusOK, map[string]any{"schemas": []string{listSchema}, "totalResults": len(users),
|
||||
"startIndex": start, "itemsPerPage": len(res), "Resources": res})
|
||||
}
|
||||
|
||||
func (s *Server) getUser(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.st.UserByID(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "", "no such user")
|
||||
return
|
||||
}
|
||||
write(w, http.StatusOK, userOut(u))
|
||||
}
|
||||
|
||||
func decode(r *http.Request, v any) error {
|
||||
return json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
var b [10]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return "usr-" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(b[:]))
|
||||
}
|
||||
|
||||
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var in userIn
|
||||
if err := decode(r, &in); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", err.Error())
|
||||
return
|
||||
}
|
||||
email := in.email()
|
||||
if !strings.Contains(email, "@") {
|
||||
fail(w, http.StatusBadRequest, "invalidValue", "userName or an email must be an email address")
|
||||
return
|
||||
}
|
||||
if _, err := s.st.UserByEmail(r.Context(), email); err == nil {
|
||||
fail(w, http.StatusConflict, "uniqueness", email+" already has an account")
|
||||
return
|
||||
}
|
||||
u := store.User{ID: newID(), Email: email, Name: or(in.name(), email),
|
||||
// No password works: the provider signs this account in.
|
||||
PasswordHash: "!scim", State: store.UserActive, CreatedAt: time.Now()}
|
||||
if in.Active != nil && !*in.Active {
|
||||
u.State = store.UserSuspended
|
||||
}
|
||||
if err := s.st.CreateUser(r.Context(), u); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
s.log.Info("an account was provisioned by the identity provider", "email", email)
|
||||
write(w, http.StatusCreated, userOut(u))
|
||||
}
|
||||
|
||||
// setActive suspends or reinstates; a suspended account's sessions close.
|
||||
func (s *Server) setActive(ctx context.Context, u *store.User, active bool) error {
|
||||
want := store.UserActive
|
||||
if !active {
|
||||
want = store.UserSuspended
|
||||
}
|
||||
if u.State == want {
|
||||
return nil
|
||||
}
|
||||
if err := s.st.SetUserState(ctx, u.ID, want); err != nil {
|
||||
return err
|
||||
}
|
||||
if !active {
|
||||
if err := s.st.DeleteUserSessions(ctx, u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
u.State = want
|
||||
s.log.Info("the identity provider changed an account", "email", u.Email, "state", want)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) replaceUser(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.st.UserByID(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "", "no such user")
|
||||
return
|
||||
}
|
||||
var in userIn
|
||||
if err := decode(r, &in); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", err.Error())
|
||||
return
|
||||
}
|
||||
if in.Active != nil {
|
||||
if err := s.setActive(r.Context(), &u, *in.Active); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
write(w, http.StatusOK, userOut(u))
|
||||
}
|
||||
|
||||
type patchOp struct {
|
||||
Op string `json:"op"`
|
||||
Path string `json:"path"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
}
|
||||
|
||||
func (s *Server) patchUser(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.st.UserByID(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "", "no such user")
|
||||
return
|
||||
}
|
||||
var in struct{ Operations []patchOp }
|
||||
if err := decode(r, &in); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", err.Error())
|
||||
return
|
||||
}
|
||||
for _, op := range in.Operations {
|
||||
if active, ok := activeOf(op); ok {
|
||||
if err := s.setActive(r.Context(), &u, active); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
write(w, http.StatusOK, userOut(u))
|
||||
}
|
||||
|
||||
// activeOf reads "active" from an operation, written either way providers
|
||||
// write it: {path: active, value: false} or {value: {active: false}}, the
|
||||
// value a bool or the string "False".
|
||||
func activeOf(op patchOp) (bool, bool) {
|
||||
if !strings.EqualFold(op.Op, "replace") && !strings.EqualFold(op.Op, "add") {
|
||||
return false, false
|
||||
}
|
||||
raw := op.Value
|
||||
if !strings.EqualFold(op.Path, "active") {
|
||||
var v map[string]json.RawMessage
|
||||
if json.Unmarshal(op.Value, &v) != nil {
|
||||
return false, false
|
||||
}
|
||||
var ok bool
|
||||
if raw, ok = v["active"]; !ok {
|
||||
return false, false
|
||||
}
|
||||
}
|
||||
var b bool
|
||||
if json.Unmarshal(raw, &b) == nil {
|
||||
return b, true
|
||||
}
|
||||
var str string
|
||||
if json.Unmarshal(raw, &str) == nil {
|
||||
if v, err := strconv.ParseBool(str); err == nil {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return false, false
|
||||
}
|
||||
|
||||
func (s *Server) deleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
u, err := s.st.UserByID(r.Context(), r.PathValue("id"))
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "", "no such user")
|
||||
return
|
||||
}
|
||||
if err := s.setActive(r.Context(), &u, false); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "", err.Error())
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- groups ---
|
||||
|
||||
// groups are the names the mapping knows, which are the only groups that
|
||||
// mean anything here.
|
||||
func (s *Server) groups() []string {
|
||||
seen := map[string]bool{}
|
||||
for _, gs := range s.m.Roles {
|
||||
for _, g := range gs {
|
||||
seen[g] = true
|
||||
}
|
||||
}
|
||||
for g := range s.m.Memberships {
|
||||
seen[g] = true
|
||||
}
|
||||
out := make([]string, 0, len(seen))
|
||||
for g := range seen {
|
||||
out = append(out, g)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func groupOut(name string) map[string]any {
|
||||
return map[string]any{"schemas": []string{groupSchema}, "id": name, "displayName": name,
|
||||
"meta": map[string]string{"resourceType": "Group"}}
|
||||
}
|
||||
|
||||
func (s *Server) listGroups(w http.ResponseWriter, r *http.Request) {
|
||||
names := s.groups()
|
||||
if f := r.URL.Query().Get("filter"); f != "" {
|
||||
m := regexp.MustCompile(`(?i)^\s*displayName\s+eq\s+"([^"]*)"\s*$`).FindStringSubmatch(f)
|
||||
if m == nil {
|
||||
fail(w, http.StatusBadRequest, "invalidFilter", `only displayName eq "…" is supported`)
|
||||
return
|
||||
}
|
||||
names = slices.DeleteFunc(names, func(n string) bool { return n != m[1] })
|
||||
}
|
||||
res := []map[string]any{}
|
||||
for _, n := range names {
|
||||
res = append(res, groupOut(n))
|
||||
}
|
||||
write(w, http.StatusOK, map[string]any{"schemas": []string{listSchema}, "totalResults": len(res),
|
||||
"startIndex": 1, "itemsPerPage": len(res), "Resources": res})
|
||||
}
|
||||
|
||||
func (s *Server) getGroup(w http.ResponseWriter, r *http.Request) {
|
||||
if !slices.Contains(s.groups(), r.PathValue("id")) {
|
||||
fail(w, http.StatusNotFound, "", "no such group: map it under auth.oidc roles or memberships")
|
||||
return
|
||||
}
|
||||
write(w, http.StatusOK, groupOut(r.PathValue("id")))
|
||||
}
|
||||
|
||||
type groupIn struct {
|
||||
DisplayName string `json:"displayName"`
|
||||
Members []struct {
|
||||
Value string `json:"value"`
|
||||
} `json:"members"`
|
||||
}
|
||||
|
||||
// createGroup answers a provider pushing a group: one the mapping knows is
|
||||
// followed from now on, its members joined; any other is acknowledged and
|
||||
// means nothing here.
|
||||
func (s *Server) createGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var in groupIn
|
||||
if err := decode(r, &in); err != nil || in.DisplayName == "" {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", "a group needs a displayName")
|
||||
return
|
||||
}
|
||||
for _, m := range in.Members {
|
||||
s.member(r.Context(), in.DisplayName, m.Value, true)
|
||||
}
|
||||
write(w, http.StatusCreated, groupOut(in.DisplayName))
|
||||
}
|
||||
|
||||
func (s *Server) replaceGroup(w http.ResponseWriter, r *http.Request) {
|
||||
var in groupIn
|
||||
if err := decode(r, &in); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", err.Error())
|
||||
return
|
||||
}
|
||||
for _, m := range in.Members {
|
||||
s.member(r.Context(), r.PathValue("id"), m.Value, true)
|
||||
}
|
||||
write(w, http.StatusOK, groupOut(r.PathValue("id")))
|
||||
}
|
||||
|
||||
func (s *Server) patchGroup(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("id")
|
||||
var in struct{ Operations []patchOp }
|
||||
if err := decode(r, &in); err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalidSyntax", err.Error())
|
||||
return
|
||||
}
|
||||
for _, op := range in.Operations {
|
||||
add := strings.EqualFold(op.Op, "add") || strings.EqualFold(op.Op, "replace")
|
||||
remove := strings.EqualFold(op.Op, "remove")
|
||||
var members []struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
_ = json.Unmarshal(op.Value, &members)
|
||||
// remove with a path: members[value eq "id"]
|
||||
if remove && len(members) == 0 {
|
||||
if m := regexp.MustCompile(`value eq "([^"]+)"`).FindStringSubmatch(op.Path); m != nil {
|
||||
members = append(members, struct {
|
||||
Value string `json:"value"`
|
||||
}{m[1]})
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(strings.ToLower(op.Path), "members") && op.Path != "" {
|
||||
continue
|
||||
}
|
||||
for _, m := range members {
|
||||
if add || remove {
|
||||
s.member(r.Context(), name, m.Value, add)
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) deleteGroup(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// member applies a person joining or leaving a group: the staff role it
|
||||
// gives, and the place in the tree.
|
||||
func (s *Server) member(ctx context.Context, group, userID string, joined bool) {
|
||||
u, err := s.st.UserByID(ctx, userID)
|
||||
if err != nil {
|
||||
s.log.Warn("a group change names a user the gateway does not have", "group", group, "user", userID)
|
||||
return
|
||||
}
|
||||
for _, role := range []string{store.RoleAdmin, store.RoleOperator, store.RoleBilling, store.RoleViewer} {
|
||||
if !slices.Contains(s.m.Roles[role], group) {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case joined && roleRank(role) > roleRank(u.StaffRole()):
|
||||
_ = s.st.SetStaffRole(ctx, u.ID, role)
|
||||
case !joined && u.StaffRole() == role:
|
||||
_ = s.st.SetStaffRole(ctx, u.ID, "")
|
||||
}
|
||||
}
|
||||
where, ok := s.m.Memberships[group]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
scope, id, err := s.place(ctx, where)
|
||||
if err != nil {
|
||||
s.log.Warn("a group maps to a place the tree does not have", "group", group, "place", where, "err", err)
|
||||
return
|
||||
}
|
||||
if joined {
|
||||
err = s.st.AddMembership(ctx, u.ID, scope, id, store.RoleMember, "scim", time.Now())
|
||||
} else {
|
||||
_, err = s.st.RemoveMembership(ctx, u.ID, scope, id, time.Now())
|
||||
}
|
||||
if err != nil {
|
||||
s.log.Warn("a group's membership could not be applied", "group", group, "user", u.Email, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func roleRank(r string) int {
|
||||
return map[string]int{store.RoleViewer: 1, store.RoleBilling: 2, store.RoleOperator: 3, store.RoleAdmin: 4}[r]
|
||||
}
|
||||
|
||||
func (s *Server) place(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 := s.st.AllOrgs(ctx)
|
||||
for _, o := range orgs {
|
||||
if same(o.Name) {
|
||||
return store.ScopeOrg, o.ID, nil
|
||||
}
|
||||
}
|
||||
return "", "", errors.Join(err, fmt.Errorf("no organization %s", path))
|
||||
case "team":
|
||||
teams, err := s.st.AllTeams(ctx)
|
||||
for _, t := range teams {
|
||||
if same(t.OrgName + "/" + t.Name) {
|
||||
return store.ScopeTeam, t.ID, nil
|
||||
}
|
||||
}
|
||||
return "", "", errors.Join(err, fmt.Errorf("no team %s", path))
|
||||
default:
|
||||
projects, err := s.st.AllProjects(ctx)
|
||||
for _, p := range projects {
|
||||
if same(p.Path) {
|
||||
return store.ScopeProject, p.ID, nil
|
||||
}
|
||||
}
|
||||
return "", "", errors.Join(err, fmt.Errorf("no project %s", path))
|
||||
}
|
||||
}
|
||||
|
||||
func or(s, def string) string {
|
||||
if s == "" {
|
||||
return def
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package scim
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
|
||||
)
|
||||
|
||||
type mem struct {
|
||||
users map[string]store.User
|
||||
sessions map[string]bool
|
||||
roles map[string]string
|
||||
members map[string]bool
|
||||
}
|
||||
|
||||
func newMem() *mem {
|
||||
return &mem{users: map[string]store.User{}, sessions: map[string]bool{}, roles: map[string]string{}, members: map[string]bool{}}
|
||||
}
|
||||
|
||||
func (m *mem) Users(context.Context, store.UserState) ([]store.User, error) {
|
||||
var out []store.User
|
||||
for _, u := range m.users {
|
||||
out = append(out, u)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (m *mem) UserByID(_ context.Context, id string) (store.User, error) {
|
||||
if u, ok := m.users[id]; ok {
|
||||
u.Role = m.roles[id]
|
||||
return u, nil
|
||||
}
|
||||
return store.User{}, store.ErrNotFound
|
||||
}
|
||||
func (m *mem) UserByEmail(_ context.Context, e string) (store.User, error) {
|
||||
for _, u := range m.users {
|
||||
if u.Email == e {
|
||||
return u, nil
|
||||
}
|
||||
}
|
||||
return store.User{}, store.ErrNotFound
|
||||
}
|
||||
func (m *mem) CreateUser(_ context.Context, u store.User) error { m.users[u.ID] = u; return nil }
|
||||
func (m *mem) SetUserState(_ context.Context, id string, s store.UserState) error {
|
||||
u := m.users[id]
|
||||
u.State = s
|
||||
m.users[id] = u
|
||||
return nil
|
||||
}
|
||||
func (m *mem) DeleteUserSessions(_ context.Context, id string) error {
|
||||
delete(m.sessions, id)
|
||||
return nil
|
||||
}
|
||||
func (m *mem) SetStaffRole(_ context.Context, id, role string) error { m.roles[id] = role; return nil }
|
||||
func (m *mem) AddMembership(_ context.Context, u string, sc store.Scope, id, _, _ string, _ time.Time) error {
|
||||
m.members[u+"@"+string(sc)+":"+id] = true
|
||||
return nil
|
||||
}
|
||||
func (m *mem) RemoveMembership(_ context.Context, u string, sc store.Scope, id string, _ time.Time) (int, error) {
|
||||
delete(m.members, u+"@"+string(sc)+":"+id)
|
||||
return 1, nil
|
||||
}
|
||||
func (m *mem) AllOrgs(context.Context) ([]store.Org, error) { return nil, nil }
|
||||
func (m *mem) AllTeams(context.Context) ([]store.TeamPath, error) {
|
||||
return []store.TeamPath{{ID: "t1", Name: "ml", OrgName: "Acme"}}, nil
|
||||
}
|
||||
func (m *mem) AllProjects(context.Context) ([]store.ProjectPath, error) { return nil, nil }
|
||||
|
||||
func server(t *testing.T) (*mem, http.Handler) {
|
||||
st := newMem()
|
||||
mux := http.NewServeMux()
|
||||
New(st, "s3cret", Mapping{Roles: map[string][]string{"operator": {"ops"}},
|
||||
Memberships: map[string]string{"ml": "team:Acme/ml"}}, slog.New(slog.DiscardHandler)).Register(mux)
|
||||
return st, mux
|
||||
}
|
||||
|
||||
func do(t *testing.T, h http.Handler, method, path, body string) (*httptest.ResponseRecorder, map[string]any) {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
r.Header.Set("Authorization", "Bearer s3cret")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
return rec, out
|
||||
}
|
||||
|
||||
func TestAProviderProvisionsAndSuspendsAccounts(t *testing.T) {
|
||||
st, h := server(t)
|
||||
|
||||
r := httptest.NewRequest("GET", "/scim/v2/Users", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != 401 {
|
||||
t.Errorf("no token: %d", rec.Code)
|
||||
}
|
||||
|
||||
rec, u := do(t, h, "POST", "/scim/v2/Users", `{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
|
||||
"userName":"Ann@Example.com","name":{"givenName":"Ann","familyName":"Lee"},"active":true}`)
|
||||
if rec.Code != 201 || u["userName"] != "ann@example.com" || u["active"] != true {
|
||||
t.Fatalf("create: %d %v", rec.Code, u)
|
||||
}
|
||||
id := u["id"].(string)
|
||||
if st.users[id].Name != "Ann Lee" || st.users[id].PasswordHash != "!scim" {
|
||||
t.Errorf("stored %+v", st.users[id])
|
||||
}
|
||||
if rec, _ := do(t, h, "POST", "/scim/v2/Users", `{"userName":"ann@example.com"}`); rec.Code != 409 {
|
||||
t.Errorf("again: %d", rec.Code)
|
||||
}
|
||||
if _, l := do(t, h, "GET", `/scim/v2/Users?filter=userName+eq+%22ANN@example.com%22`, ""); l["totalResults"] != float64(1) {
|
||||
t.Errorf("filter: %v", l)
|
||||
}
|
||||
|
||||
// Entra writes {op: Replace, path: active, value: "False"}; Okta {op:
|
||||
// replace, value: {active: false}}.
|
||||
st.sessions[id] = true
|
||||
do(t, h, "PATCH", "/scim/v2/Users/"+id, `{"Operations":[{"op":"Replace","path":"active","value":"False"}]}`)
|
||||
if st.users[id].State != store.UserSuspended || st.sessions[id] {
|
||||
t.Errorf("suspend: %+v sessions %v", st.users[id], st.sessions[id])
|
||||
}
|
||||
do(t, h, "PATCH", "/scim/v2/Users/"+id, `{"Operations":[{"op":"replace","value":{"active":true}}]}`)
|
||||
if st.users[id].State != store.UserActive {
|
||||
t.Errorf("reinstate: %+v", st.users[id])
|
||||
}
|
||||
if rec, _ := do(t, h, "DELETE", "/scim/v2/Users/"+id, ""); rec.Code != 204 || st.users[id].State != store.UserSuspended {
|
||||
t.Errorf("delete is suspend: %d %+v", rec.Code, st.users[id])
|
||||
}
|
||||
|
||||
// Groups the mapping knows give roles and places.
|
||||
do(t, h, "PATCH", "/scim/v2/Users/"+id, `{"Operations":[{"op":"replace","value":{"active":true}}]}`)
|
||||
do(t, h, "PATCH", "/scim/v2/Groups/ops", `{"Operations":[{"op":"add","path":"members","value":[{"value":"`+id+`"}]}]}`)
|
||||
do(t, h, "PATCH", "/scim/v2/Groups/ml", `{"Operations":[{"op":"add","path":"members","value":[{"value":"`+id+`"}]}]}`)
|
||||
if st.roles[id] != "operator" || !st.members[id+"@team:t1"] {
|
||||
t.Errorf("roles %v members %v", st.roles, st.members)
|
||||
}
|
||||
do(t, h, "PATCH", "/scim/v2/Groups/ml", `{"Operations":[{"op":"remove","path":"members[value eq \"`+id+`\"]"}]}`)
|
||||
do(t, h, "PATCH", "/scim/v2/Groups/ops", `{"Operations":[{"op":"remove","path":"members","value":[{"value":"`+id+`"}]}]}`)
|
||||
if st.roles[id] != "" || st.members[id+"@team:t1"] {
|
||||
t.Errorf("after leaving: roles %v members %v", st.roles, st.members)
|
||||
}
|
||||
if _, l := do(t, h, "GET", "/scim/v2/Groups", ""); l["totalResults"] != float64(2) {
|
||||
t.Errorf("groups: %v", l)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user