| 1 | // Package issuer hands installed apps a signed identity assertion for the |
| 2 | // member using Base. |
| 3 | // |
| 4 | // An app sends the browser to GET /authorize?consumer=<app>&nonce=<n>. Base |
| 5 | // answers with a page whose form posts the assertion to the app's own |
| 6 | // /auth/assertion, submitted by a deferred script or the Continue button. |
| 7 | // The audience is always the installed app's origin, the host Base recorded |
| 8 | // when it installed the app, never from the request. |
| 9 | package issuer |
| 10 | |
| 11 | import ( |
| 12 | "database/sql" |
| 13 | "embed" |
| 14 | "encoding/base64" |
| 15 | "encoding/json" |
| 16 | "errors" |
| 17 | "io/fs" |
| 18 | "log/slog" |
| 19 | "net/http" |
| 20 | "strings" |
| 21 | "time" |
| 22 | |
| 23 | "amadan.net/rastrillo/rastrillo/assertion" |
| 24 | |
| 25 | "amadan.net/oficina/base/internal/catalog" |
| 26 | "amadan.net/oficina/base/internal/config" |
| 27 | "amadan.net/oficina/base/internal/install" |
| 28 | "amadan.net/oficina/base/internal/look" |
| 29 | "amadan.net/oficina/base/internal/store" |
| 30 | ) |
| 31 | |
| 32 | // Lifetime is how long an assertion is valid: the most rastrillo allows. |
| 33 | const Lifetime = 120 * time.Second |
| 34 | |
| 35 | //go:embed templates/*.html |
| 36 | var templateFS embed.FS |
| 37 | |
| 38 | type issuer struct { |
| 39 | db *sql.DB |
| 40 | cfg config.Config |
| 41 | kid string |
| 42 | member func(*http.Request) (store.Member, bool) |
| 43 | signedInAt func(*http.Request) (time.Time, bool) |
| 44 | logger *slog.Logger |
| 45 | pages *look.Renderer |
| 46 | now func() time.Time |
| 47 | } |
| 48 | |
| 49 | // New returns the GET /authorize handler. Mount it behind the member gate: |
| 50 | // member reports the signed-in member the gate admitted, and signedInAt when |
| 51 | // the session signed in (false if unknown). db is the writer handle. |
| 52 | 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) { |
| 53 | if db == nil || member == nil || signedInAt == nil { |
| 54 | return nil, errors.New("issuer: db, member and signedInAt are required") |
| 55 | } |
| 56 | if cfg.AssertionKey == nil { |
| 57 | return nil, errors.New("issuer: BASE_ASSERTION_KEY is required") |
| 58 | } |
| 59 | if logger == nil { |
| 60 | logger = slog.Default() |
| 61 | } |
| 62 | sub, err := fs.Sub(templateFS, "templates") |
| 63 | if err != nil { |
| 64 | return nil, err |
| 65 | } |
| 66 | pages, err := look.NewRenderer(sub, nil) |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | kid, _ := install.KeySet(cfg.AssertionKey) |
| 71 | return &issuer{db: db, cfg: cfg, kid: kid, member: member, signedInAt: signedInAt, |
| 72 | logger: logger, pages: pages, now: time.Now}, nil |
| 73 | } |
| 74 | |
| 75 | type handoff struct { |
| 76 | AppName string |
| 77 | Action string |
| 78 | Assertion string |
| 79 | } |
| 80 | |
| 81 | func (s *issuer) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 82 | w.Header().Set("Cache-Control", "no-store") |
| 83 | if r.Method != http.MethodGet { |
| 84 | w.Header().Set("Allow", http.MethodGet) |
| 85 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 86 | return |
| 87 | } |
| 88 | m, ok := s.member(r) |
| 89 | if !ok { |
| 90 | http.Error(w, "forbidden", http.StatusForbidden) |
| 91 | return |
| 92 | } |
| 93 | q := r.URL.Query() |
| 94 | if len(q["consumer"]) > 1 || len(q["nonce"]) != 1 || !nonceShape(q["nonce"][0]) { |
| 95 | http.Error(w, "bad request", http.StatusBadRequest) |
| 96 | return |
| 97 | } |
| 98 | app := q.Get("consumer") |
| 99 | aud, found, err := s.installedOrigin(r, app) |
| 100 | if err != nil { |
| 101 | s.logger.Error("authorize: installs", "err", err) |
| 102 | http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| 103 | return |
| 104 | } |
| 105 | if !found { |
| 106 | http.Error(w, "not installed", http.StatusNotFound) |
| 107 | return |
| 108 | } |
| 109 | |
| 110 | now := s.now() |
| 111 | iat := now.Unix() |
| 112 | authTime := iat |
| 113 | if at, ok := s.signedInAt(r); ok && at.Unix() > 0 && at.Unix() <= iat { |
| 114 | authTime = at.Unix() |
| 115 | } |
| 116 | ext, err := json.Marshal(struct { |
| 117 | Name string `json:"name"` |
| 118 | Email string `json:"email"` |
| 119 | Base string `json:"base"` |
| 120 | }{clip(m.Name, extName), clip(m.Email, extEmail), clip(s.cfg.Name, extBase)}) |
| 121 | if err != nil { |
| 122 | s.fail(w, app, err) |
| 123 | return |
| 124 | } |
| 125 | jti, err := assertion.RandomID() |
| 126 | if err != nil { |
| 127 | s.fail(w, app, err) |
| 128 | return |
| 129 | } |
| 130 | token, err := assertion.Sign(s.cfg.AssertionKey, assertion.Claims{ |
| 131 | Version: 1, |
| 132 | Issuer: s.cfg.Origin, |
| 133 | Audience: aud, |
| 134 | Subject: m.ID, |
| 135 | KeyID: s.kid, |
| 136 | ID: jti, |
| 137 | Nonce: q.Get("nonce"), |
| 138 | IssuedAt: iat, |
| 139 | ExpiresAt: iat + int64(Lifetime/time.Second), |
| 140 | AuthTime: authTime, |
| 141 | Ext: ext, |
| 142 | }) |
| 143 | if err != nil { |
| 144 | s.fail(w, app, err) |
| 145 | return |
| 146 | } |
| 147 | name := app |
| 148 | if e, ok := catalog.Get(app); ok { |
| 149 | name = e.Name |
| 150 | } |
| 151 | h := w.Header() |
| 152 | // origin, not no-referrer: a cross-origin POST under no-referrer carries |
| 153 | // Origin: null, and the app accepts the assertion only when Origin is |
| 154 | // exactly Base's origin. origin still withholds the path and query, |
| 155 | // which carry the nonce (R21). |
| 156 | h.Set("Referrer-Policy", "origin") |
| 157 | h.Set("Content-Security-Policy", handoffCSP(aud)) |
| 158 | if err := s.pages.Page(w, "handoff", handoff{AppName: name, Action: aud + "/auth/assertion", Assertion: token}); err != nil { |
| 159 | s.fail(w, app, err) |
| 160 | return |
| 161 | } |
| 162 | // Never the token or the nonce: the jti is enough to match the app's logs. |
| 163 | s.logger.Info("assertion issued", "app", app, "member", m.ID, "jti", jti) |
| 164 | } |
| 165 | |
| 166 | // fail answers 500. The error text never carries the token: assertion's |
| 167 | // errors are fixed strings. |
| 168 | func (s *issuer) fail(w http.ResponseWriter, app string, err error) { |
| 169 | s.logger.Error("authorize: signing", "app", app, "err", err) |
| 170 | http.Error(w, "something went wrong", http.StatusInternalServerError) |
| 171 | } |
| 172 | |
| 173 | // installedOrigin returns https://<host> for app when its install row is |
| 174 | // "installed", where host is the one Base recorded when it installed the |
| 175 | // app. That is the origin the app was given as its own (BASE_APP_ORIGIN), |
| 176 | // so it stays right if the slug or apps domain changes later. |
| 177 | func (s *issuer) installedOrigin(r *http.Request, app string) (string, bool, error) { |
| 178 | if app == "" { |
| 179 | return "", false, nil |
| 180 | } |
| 181 | installs, err := store.Installs(r.Context(), s.db) |
| 182 | if err != nil { |
| 183 | return "", false, err |
| 184 | } |
| 185 | for _, in := range installs { |
| 186 | if in.App != app { |
| 187 | continue |
| 188 | } |
| 189 | if in.State != "installed" || in.Host == "" { |
| 190 | return "", false, nil |
| 191 | } |
| 192 | return "https://" + in.Host, true, nil |
| 193 | } |
| 194 | return "", false, nil |
| 195 | } |
| 196 | |
| 197 | // Ext is display only, and rastrillo refuses one over 1 KiB. Each field |
| 198 | // gets a share of that, counted as encoded JSON; with the object's own 32 |
| 199 | // bytes the three add up to 992. |
| 200 | const ( |
| 201 | extName = 384 |
| 202 | extEmail = 320 |
| 203 | extBase = 256 |
| 204 | ) |
| 205 | |
| 206 | // clip returns s if its JSON encoding (without quotes) fits in max bytes, and |
| 207 | // otherwise its longest whole-character prefix that fits with a trailing |
| 208 | // "…". Escapes count at their encoded size. |
| 209 | func clip(s string, max int) string { |
| 210 | if encodedLen(s) <= max { |
| 211 | return s |
| 212 | } |
| 213 | const ellipsis = "…" // 3 bytes, not escaped |
| 214 | var b strings.Builder |
| 215 | used := len(ellipsis) |
| 216 | for _, r := range s { |
| 217 | n := encodedLen(string(r)) |
| 218 | if used+n > max { |
| 219 | break |
| 220 | } |
| 221 | used += n |
| 222 | b.WriteRune(r) // an invalid byte becomes U+FFFD, a valid character |
| 223 | } |
| 224 | return b.String() + ellipsis |
| 225 | } |
| 226 | |
| 227 | // encodedLen is the length of s as encoding/json writes it, less the quotes. |
| 228 | func encodedLen(s string) int { |
| 229 | b, _ := json.Marshal(s) |
| 230 | return len(b) - 2 |
| 231 | } |
| 232 | |
| 233 | // nonceShape accepts exactly what assertion.RandomID produces: 16 bytes as |
| 234 | // 22 unpadded, canonical base64url characters. |
| 235 | func nonceShape(s string) bool { |
| 236 | if len(s) != 22 { |
| 237 | return false |
| 238 | } |
| 239 | b, err := base64.RawURLEncoding.Strict().DecodeString(s) |
| 240 | return err == nil && len(b) == 16 && base64.RawURLEncoding.EncodeToString(b) == s |
| 241 | } |
| 242 | |
| 243 | // handoffCSP is rastrillo's default policy with two changes: forms may post |
| 244 | // only to the app's origin, and the pow honeypot's style hash is dropped |
| 245 | // because this page has no pow form. Scripts stay 'self'. |
| 246 | func handoffCSP(aud string) string { |
| 247 | return "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action " + aud |
| 248 | } |
| 249 | |