oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "context"
5 "crypto/hmac"
6 "encoding/base64"
7 "errors"
8 "net/http"
9 "strings"
10 "time"
11
12 "amadan.net/oficina/home/internal/home/directorydata"
13 "amadan.net/oficina/home/internal/operator"
14 "amadan.net/rastrillo/rastrillo/assertion"
15 "amadan.net/rastrillo/rastrillo/sessions"
16 json "github.com/go-json-experiment/json"
17)
18
19// The confirm ceremony (team-provisioning-amendment.md §4, steps 2 and 3):
20// Paul opens each role's window on Home's own page, after a fresh sign-in,
21// against Home's own copy of the plan. One pending plan per role, so no
22// query; both pages show the same plan id prefix.
23
24const operatorFreshness = 300 * time.Second
25
26var operatorKinds = map[string]string{
27 "initialize": "Initialize the directory",
28 "create-team": "Create a team",
29 "add-apps": "Add apps to a team",
30 "retire-apps": "Retire apps from a team",
31}
32
33// appName is the compiled registry name for a slug, or "" — never the slug
34// as stored, so the credential page draws only compiled constants.
35func appName(slug string) string {
36 for _, a := range directoryApps() {
37 if a.slug == slug {
38 return a.name
39 }
40 }
41 return ""
42}
43
44func operatorTime(unix int64) string {
45 return time.Unix(unix, 0).UTC().Format("15:04 UTC, 2 Jan 2006")
46}
47
48// ---- directory: oficina.works/operator/confirm ----
49
50// directoryFresh is the directory's view of freshness: the assertion's
51// auth_time, within 300 s and not in the future. The directory cannot see
52// the sign-in method, so a recovery-code or no-gesture Keymail session
53// passes here as it passes the Team page (the amendment's inherited gap);
54// the credential page is where the method is visible and refused.
55func directoryFresh(s sessions.Session, now time.Time) bool {
56 // A native app's directory session is never fresh: it reads teams and
57 // nothing else (directory_native.go, nativeSessionsStayNative).
58 return s.Method != nativeSessionMethod && !s.AuthTime.IsZero() && !s.AuthTime.After(now) && now.Sub(s.AuthTime) <= operatorFreshness
59}
60
61type directoryPlanView struct {
62 ID, Prefix, Kind, Label, Name, Expires string
63 ExistingTeam string
64 Hosts []string
65}
66
67func (a *App) directoryView(v operator.PlanView) directoryPlanView {
68 out := directoryPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Label: v.Label, Name: v.DisplayName, Expires: operatorTime(v.Expires)}
69 out.ExistingTeam = v.ExistingTeam
70 if v.ExistingTeam != "" {
71 out.Kind = "Connect existing apps to a team"
72 }
73 for _, app := range v.Apps {
74 if v.ExistingTeam != "" {
75 out.Hosts = append(out.Hosts, strings.TrimPrefix(directorydata.CanonicalOrigin(app), "https://"))
76 } else {
77 out.Hosts = append(out.Hosts, v.Label+"."+app+".oficina.works")
78 }
79 }
80 return out
81}
82
83// directoryOperatorSession answers the request itself unless it carries the
84// operator's fresh session.
85func (a *App) directoryOperatorSession(w http.ResponseWriter, r *http.Request) (sessions.Session, bool) {
86 w.Header().Set("Cache-Control", "no-store")
87 s, ok := sessions.Current(r)
88 if ok && s.Subject != a.op.subject {
89 a.notFound(w, r)
90 return s, false
91 }
92 // A POST's freshness is checked inside the write only (the Open admit
93 // closure), so that check is the one that counts.
94 if !ok || (r.Method == http.MethodGet && !directoryFresh(s, time.Now())) {
95 if r.Method != http.MethodGet {
96 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
97 return s, false
98 }
99 http.Redirect(w, r, a.fresh.StartPath()+"?return_to=%2Foperator%2Fconfirm", http.StatusSeeOther)
100 return s, false
101 }
102 return s, true
103}
104
105func (a *App) handleDirectoryConfirm(w http.ResponseWriter, r *http.Request) {
106 if _, ok := a.directoryOperatorSession(w, r); !ok {
107 return
108 }
109 data := map[string]any{}
110 v, err := a.op.plans.Pending(r.Context(), a.op.now())
111 switch {
112 case err == nil:
113 data["Plan"] = a.directoryView(v)
114 case !errors.Is(err, operator.ErrRefused):
115 a.serverError(w, r)
116 return
117 }
118 a.render(w, r, http.StatusOK, "operator_confirm.html", data)
119}
120
121func (a *App) handleDirectoryConfirmPost(w http.ResponseWriter, r *http.Request) {
122 s, ok := a.directoryOperatorSession(w, r)
123 if !ok {
124 return
125 }
126 // Freshness once up front, so no stale session is drawn a page; the
127 // check inside the write below is still the one that counts.
128 fresh := directoryFresh(s, time.Now())
129 if err := r.ParseForm(); err != nil {
130 if !fresh {
131 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
132 return
133 }
134 a.renderOperatorRefusal(w, r, "operator_confirm.html", http.StatusBadRequest, "Nothing was opened.")
135 return
136 }
137 stale := false
138 v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(operator.PlanView) bool {
139 // Subject and freshness inside the write: the POST's only freshness
140 // check. A stale session goes back through the GET's fresh exchange.
141 if s.Subject != a.op.subject || !directoryFresh(s, time.Now()) {
142 stale = true
143 return false
144 }
145 return true
146 })
147 if !fresh || stale {
148 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
149 return
150 }
151 a.afterOpen(w, r, "operator_confirm.html", v, err, func(view operator.PlanView) map[string]any {
152 return map[string]any{"Opened": operatorTime(view.WindowExpires), "Prefix": view.Prefix()}
153 })
154}
155
156// ---- credential: id.oficina.works/operator/confirm ----
157
158// credentialFresh: sessions.Fresh(300), no future auth_time, not a Keymail
159// approval without a gesture, and not a recovery-code session (recovery
160// mints AuthTime now, so it would satisfy any freshness window).
161func credentialFresh(s sessions.Session, now time.Time) bool {
162 authTime := s.AuthTime
163 if authTime.IsZero() {
164 authTime = s.At
165 }
166 return sessions.Fresh(s, operatorFreshness, now) && !authTime.After(now) && !keymailWithoutGesture(s) && !strings.Contains(s.Method, "recovery")
167}
168
169// writeOperatorIntent seals the fresh intent handleSigninBegin and the
170// Keymail callback already honour, so the forced sign-in takes a real
171// gesture instead of looping. Its consumer is reserved; its nonce random.
172func (a *App) writeOperatorIntent(w http.ResponseWriter) error {
173 nonce, err := assertion.RandomID()
174 if err != nil {
175 return err
176 }
177 b, err := json.Marshal(assertionIntent{Consumer: operatorConfirmConsumer, Nonce: nonce, Expires: time.Now().Unix() + 600, MaxAge: 300, Subject: a.op.subject})
178 if err != nil {
179 return err
180 }
181 sealed, err := a.secrets.Sealer.Seal("assertion.intent", b)
182 if err != nil {
183 return err
184 }
185 http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/", MaxAge: 600, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
186 return nil
187}
188
189// clearOperatorIntent consumes this page's own intent, and no other.
190func (a *App) clearOperatorIntent(w http.ResponseWriter, r *http.Request) {
191 if intent, ok := a.readAssertionIntent(r, time.Now()); ok && intent.Consumer == operatorConfirmConsumer {
192 http.SetCookie(w, &http.Cookie{Name: assertionIntentCookie, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
193 }
194}
195
196func (a *App) credentialOperatorSession(w http.ResponseWriter, r *http.Request) (sessions.Session, bool) {
197 w.Header().Set("Cache-Control", "no-store")
198 s, ok := a.sessions.From(r)
199 if ok && s.Subject != a.op.subject {
200 a.notFound(w, r)
201 return s, false
202 }
203 // A POST's freshness and method are checked inside the write only (the
204 // Open admit closure), so that check is the one that counts.
205 if !ok || (r.Method == http.MethodGet && !credentialFresh(s, time.Now())) {
206 if r.Method != http.MethodGet {
207 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
208 return s, false
209 }
210 if err := a.writeOperatorIntent(w); err != nil {
211 a.serverError(w, r)
212 return s, false
213 }
214 http.Redirect(w, r, "/signin?return_to=%2Foperator%2Fconfirm", http.StatusSeeOther)
215 return s, false
216 }
217 return s, true
218}
219
220type credentialPlanView struct {
221 ID, Prefix, Kind, Owner, Expires string
222 ExistingTeam string
223 Apps []string
224}
225
226func credentialView(v operator.PlanView) credentialPlanView {
227 out := credentialPlanView{ID: v.ID, Prefix: v.Prefix(), Kind: operatorKinds[v.Kind], Expires: operatorTime(v.Expires)}
228 out.ExistingTeam = v.ExistingTeam
229 if v.ExistingTeam != "" {
230 out.Kind = "Connect existing apps to a team"
231 }
232 if len(v.OwnerIndex) >= 8 {
233 out.Owner = v.OwnerIndex[:8]
234 }
235 for _, app := range v.Apps {
236 name := appName(app)
237 if v.ExistingTeam != "" {
238 name += " (" + strings.TrimPrefix(directorydata.CanonicalOrigin(app), "https://") + ")"
239 }
240 out.Apps = append(out.Apps, name)
241 }
242 return out
243}
244
245func (a *App) handleCredentialConfirm(w http.ResponseWriter, r *http.Request) {
246 if _, ok := a.credentialOperatorSession(w, r); !ok {
247 return
248 }
249 a.clearOperatorIntent(w, r)
250 data := map[string]any{}
251 v, err := a.op.plans.Pending(r.Context(), a.op.now())
252 switch {
253 case err == nil:
254 data["Plan"] = credentialView(v)
255 case !errors.Is(err, operator.ErrRefused):
256 a.serverError(w, r)
257 return
258 }
259 a.render(w, r, http.StatusOK, "operator_confirm_id.html", data)
260}
261
262func (a *App) handleCredentialConfirmPost(w http.ResponseWriter, r *http.Request) {
263 s, ok := a.credentialOperatorSession(w, r)
264 if !ok {
265 return
266 }
267 // Freshness once up front, so no stale session is drawn a page; the
268 // check inside the write below is still the one that counts.
269 fresh := credentialFresh(s, time.Now())
270 if err := r.ParseForm(); err != nil {
271 if !fresh {
272 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
273 return
274 }
275 a.renderOperatorRefusal(w, r, "operator_confirm_id.html", http.StatusBadRequest, "Nothing was opened.")
276 return
277 }
278 typed := strings.TrimSpace(r.PostFormValue("owner"))
279 pepper := a.secrets.Pepper
280 stale := false
281 v, err := a.op.plans.Open(r.Context(), r.PostFormValue("plan"), a.op.now(), func(v operator.PlanView) bool {
282 // Subject, freshness and method inside the write — the POST's only
283 // check of them — then the typed owner must blind-index to Home's
284 // stored owner_index.
285 if s.Subject != a.op.subject || !credentialFresh(s, time.Now()) {
286 stale = true
287 return false
288 }
289 if v.OwnerIndex == "" {
290 return true
291 }
292 return typed != "" && hmac.Equal([]byte(blindIndex(pepper, typed)), []byte(v.OwnerIndex))
293 })
294 if !fresh || stale {
295 http.Redirect(w, r, operatorConfirm, http.StatusSeeOther)
296 return
297 }
298 if err == nil {
299 a.clearOperatorIntent(w, r)
300 }
301 a.afterOpen(w, r, "operator_confirm_id.html", v, err, func(view operator.PlanView) map[string]any {
302 return map[string]any{"Opened": operatorTime(view.WindowExpires)}
303 })
304}
305
306// ---- shared ----
307
308func (a *App) afterOpen(w http.ResponseWriter, r *http.Request, page string, v operator.PlanView, err error, opened func(operator.PlanView) map[string]any) {
309 switch {
310 case err == nil:
311 a.op.sweepAt(v.WindowExpires)
312 a.logger.Info("operator confirm", "role", a.op.role, "outcome", "opened")
313 a.render(w, r, http.StatusOK, page, opened(v))
314 case errors.Is(err, operator.ErrBusy):
315 a.renderOperatorRefusal(w, r, page, http.StatusConflict, "Another window is already open. Wait for it to close.")
316 case errors.Is(err, operator.ErrRefused):
317 a.renderOperatorRefusal(w, r, page, http.StatusForbidden, "Nothing was opened. Check the plan and what you typed, then try again.")
318 default:
319 a.serverError(w, r)
320 }
321}
322
323func (a *App) renderOperatorRefusal(w http.ResponseWriter, r *http.Request, page string, status int, msg string) {
324 a.logger.Info("operator confirm", "role", a.op.role, "outcome", "refused")
325 data := map[string]any{"Error": msg}
326 if v, err := a.op.plans.Pending(context.Background(), a.op.now()); err == nil {
327 if page == "operator_confirm.html" {
328 data["Plan"] = a.directoryView(v)
329 } else {
330 data["Plan"] = credentialView(v)
331 }
332 }
333 a.render(w, r, status, page, data)
334}
335