| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | |
| 11 | "amadan.net/rastrillo/rastrillo/csrf" |
| 12 | "github.com/go-chi/chi/v5" |
| 13 | ) |
| 14 | |
| 15 | type Authenticator struct { |
| 16 | LookupMember func(context.Context, string) (kernel.Member, error) |
| 17 | NotFound error |
| 18 | Origin string |
| 19 | Cookie func(*http.Request) (PersonPrincipal, error) |
| 20 | Bearer VerifyPersonBearer |
| 21 | Member func(*http.Request, PersonPrincipal) error |
| 22 | Forbidden error |
| 23 | } |
| 24 | |
| 25 | func (a Authenticator) Authenticate(r *http.Request) (PersonPrincipal, error) { |
| 26 | var p PersonPrincipal |
| 27 | var err error |
| 28 | if headers := r.Header.Values("Authorization"); len(headers) != 0 { |
| 29 | if len(headers) != 1 || len(r.Header.Values("Cookie")) != 0 || !strings.HasPrefix(headers[0], "Bearer ") || a.Bearer == nil { |
| 30 | return p, ErrUnauthenticated |
| 31 | } |
| 32 | token := strings.TrimPrefix(headers[0], "Bearer ") |
| 33 | if token == "" || strings.ContainsAny(token, " \t\r\n") { |
| 34 | return p, ErrUnauthenticated |
| 35 | } |
| 36 | p, err = a.Bearer(r.Context(), token) |
| 37 | if err != nil || p.CredentialID == "" { |
| 38 | return PersonPrincipal{}, ErrUnauthenticated |
| 39 | } |
| 40 | } else { |
| 41 | if a.Cookie == nil { |
| 42 | return p, ErrUnauthenticated |
| 43 | } |
| 44 | p, err = a.Cookie(r) |
| 45 | if err != nil { |
| 46 | return p, err |
| 47 | } |
| 48 | } |
| 49 | if p.Address == "" || p.SessionEpoch <= 0 { |
| 50 | return PersonPrincipal{}, ErrUnauthenticated |
| 51 | } |
| 52 | if err = a.Member(r, p); err != nil { |
| 53 | return PersonPrincipal{}, err |
| 54 | } |
| 55 | if !OriginAllowed(r, a.Origin) { |
| 56 | return PersonPrincipal{}, a.Forbidden |
| 57 | } |
| 58 | if len(r.Header.Values("Authorization")) == 0 && Mutating(r.Method) && !csrf.SameOrigin(r, a.Origin) { |
| 59 | return PersonPrincipal{}, a.Forbidden |
| 60 | } |
| 61 | return p, nil |
| 62 | } |
| 63 | func Mutating(method string) bool { return method != "GET" && method != "HEAD" && method != "OPTIONS" } |
| 64 | func OriginAllowed(r *http.Request, origin string) bool { |
| 65 | if values := r.Header.Values("Origin"); len(values) > 1 || len(values) == 1 && values[0] != origin { |
| 66 | return false |
| 67 | } |
| 68 | if values := r.Header.Values("Referer"); len(values) > 1 { |
| 69 | return false |
| 70 | } else if len(values) == 1 { |
| 71 | u, err := url.Parse(values[0]) |
| 72 | if err != nil || u.Scheme+"://"+u.Host != origin { |
| 73 | return false |
| 74 | } |
| 75 | } |
| 76 | switch r.Header.Get("Sec-Fetch-Site") { |
| 77 | case "", "same-origin", "none": |
| 78 | return true |
| 79 | default: |
| 80 | return false |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // Dispatcher bypasses the browser wrapper only for registered protocol routes. |
| 85 | // Their handlers verify their own credentials before accepting a mutation. |
| 86 | func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http.ResponseWriter), assertionCallback ...bool) func(http.Handler) http.Handler { |
| 87 | return func(next http.Handler) http.Handler { |
| 88 | var options []csrf.Option |
| 89 | if len(assertionCallback) == 1 && assertionCallback[0] { |
| 90 | options = append(options, csrf.Exempt("/auth/assertion"), csrf.Exempt("/native/oficina-id")) |
| 91 | } |
| 92 | browser := csrf.Protect(origin, options...)(next) |
| 93 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 94 | // Escaped separators must never select a different lane than chi's RawPath. |
| 95 | if strings.Contains(strings.ToLower(r.URL.RawPath), "%2f") { |
| 96 | WriteError(w, r, 422, "invalid_input", nil) |
| 97 | return |
| 98 | } |
| 99 | protocol := registered(r, runner, "/api/runner/v2") |
| 100 | personRoute := registered(r, person, "/api/v1") |
| 101 | public := r.Method == "POST" && (r.URL.Path == "/api/enrolments" || r.URL.Path == "/api/enrolments/token") |
| 102 | // The runner stream authenticates its own bearer before upgrading. |
| 103 | stream := r.Method == "GET" && r.URL.Path == "/api/runner/stream" |
| 104 | if personRoute { |
| 105 | next.ServeHTTP(w, r) |
| 106 | return |
| 107 | } |
| 108 | if protocol || public || stream { |
| 109 | if len(r.Header.Values("Cookie")) != 0 || !OriginAllowed(r, origin) { |
| 110 | refuseRunner(w) |
| 111 | return |
| 112 | } |
| 113 | next.ServeHTTP(w, r) |
| 114 | return |
| 115 | } |
| 116 | if len(r.Header.Values("Authorization")) != 0 { |
| 117 | WriteError(w, r, 401, "unauthenticated", nil) |
| 118 | return |
| 119 | } |
| 120 | if strings.HasPrefix(r.URL.Path, "/api/v1/") || r.URL.Path == "/api/v1" { |
| 121 | // Unknown methods/paths still receive API errors and identity validation. |
| 122 | if Mutating(r.Method) && !csrf.SameOrigin(r, origin) { |
| 123 | WriteError(w, r, 403, "forbidden", nil) |
| 124 | return |
| 125 | } |
| 126 | next.ServeHTTP(w, r) |
| 127 | return |
| 128 | } |
| 129 | browser.ServeHTTP(w, r) |
| 130 | }) |
| 131 | } |
| 132 | } |
| 133 | func registered(r *http.Request, routes chi.Routes, prefix string) bool { |
| 134 | path := r.URL.RawPath |
| 135 | if path == "" { |
| 136 | path = r.URL.Path |
| 137 | } |
| 138 | if !strings.HasPrefix(path, prefix+"/") { |
| 139 | return false |
| 140 | } |
| 141 | return routes.Match(chi.NewRouteContext(), r.Method, strings.TrimPrefix(path, prefix)) |
| 142 | } |
| 143 | func PrincipalFrom(ctx context.Context) (PersonPrincipal, bool) { |
| 144 | p, ok := ctx.Value(principalKey{}).(PersonPrincipal) |
| 145 | return p, ok |
| 146 | } |
| 147 | |
| 148 | func DenyPersonBearer(context.Context, string) (PersonPrincipal, error) { |
| 149 | return PersonPrincipal{}, ErrUnauthenticated |
| 150 | } |
| 151 | |
| 152 | func CurrentSession(ctx context.Context, address string, epoch int64) bool { |
| 153 | p, ok := PrincipalFrom(ctx) |
| 154 | return !ok || p.Address == address && p.SessionEpoch >= epoch |
| 155 | } |
| 156 | |
| 157 | func WithVerifiedPrincipal(ctx context.Context, p PersonPrincipal) context.Context { |
| 158 | return context.WithValue(ctx, principalKey{}, p) |
| 159 | } |
| 160 | |
| 161 | func (auth Authenticator) AuthenticateRoute(r *http.Request, route Route) (PersonPrincipal, error) { |
| 162 | switch route.Operation { |
| 163 | case "begin_device", "exchange_device": |
| 164 | if len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 { |
| 165 | return PersonPrincipal{}, ErrUnauthenticated |
| 166 | } |
| 167 | if !OriginAllowed(r, auth.Origin) { |
| 168 | return PersonPrincipal{}, auth.Forbidden |
| 169 | } |
| 170 | return PersonPrincipal{}, nil |
| 171 | case "native_device": |
| 172 | if len(r.Header.Values("Authorization")) != 0 { |
| 173 | return PersonPrincipal{}, ErrUnauthenticated |
| 174 | } |
| 175 | p, err := auth.Authenticate(r) |
| 176 | if err != nil { |
| 177 | return p, err |
| 178 | } |
| 179 | if p.SessionHash == "" || p.CredentialID != "" { |
| 180 | return PersonPrincipal{}, ErrUnauthenticated |
| 181 | } |
| 182 | return p, nil |
| 183 | case "approve_device", "accept_invite", "invite": |
| 184 | if route.Operation == "invite" && len(r.Header.Values("Authorization")) != 0 { |
| 185 | return auth.Authenticate(r) |
| 186 | } |
| 187 | if len(r.Header.Values("Authorization")) != 0 { |
| 188 | return PersonPrincipal{}, ErrUnauthenticated |
| 189 | } |
| 190 | if Mutating(r.Method) && !csrf.SameOrigin(r, auth.Origin) || !OriginAllowed(r, auth.Origin) { |
| 191 | return PersonPrincipal{}, auth.Forbidden |
| 192 | } |
| 193 | if route.Operation == "accept_invite" || route.Operation == "invite" { |
| 194 | p, e := auth.Cookie(r) |
| 195 | if e != nil { |
| 196 | return p, e |
| 197 | } |
| 198 | member, e := auth.LookupMember(r.Context(), p.Address) |
| 199 | if e != nil && !errors.Is(e, auth.NotFound) { |
| 200 | return p, e |
| 201 | } |
| 202 | if e == nil && p.SessionEpoch < member.SessionEpoch { |
| 203 | return p, auth.Forbidden |
| 204 | } |
| 205 | p.Pending = errors.Is(e, auth.NotFound) || !member.Active |
| 206 | return p, nil |
| 207 | } |
| 208 | } |
| 209 | return auth.Authenticate(r) |
| 210 | } |
| 211 | |