// Package issuer hands installed apps a signed identity assertion for the // member using Base. // // An app sends the browser to GET /authorize?consumer=&nonce=. Base // answers with a page whose form posts the assertion to the app's own // /auth/assertion, submitted by a deferred script or the Continue button. // The audience is always the installed app's origin, the host Base recorded // when it installed the app, never from the request. package issuer import ( "database/sql" "embed" "encoding/base64" "encoding/json" "errors" "io/fs" "log/slog" "net/http" "strings" "time" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/oficina/base/internal/catalog" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/look" "amadan.net/oficina/base/internal/store" ) // Lifetime is how long an assertion is valid: the most rastrillo allows. const Lifetime = 120 * time.Second //go:embed templates/*.html var templateFS embed.FS type issuer struct { db *sql.DB cfg config.Config kid string member func(*http.Request) (store.Member, bool) signedInAt func(*http.Request) (time.Time, bool) logger *slog.Logger pages *look.Renderer now func() time.Time } // New returns the GET /authorize handler. Mount it behind the member gate: // member reports the signed-in member the gate admitted, and signedInAt when // the session signed in (false if unknown). db is the writer handle. func New(db *sql.DB, cfg config.Config, member func(*http.Request) (store.Member, bool), signedInAt func(*http.Request) (time.Time, bool), logger *slog.Logger) (http.Handler, error) { if db == nil || member == nil || signedInAt == nil { return nil, errors.New("issuer: db, member and signedInAt are required") } if cfg.AssertionKey == nil { return nil, errors.New("issuer: BASE_ASSERTION_KEY is required") } if logger == nil { logger = slog.Default() } sub, err := fs.Sub(templateFS, "templates") if err != nil { return nil, err } pages, err := look.NewRenderer(sub, nil) if err != nil { return nil, err } kid, _ := install.KeySet(cfg.AssertionKey) return &issuer{db: db, cfg: cfg, kid: kid, member: member, signedInAt: signedInAt, logger: logger, pages: pages, now: time.Now}, nil } type handoff struct { AppName string Action string Assertion string } func (s *issuer) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") if r.Method != http.MethodGet { w.Header().Set("Allow", http.MethodGet) http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } m, ok := s.member(r) if !ok { http.Error(w, "forbidden", http.StatusForbidden) return } q := r.URL.Query() if len(q["consumer"]) > 1 || len(q["nonce"]) != 1 || !nonceShape(q["nonce"][0]) { http.Error(w, "bad request", http.StatusBadRequest) return } app := q.Get("consumer") aud, found, err := s.installedOrigin(r, app) if err != nil { s.logger.Error("authorize: installs", "err", err) http.Error(w, "unavailable", http.StatusServiceUnavailable) return } if !found { http.Error(w, "not installed", http.StatusNotFound) return } now := s.now() iat := now.Unix() authTime := iat if at, ok := s.signedInAt(r); ok && at.Unix() > 0 && at.Unix() <= iat { authTime = at.Unix() } ext, err := json.Marshal(struct { Name string `json:"name"` Email string `json:"email"` Base string `json:"base"` }{clip(m.Name, extName), clip(m.Email, extEmail), clip(s.cfg.Name, extBase)}) if err != nil { s.fail(w, app, err) return } jti, err := assertion.RandomID() if err != nil { s.fail(w, app, err) return } token, err := assertion.Sign(s.cfg.AssertionKey, assertion.Claims{ Version: 1, Issuer: s.cfg.Origin, Audience: aud, Subject: m.ID, KeyID: s.kid, ID: jti, Nonce: q.Get("nonce"), IssuedAt: iat, ExpiresAt: iat + int64(Lifetime/time.Second), AuthTime: authTime, Ext: ext, }) if err != nil { s.fail(w, app, err) return } name := app if e, ok := catalog.Get(app); ok { name = e.Name } h := w.Header() // origin, not no-referrer: a cross-origin POST under no-referrer carries // Origin: null, and the app accepts the assertion only when Origin is // exactly Base's origin. origin still withholds the path and query, // which carry the nonce (R21). h.Set("Referrer-Policy", "origin") h.Set("Content-Security-Policy", handoffCSP(aud)) if err := s.pages.Page(w, "handoff", handoff{AppName: name, Action: aud + "/auth/assertion", Assertion: token}); err != nil { s.fail(w, app, err) return } // Never the token or the nonce: the jti is enough to match the app's logs. s.logger.Info("assertion issued", "app", app, "member", m.ID, "jti", jti) } // fail answers 500. The error text never carries the token: assertion's // errors are fixed strings. func (s *issuer) fail(w http.ResponseWriter, app string, err error) { s.logger.Error("authorize: signing", "app", app, "err", err) http.Error(w, "something went wrong", http.StatusInternalServerError) } // installedOrigin returns https:// for app when its install row is // "installed", where host is the one Base recorded when it installed the // app. That is the origin the app was given as its own (BASE_APP_ORIGIN), // so it stays right if the slug or apps domain changes later. func (s *issuer) installedOrigin(r *http.Request, app string) (string, bool, error) { if app == "" { return "", false, nil } installs, err := store.Installs(r.Context(), s.db) if err != nil { return "", false, err } for _, in := range installs { if in.App != app { continue } if in.State != "installed" || in.Host == "" { return "", false, nil } return "https://" + in.Host, true, nil } return "", false, nil } // Ext is display only, and rastrillo refuses one over 1 KiB. Each field // gets a share of that, counted as encoded JSON; with the object's own 32 // bytes the three add up to 992. const ( extName = 384 extEmail = 320 extBase = 256 ) // clip returns s if its JSON encoding (without quotes) fits in max bytes, and // otherwise its longest whole-character prefix that fits with a trailing // "…". Escapes count at their encoded size. func clip(s string, max int) string { if encodedLen(s) <= max { return s } const ellipsis = "…" // 3 bytes, not escaped var b strings.Builder used := len(ellipsis) for _, r := range s { n := encodedLen(string(r)) if used+n > max { break } used += n b.WriteRune(r) // an invalid byte becomes U+FFFD, a valid character } return b.String() + ellipsis } // encodedLen is the length of s as encoding/json writes it, less the quotes. func encodedLen(s string) int { b, _ := json.Marshal(s) return len(b) - 2 } // nonceShape accepts exactly what assertion.RandomID produces: 16 bytes as // 22 unpadded, canonical base64url characters. func nonceShape(s string) bool { if len(s) != 22 { return false } b, err := base64.RawURLEncoding.Strict().DecodeString(s) return err == nil && len(b) == 16 && base64.RawURLEncoding.EncodeToString(b) == s } // handoffCSP is rastrillo's default policy with two changes: forms may post // only to the app's origin, and the pow honeypot's style hash is dropped // because this page has no pow form. Scripts stay 'self'. func handoffCSP(aud string) string { return "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action " + aud }