yaiam: web sign-in (Web) and admin API reads (Admin)
Web signs the users of a web application in with the code flow and PKCE: state, nonce and verifier in a short-lived __Host- cookie, the ID token checked per OIDC Core 3.1.3.7, profile, groups and roles from UserInfo, and the RP-initiated logout URL. Admin reads users, groups and group members from yaiam's admin API with a client credentials token. Toolchain go1.27.4. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4bff8798e5
commit
a3e8f9bb3b
10 files changed
+1183
-16
No files matched your search
+198
@@ -0,0 +1,198 @@
|
||||
package yaiam
|
||||
|
||||
// Reading a tenant's users and groups from yaiam's admin API, as a
|
||||
// service: a confidential service client of yaiam (its service account
|
||||
// holds yaiam.user.read and yaiam.group.read; the client's tokens have
|
||||
// the admin API as their audience) gets a token with the client
|
||||
// credentials grant and asks /api/v1/tenants/<tenant>/... with it. For
|
||||
// an application that wants to know users before they sign in, or the
|
||||
// members of a group; whoever signs in brings their own groups
|
||||
// (SignedIn).
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// maxList bounds an answer of the admin API: its lists come whole (no
|
||||
// paging) -- some 100 000 users.
|
||||
const maxList = 64 << 20
|
||||
|
||||
// Admin reads from yaiam's admin API. Its fields must not change once it
|
||||
// is in use; use it by pointer; it is safe for concurrent use.
|
||||
type Admin struct {
|
||||
// Client holds the issuer (the tenant's, whose token endpoint gives
|
||||
// the token), the service client's ID and the HTTP client.
|
||||
Client
|
||||
// ClientSecret is the service client's secret.
|
||||
ClientSecret string
|
||||
// API is the admin API, e.g. "https://admin.example.org/api/v1"
|
||||
// (yaiam-web; https, or http on a loopback host).
|
||||
API string
|
||||
// Tenant is the tenant's slug; its token works only there.
|
||||
Tenant string
|
||||
|
||||
tokMu sync.Mutex
|
||||
tok *Token
|
||||
}
|
||||
|
||||
// Member is a user of the tenant as the admin API lists them.
|
||||
type Member struct {
|
||||
ID string `json:"id"`
|
||||
Ref string `json:"ref"` // the name, or "home/name" for a member from another tenant
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
State string `json:"user_state"`
|
||||
Home bool `json:"home"`
|
||||
}
|
||||
|
||||
// Group is a group of the tenant.
|
||||
type Group struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Protected bool `json:"protected"`
|
||||
}
|
||||
|
||||
// User is one user in full.
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
Locale string `json:"locale"`
|
||||
TimeZone string `json:"time_zone"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// Users lists the tenant's users.
|
||||
func (a *Admin) Users(ctx context.Context) ([]Member, error) {
|
||||
var out struct {
|
||||
Items []Member `json:"items"`
|
||||
}
|
||||
return out.Items, a.get(ctx, "users", &out)
|
||||
}
|
||||
|
||||
// User returns the user named name.
|
||||
func (a *Admin) User(ctx context.Context, name string) (*User, error) {
|
||||
var u User
|
||||
if err := a.get(ctx, "users/"+url.PathEscape(name), &u); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// Groups lists the tenant's groups.
|
||||
func (a *Admin) Groups(ctx context.Context) ([]Group, error) {
|
||||
var out struct {
|
||||
Items []Group `json:"items"`
|
||||
}
|
||||
return out.Items, a.get(ctx, "groups", &out)
|
||||
}
|
||||
|
||||
// GroupMembers lists the direct members of the group name.
|
||||
func (a *Admin) GroupMembers(ctx context.Context, name string) ([]Member, error) {
|
||||
var out struct {
|
||||
Items []Member `json:"items"`
|
||||
}
|
||||
return out.Items, a.get(ctx, "groups/"+url.PathEscape(name)+"/members", &out)
|
||||
}
|
||||
|
||||
// token is a service token from the client credentials grant, kept until
|
||||
// a minute before it runs out.
|
||||
func (a *Admin) token(ctx context.Context) (string, error) {
|
||||
a.tokMu.Lock()
|
||||
defer a.tokMu.Unlock()
|
||||
if a.tok != nil && time.Until(a.tok.Expiry) > leeway {
|
||||
return a.tok.AccessToken, nil
|
||||
}
|
||||
m, err := a.discover(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.TokenEndpoint, strings.NewReader(url.Values{"grant_type": {"client_credentials"}}.Encode()))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.SetBasicAuth(url.QueryEscape(a.ClientID), url.QueryEscape(a.ClientSecret))
|
||||
status, body, err := a.do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("yaiam: token: %w", err)
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
return "", oauthError("token", status, body)
|
||||
}
|
||||
var out struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &out); err != nil {
|
||||
return "", fmt.Errorf("yaiam: token: %w", err)
|
||||
}
|
||||
if out.AccessToken == "" || !strings.EqualFold(out.TokenType, "Bearer") || out.ExpiresIn <= 0 {
|
||||
return "", errors.New("yaiam: token: no bearer token with a lifetime in the answer")
|
||||
}
|
||||
a.tok = &Token{Issuer: a.Issuer, ClientID: a.ClientID, AccessToken: out.AccessToken,
|
||||
Expiry: time.Now().Add(time.Duration(out.ExpiresIn) * time.Second)}
|
||||
return out.AccessToken, nil
|
||||
}
|
||||
|
||||
// get asks the API for path below the tenant and decodes the answer.
|
||||
// A refused token is fetched again once.
|
||||
func (a *Admin) get(ctx context.Context, path string, out any) error {
|
||||
if err := checkURL("admin API", a.API); err != nil {
|
||||
return err
|
||||
}
|
||||
if a.Tenant == "" || strings.ContainsAny(a.Tenant, "/?#") {
|
||||
return errors.New("yaiam: admin API: no tenant")
|
||||
}
|
||||
target := strings.TrimSuffix(a.API, "/") + "/tenants/" + url.PathEscape(a.Tenant) + "/" + path
|
||||
for attempt := 0; ; attempt++ {
|
||||
tok, err := a.token(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
status, body, err := a.doMax(req, maxList)
|
||||
if err != nil {
|
||||
return fmt.Errorf("yaiam: admin API: %w", err)
|
||||
}
|
||||
if status == http.StatusUnauthorized && attempt == 0 {
|
||||
a.tokMu.Lock()
|
||||
a.tok = nil
|
||||
a.tokMu.Unlock()
|
||||
continue
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
var p struct {
|
||||
Title string `json:"title"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
json.Unmarshal(body, &p)
|
||||
desc := p.Detail
|
||||
if desc == "" {
|
||||
desc = p.Title
|
||||
}
|
||||
return &Error{Endpoint: "admin API", Status: status, Description: desc}
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return fmt.Errorf("yaiam: admin API: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user