| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "net/http" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/estilo.git/chrome" |
| 11 | "amadan.net/oficina/estilo.git/theme" |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | "amadan.net/rastrillo/rastrillo/assertion" |
| 14 | "amadan.net/rastrillo/rastrillo/csrf" |
| 15 | "amadan.net/rastrillo/rastrillo/db" |
| 16 | "amadan.net/rastrillo/rastrillo/sessions" |
| 17 | "github.com/go-chi/chi/v5" |
| 18 | "github.com/keymaildev/signin" |
| 19 | ) |
| 20 | |
| 21 | // freshStartPath is the directory's fresh-only start (handoff |
| 22 | // ConsumerConfig.StartPath). It asks the credential origin for max_age=300. |
| 23 | const freshStartPath = "/auth/fresh/start" |
| 24 | |
| 25 | func newDirectory(cfg Runtime, d *db.DB, logger *slog.Logger) (*App, error) { |
| 26 | if !cfg.validAppPreviews() || cfg.role != "directory" || cfg.origins.validate() != nil || cfg.secrets.Sealer == nil || d == nil || cfg.signer != nil || !cfg.roster.valid(cfg.role, cfg.keys) { |
| 27 | return nil, errExchangeConfig |
| 28 | } |
| 29 | if logger == nil { |
| 30 | logger = slog.Default() |
| 31 | } |
| 32 | renderer, err := newRenderer() |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | sess, err := sessions.New(sessions.Config{DB: d.Writer(), Origin: cfg.origins.Directory, TTL: 30 * 24 * time.Hour, SigninPath: handoff.StartPath, Logger: logger}) |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | store, err := handoff.NewStore(d.Writer(), cfg.secrets.Sealer, cfg.origins.Credential, cfg.origins.Directory, cfg.keys) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | if err = store.Sweep(context.Background(), time.Now()); err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | a := &App{handoffStore: store, runtime: &cfg, origins: cfg.origins, credentialHost: strings.TrimPrefix(cfg.origins.Credential, "https://"), directoryHost: strings.TrimPrefix(cfg.origins.Directory, "https://"), secrets: cfg.secrets, db: d, logger: logger, renderer: renderer, sessions: sess} |
| 48 | // One completion for both consumers: the directory's one session boundary. |
| 49 | complete := func(w http.ResponseWriter, r *http.Request, c assertion.Claims) error { |
| 50 | // An assertion issued before "Sign out all devices" buys nothing. |
| 51 | if err := a.directorySigninAllowed(r.Context(), c); err != nil { |
| 52 | markSignedOutAllFinish(w) |
| 53 | return err |
| 54 | } |
| 55 | afterMarkCheck() |
| 56 | if err := a.sessions.SignIn(w, r, sessions.Session{Subject: c.Subject, Method: "assertion", AuthTime: time.Unix(c.AuthTime, 0)}); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | // SignIn writes on its own, so a receipt may have committed between |
| 60 | // the check above and it. Check again now the session exists; if the |
| 61 | // press came in between, the new session goes too. |
| 62 | if err := a.directorySigninAllowed(r.Context(), c); err != nil { |
| 63 | a.undoSignIn(w, r) |
| 64 | markSignedOutAllFinish(w) |
| 65 | return err |
| 66 | } |
| 67 | return nil |
| 68 | } |
| 69 | a.consumer, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", CurrentSubject: func(r *http.Request) string { |
| 70 | s, ok := sessions.Current(r) |
| 71 | if !ok { |
| 72 | return "" |
| 73 | } |
| 74 | return s.Subject |
| 75 | }, Complete: complete, Fail: func(w http.ResponseWriter, r *http.Request, status int) { |
| 76 | a.failDirectoryHandoff(w, r, status) |
| 77 | }}) |
| 78 | if err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | // The fresh-only consumer (team-provisioning-amendment.md §4, the |
| 82 | // directory confirm page; team-members.md §2): the same Store, consumer ID, |
| 83 | // Callback and Finish as the ordinary one, its own start path, and |
| 84 | // max_age=300 on every authorize it asks for. Store.Finish enforces the |
| 85 | // freshness the pending row was started with, whichever Finish serves it. |
| 86 | a.fresh, err = handoff.NewConsumer(handoff.ConsumerConfig{Store: store, ConsumerID: "directory", RequireFreshAuth: true, StartPath: freshStartPath, CurrentSubject: func(r *http.Request) string { |
| 87 | s, ok := sessions.Current(r) |
| 88 | if !ok { |
| 89 | return "" |
| 90 | } |
| 91 | return s.Subject |
| 92 | }, Complete: complete, Fail: func(w http.ResponseWriter, r *http.Request, status int) { |
| 93 | a.failDirectoryHandoff(w, r, status) |
| 94 | }}) |
| 95 | if err != nil { |
| 96 | return nil, err |
| 97 | } |
| 98 | a.teamWrites = signin.NewMemoryLimiter(time.Hour) |
| 99 | a.dash = newDashboardState() |
| 100 | a.directory, err = a.newDirectoryFeatures() |
| 101 | if err != nil { |
| 102 | return nil, err |
| 103 | } |
| 104 | if err = a.newOperatorEndpoint(a.runtime); err != nil { |
| 105 | return nil, err |
| 106 | } |
| 107 | return a, nil |
| 108 | } |
| 109 | func (a *App) directoryRouter() http.Handler { |
| 110 | r := chi.NewRouter() |
| 111 | r.Use(chooserNoStore) |
| 112 | r.Use(a.serveKnownHost) |
| 113 | r.Use(a.chooserCookies) |
| 114 | // Before the session middleware: a native app's session is invisible to |
| 115 | // every route but the native API it was minted for. |
| 116 | r.Use(a.nativeSessionsStayNative) |
| 117 | r.Use(a.sessions.Middleware) |
| 118 | // After the session middleware, so a signed-in person's 404 shows their |
| 119 | // account menu (spec §3.3). |
| 120 | r.NotFound(a.notFound) |
| 121 | r.MethodNotAllowed(a.methodNotAllowed) |
| 122 | a.mountCredits(r) |
| 123 | // This callback alone accepts a cross-origin POST, with its own exact issuer |
| 124 | // check and browser-bound finish. Every other mutation retains CSRF protection. |
| 125 | r.Post(handoff.CallbackPath, a.consumer.Callback) |
| 126 | r.Post(dashboardCallback, a.receiveDashboard) |
| 127 | // The credential origin's member-resolution receipt arrives here as a |
| 128 | // cross-origin POST, with its own exact Origin check (team_page.go). |
| 129 | r.Post(teamResolvedPath, a.handleTeamResolved) |
| 130 | // The native exchange and sign-out (directory_native.go) refuse every |
| 131 | // browser evidence header instead. |
| 132 | r.Post(nativeExchangePath, a.directoryNativeExchange) |
| 133 | r.Post(nativeDirectorySignout, a.directoryNativeSignout) |
| 134 | // "Sign out all devices" arrives from the credential origin as a |
| 135 | // cross-origin POST with its own exact Origin check (signout_all.go). |
| 136 | r.Post(signedOutAllPath, a.handleSignedOutAll) |
| 137 | r.Group(func(r chi.Router) { |
| 138 | r.Use(csrf.Protect(a.origins.Directory)) |
| 139 | for _, chooser := range a.directory.choosers { |
| 140 | r.Get(chooser.entryPath, chooser.Entry) |
| 141 | r.Post(chooser.choicePath, chooser.Select) |
| 142 | } |
| 143 | r.Get(handoff.StartPath, a.consumer.Start) |
| 144 | r.Get(a.fresh.StartPath(), a.fresh.Start) |
| 145 | r.Get(handoff.FinishPath, func(w http.ResponseWriter, r *http.Request) { |
| 146 | // The writer lets Complete tell Fail that the refusal was "Sign |
| 147 | // out all devices", so the person sees that rather than a |
| 148 | // generic failure. |
| 149 | a.consumer.Finish(&finishWriter{ResponseWriter: w}, r) |
| 150 | }) |
| 151 | r.Get(nativeTeamsPath, a.directoryNativeTeams) |
| 152 | r.Get(noTeamsHelpPath, a.handleNoTeamsHelp) |
| 153 | r.Get("/signin", func(w http.ResponseWriter, r *http.Request) { |
| 154 | http.Redirect(w, r, handoff.StartPath, http.StatusSeeOther) |
| 155 | }) |
| 156 | // The Team page (team-members.md, Part A). |
| 157 | r.Get(teamPath, a.handleTeam) |
| 158 | r.Post(teamAddPath, a.handleTeamAdd) |
| 159 | r.Post(teamRolePath, a.handleTeamRole) |
| 160 | r.Post(teamNamePath, a.handleTeamName) |
| 161 | r.Post(teamRemovePath, a.handleTeamRemove) |
| 162 | r.Get(teamConfirmPath, a.handleTeamConfirm) |
| 163 | r.Post(teamConfirmPath, a.handleTeamConfirmPost) |
| 164 | if a.op != nil { |
| 165 | r.Get(operatorConfirm, a.handleDirectoryConfirm) |
| 166 | r.Post(operatorConfirm, a.handleDirectoryConfirmPost) |
| 167 | } |
| 168 | // One URL, two audiences. A visitor with no session gets the front |
| 169 | // page — what Oficina is, the apps, and the way in. A signed-in |
| 170 | // person gets their directory. Gating this behind sessions.Require |
| 171 | // instead, as it was, sends every stranger who types oficina.works |
| 172 | // to a sign-in form: a door with no building attached to it. |
| 173 | // |
| 174 | // The session is READ here, never required, so an expired cookie |
| 175 | // degrades to the front page rather than to a redirect loop. |
| 176 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { |
| 177 | // no-store covers BOTH branches, and it is set before either |
| 178 | // runs. One URL now answers two different bodies keyed on a |
| 179 | // cookie, so a shared cache that stored the anonymous 200 |
| 180 | // would hand the front page to signed-in people. Vary: Cookie |
| 181 | // says the same thing to a cache that honours it; no-store is |
| 182 | // the half that does not depend on it honouring anything. |
| 183 | w.Header().Set("Cache-Control", "no-store") |
| 184 | w.Header().Add("Vary", "Cookie") |
| 185 | // Current reads what Middleware already resolved for this |
| 186 | // request, rather than asking the database a second time. |
| 187 | if _, ok := sessions.Current(r); !ok { |
| 188 | a.handleIndex(w, r) |
| 189 | return |
| 190 | } |
| 191 | a.handleDashboard(w, r) |
| 192 | }) |
| 193 | // The account menu's Appearance (spec §8.3): inside Protect, outside |
| 194 | // any session requirement, so a session that expired mid-page does |
| 195 | // not turn the click into a sign-in loop. A host-only cookie, so the |
| 196 | // choice is the directory's own. |
| 197 | r.Post("/appearance", chrome.HandleAppearance) |
| 198 | // Local revocation and landing never wait for the credential origin. |
| 199 | r.Post(signoutPath, func(w http.ResponseWriter, r *http.Request) { |
| 200 | w.Header().Set("Cache-Control", "no-store") |
| 201 | a.sessions.SignOut(w, r) |
| 202 | idCookie(w, "__Host-oficina-finish-signout", "1", 300) |
| 203 | http.Redirect(w, r, "/signed-out", http.StatusSeeOther) |
| 204 | }) |
| 205 | r.Get("/signed-out", func(w http.ResponseWriter, r *http.Request) { |
| 206 | w.Header().Set("Cache-Control", "no-store") |
| 207 | finish := cookieValue(r, "__Host-oficina-finish-signout") == "1" |
| 208 | all := cookieValue(r, "__Host-oficina-signed-out-all") == "1" |
| 209 | idCookie(w, "__Host-oficina-finish-signout", "", -1) |
| 210 | idCookie(w, "__Host-oficina-signed-out-all", "", -1) |
| 211 | a.render(w, r, 200, "directory_signed_out.html", map[string]any{"Finish": finish && !all, "AllDevices": all, "Action": a.origins.Credential + signoutPath}) |
| 212 | }) |
| 213 | r.Get("/static/assertion.js", serveAsset(staticAsset("assertion.js"), "text/javascript; charset=utf-8")) |
| 214 | r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }) |
| 215 | mountCSS(r, "/static/tokens.css", staticAsset("tokens.css")) |
| 216 | mountCSS(r, "/static/theme.css", theme.CSS()) |
| 217 | mountBrand(r) |
| 218 | mountCalma(r) |
| 219 | mountSite(r) |
| 220 | }) |
| 221 | return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 222 | if req.URL.Path == agentDirectoryPath { |
| 223 | a.agentDirectory(w, req) |
| 224 | return |
| 225 | } |
| 226 | if req.URL.Path == rosterPath { |
| 227 | a.directory.roster.ServeHTTP(w, req) |
| 228 | return |
| 229 | } |
| 230 | // Outside csrf.Protect and before the session middleware, as the |
| 231 | // handoff callback is outside CSRF; it refuses any Cookie anyway. |
| 232 | if a.serveOperator(w, req) { |
| 233 | return |
| 234 | } |
| 235 | r.ServeHTTP(w, req) |
| 236 | }) |
| 237 | } |
| 238 | |