Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ jobs:
- name: Pure subsystems (Template + Crypto + JWT + SAML + Auth.Security, ~36 LSpec assertions)
run: ./.lake/build/bin/pure_spec

- name: Auth integration (OAuth2 round-trip, OAuth2.gate, auth_proxy, per-user streaming proxy over Unix sockets, TLS timeout, SAML fixtures, ~160 LSpec assertions)
- name: Auth integration (OAuth2 round-trip, OAuth2.gate, auth_proxy, per-user streaming proxy over Unix sockets, TLS timeout, SAML fixtures, ~168 LSpec assertions)
run: ./.lake/build/bin/auth_spec

- name: Valkey driver (RESP round-trip against the `services:` valkey container, 8 LSpec assertions)
Expand Down
111 changes: 86 additions & 25 deletions LeanTea/Auth/Proxy.lean
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,33 @@ def Target.hostHeader : Target → String
| .tcp h p => s!"{h}:{p}"
| _ => "localhost"

/-- One line of the table: requests by `login` (any login, signed in or
not, for `*`) under `pathPrefix` go to `target`. -/
/-- One line of the table: requests under `pathPrefix` by the logins
`login` names go to `target`.

`login` is one login, several separated by commas (`alice,bob`), `*`
for whoever got past the sign-in (signed in, or on one of the gate's
public paths), or `-` for everyone, signed in or not: such a route
never asks to sign in, and still gets `X-Forwarded-User` when there is
a session. With `strip`, the upstream gets the path without the
prefix (`/manager/x` → `/x`) and the prefix in `X-Forwarded-Prefix`. -/
structure Route where
login : String
pathPrefix : String
target : Target
strip : Bool := false
deriving Inhabited, Repr

/-- Parse a table: one route per line, `LOGIN PATH-PREFIX TARGET`
/-- Does the route's `login` field let `login` (`none`: no session) in? -/
def Route.admits (r : Route) (login : Option String) : Bool :=
r.login == "-" || r.login == "*" ||
login.any fun l => (r.login.splitOn ",").any (·.trimAscii.toString.toLower == l.toLower)

/-- The logins a table names (not `*` or `-`), for the sign-in allow list. -/
def namedLogins (routes : List Route) : List String :=
(routes.flatMap fun r => (r.login.splitOn ",").map (·.trimAscii.toString))
|>.filter (fun l => !l.isEmpty && l != "*" && l != "-") |>.eraseDups

/-- Parse a table: one route per line, `LOGIN PATH-PREFIX TARGET [strip]`
separated by spaces; `#` starts a comment. -/
def parseRoutes (text : String) : Except String (List Route) := do
let mut out := #[]
Expand All @@ -175,13 +193,18 @@ def parseRoutes (text : String) : Except String (List Route) := do
let line := ((raw.splitOn "#").headD "").trimAscii.toString
if line.isEmpty then continue
let ws := (line.split (fun c => c == ' ' || c == '\t')).toList.map (·.toString) |>.filter (!·.isEmpty)
match ws with
| [login, pre, tgt] =>
unless pre.startsWith "/" do throw s!"line {n}: the path prefix must start with /: {pre}"
let some t := Target.parse? tgt
| throw s!"line {n}: expected unix:/path, HOST:PORT or deny, got {tgt}"
out := out.push { login, pathPrefix := pre, target := t }
| _ => throw s!"line {n}: expected LOGIN PATH-PREFIX TARGET"
let (login, pre, tgt, opts) ← match ws with
| [l, p, t] => pure (l, p, t, [])
| l :: p :: t :: o => pure (l, p, t, o)
| _ => throw s!"line {n}: expected LOGIN PATH-PREFIX TARGET [strip]"
unless pre.startsWith "/" do throw s!"line {n}: the path prefix must start with /: {pre}"
let some t := Target.parse? tgt
| throw s!"line {n}: expected unix:/path, HOST:PORT or deny, got {tgt}"
for o in opts do
unless o == "strip" do throw s!"line {n}: unknown option {o} (only strip)"
if (login.splitOn ",").any (fun l => l.trimAscii.isEmpty) then
throw s!"line {n}: empty login in {login}"
out := out.push { login, pathPrefix := pre, target := t, strip := opts.contains "strip" }
return out.toList

/-- A path prefix without its trailing slashes (`/mcp/` is `/mcp`), so
Expand All @@ -201,17 +224,34 @@ def prefixCovers (pre path : String) : Bool :=
/-- The target for `login` (`none`: not signed in) at the canonical
`path`: the longest covering prefix among the login's own lines and
the `*` lines; on a tie, `deny` wins. `none` when nothing covers it. -/
def pick (routes : List Route) (login : Option String) (path : String) : Option Target :=
let mine := routes.filter fun r =>
(r.login == "*" || login.any (·.toLower == r.login.toLower)) && prefixCovers r.pathPrefix path
def pickRoute (routes : List Route) (login : Option String) (path : String) : Option Route :=
let mine := routes.filter fun r => r.admits login && prefixCovers r.pathPrefix path
-- Compared as normalised, as `prefixCovers` matches them.
let len (r : Route) := (normPrefix r.pathPrefix).length
let best := mine.foldl (fun (acc : Option Route) r =>
match acc with
| none => some r
| some a =>
if len r > len a || (len r == len a && r.target == .deny) then some r else acc) none
best.map (·.target)
best

/-- `pickRoute`'s target. -/
def pick (routes : List Route) (login : Option String) (path : String) : Option Target :=
(pickRoute routes login path).map (·.target)

/-- `path` (as received, canonical) without the first segments that make
up `pre`: `/manager/x` under `/manager` is `/x`, and `/manager` is `/`. -/
def stripPrefix (pre path : String) : String :=
let n := ((normPrefix pre).splitOn "/").filter (!·.isEmpty) |>.length
let rest := ((path.splitOn "/").drop (n + 1))
"/" ++ String.intercalate "/" rest

/-- A `Location` the upstream sent, with the stripped prefix put back
when it is a path on this host (`/login` → `/manager/login`). -/
def relocate (pre loc : String) : String :=
if loc.startsWith "/" && !loc.startsWith "//" && !loc.startsWith "/\\" then
normPrefix pre ++ loc
else loc

structure Config where
routes : List Route
Expand Down Expand Up @@ -304,11 +344,13 @@ private def answer (client : LeanTea.Net.Transport) (r : Response) : IO Unit :=
a response as it arrives, or, after a `101`, the connection both ways
until either side closes. -/
def relay (cfg : Config) (g : GateConfig) (user : Option User) (target : Target) (req : Request)
(client : LeanTea.Net.Transport) (leftover : ByteArray) : IO Unit := do
(client : LeanTea.Net.Transport) (leftover : ByteArray) (strip : Option String := none)
: IO Unit := do
if req.body.size > cfg.maxBody then
return ← answer client (Response.text 413 s!"request body over {cfg.maxBody} bytes\n")
let upgrade := LeanTea.Net.WebSocketServer.isUpgrade req
let headers := upstreamHeaders g user req
let headers := upstreamHeaders g user req ++
((strip.map fun p => #[("X-Forwarded-Prefix", normPrefix p)]).getD #[])
-- Client headers were parsed line by line, but the identity comes from
-- the provider: a line break in it would add headers of its choosing.
if headers.any (fun (k, v) => (k ++ v).any fun c => c == '\r' || c == '\n') then
Expand All @@ -319,7 +361,10 @@ def relay (cfg : Config) (g : GateConfig) (user : Option User) (target : Target)
client.setSendTimeout cfg.sendTimeoutMs
up.setSendTimeout cfg.sendTimeoutMs
try
let path := if req.query.isEmpty then req.path else req.path ++ "?" ++ req.query
let base := match strip with
| some p => stripPrefix p req.path
| none => req.path
let path := if req.query.isEmpty then base else base ++ "?" ++ req.query
let mut head := s!"{req.method} {path} HTTP/1.1\r\nHost: {target.hostHeader}\r\n"
for (k, v) in headers do
head := head ++ s!"{k}: {v}\r\n"
Expand Down Expand Up @@ -358,6 +403,12 @@ def relay (cfg : Config) (g : GateConfig) (user : Option User) (target : Target)
let _ ← IO.wait back
else
let kept := h.lines.filter fun l => !["connection", "keep-alive"].contains (name l)
let kept := match strip with
| some p => kept.map fun l =>
if name l == "location" then
"Location: " ++ relocate p (((l.splitOn ":").drop 1 |> String.intercalate ":").trimAscii.toString)
else l
| none => kept
client.send (h.statusLine ++ "\r\n" ++
String.join (kept.map (· ++ "\r\n")) ++ "Connection: close\r\n\r\n").toUTF8
let length := h.lines.findSome? fun l =>
Expand All @@ -381,15 +432,25 @@ def relay (cfg : Config) (g : GateConfig) (user : Option User) (target : Target)
def takeover (cfg : Config) (g : GateConfig) (sessions : Sessions)
: LeanTea.Net.Server.Takeover := fun req => do
let respond (r : Response) := some fun (c : LeanTea.Net.Transport) (_ : ByteArray) => answer c r
match ← gateCheck g sessions req with
| .error r => return respond r
| .ok user =>
let checked ← gateCheck g sessions req
-- The gate's own routes (sign in, callback, sign out) stay the gate's.
if req.path == g.loginPath || req.path == g.callbackPath || req.path == g.logoutPath then
if let .error r := checked then return respond r
-- `.error` here means no session on a path that needs one; a `-` route
-- does not, so the gate's answer (a redirect or 401) is kept for later.
let user := match checked with | .ok u => u | .error _ => none
let some path := canonicalPath? req.path
| return respond (Response.text 400 "bad path\n")
if (LeanTea.Net.WebSocketServer.isUpgrade req || unsafeMethod req.method) && !originOk cfg g req then
return respond (Response.text 403 "cross-origin request refused\n")
match pick cfg.routes (user.map (·.login)) path with
| none | some .deny => return respond (Response.text 403 "not allowed here\n")
| some t => return some fun c leftover => relay cfg g user t req c leftover
match pickRoute cfg.routes (user.map (·.login)) path, checked with
| some r, _ =>
if r.target == .deny then return respond (Response.text 403 "not allowed here\n")
if r.login != "-" then
if let .error ans := checked then return respond ans
if (LeanTea.Net.WebSocketServer.isUpgrade req || unsafeMethod req.method) && !originOk cfg g req then
return respond (Response.text 403 "cross-origin request refused\n")
let strip := if r.strip && normPrefix r.pathPrefix != "/" then some r.pathPrefix else none
return some fun c leftover => relay cfg g user r.target req c leftover strip
| none, .error ans => return respond ans -- signing in may open a route
| none, .ok _ => return respond (Response.text 403 "not allowed here\n")

end LeanTea.Auth.Proxy
9 changes: 7 additions & 2 deletions docs/03-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,13 @@ bob@example.com / unix:/run/app/bob/daemon.sock
* /admin deny
```

The longest prefix wins, segment by segment (`deny` wins a tie, `*`
lines apply to everyone). A login or a path the map does not route gets
The longest prefix wins, segment by segment (`deny` wins a tie). LOGIN
is a login, several separated by commas, `*` for every signed-in user,
or `-` for everyone without signing in (a guest area). A trailing
`strip` passes the path on without the prefix and adds
`X-Forwarded-Prefix`, for an app that cannot live below a path; a
`Location: /…` it answers with gets the prefix back. One sign-in covers
every route, so several apps can share one host name and one OAuth app. A login or a path the map does not route gets
403. Paths are matched after `canonicalPath?`, so `/x/../admin` is 400,
not a way around `deny`, and they are passed on unchanged. With Google,
the login is the e-mail address, used only when the provider marks it
Expand Down
34 changes: 24 additions & 10 deletions examples/AuthProxy/Main.lean
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,31 @@ Responses are relayed as they arrive and WebSocket upgrades become a
tunnel to the upstream. `--upstream` is `HOST:PORT` or
`unix:/path/to.sock`.

**One upstream per user**: `--user-map FILE` instead of `--upstream`.
One route per line, `LOGIN PATH-PREFIX UPSTREAM`, where LOGIN is the
signed-in login (with Google, the verified e-mail address) or `*` for
everyone, and UPSTREAM is `unix:/path`, `HOST:PORT` or `deny`. The
longest prefix wins (segment-wise; `deny` wins a tie); a login or path
the map does not route gets 403. The path is passed on unchanged.
**Routes per user and per path**: `--user-map FILE` instead of
`--upstream`. One route per line, `LOGIN PATH-PREFIX UPSTREAM [strip]`:

* LOGIN: a signed-in login (with Google, the verified e-mail address),
several separated by commas, `*` for every signed-in user, or `-` for
everyone with no sign-in at all (a guest area, static files; a
session, if there is one, still sets `X-Forwarded-User`);
* UPSTREAM: `unix:/path`, `HOST:PORT` or `deny`;
* `strip`: pass the path on without the prefix (`/manager/x` → `/x`),
with the prefix in `X-Forwarded-Prefix`, and put the prefix back on a
`Location: /…` the upstream answers with. Without it the path is
passed on unchanged.

The longest prefix wins (segment-wise; `deny` wins a tie). A signed-in
login or a path the map does not route gets 403; without a session,
any route but a `-` one asks to sign in first. One sign-in (one cookie,
`Path=/`) covers every route.

```
alice@example.com / unix:/run/app/alice/daemon.sock
alice@example.com /stream unix:/run/app/alice/stream.sock
* /mcp deny
alice@example.com / unix:/run/app/alice/daemon.sock
alice@example.com /stream unix:/run/app/alice/stream.sock
alice,bob /manager 127.0.0.1:8080 strip
* /grafana 127.0.0.1:3000
- /tavern 127.0.0.1:2346 strip
* /mcp deny
```

Without `--allowed-users`, the logins named in the map may sign in.
Expand Down Expand Up @@ -200,7 +214,7 @@ def run (args : List String) : IO Unit := do
| some t@(.tcp ..) | some t@(.unix _) => pure [{ login := "*", pathPrefix := "/", target := t }]
| _ => throw <| IO.userError s!"--upstream: expected HOST:PORT or unix:/path, got {u}"
let allowed := if !o.allowed.isEmpty then o.allowed
else (routes.map (·.login)).filter (· != "*") |>.eraseDups
else LeanTea.Auth.Proxy.namedLogins routes
if allowed.isEmpty then
throw <| IO.userError "--allowed-users (or logins in --user-map) is required (nobody could sign in otherwise)"
let (lHost, lPort) ← IO.ofExcept (hostPort "--listen" o.listen)
Expand Down
44 changes: 41 additions & 3 deletions examples/Tests/AuthSpec.lean
Original file line number Diff line number Diff line change
Expand Up @@ -617,11 +617,15 @@ def dir : System.FilePath := ".lake/build/relay_test"
/-- Answers who it is and what it was sent. -/
def echoAs (name : String) : Handler := fun req =>
pure <| Response.text 200
s!"{name}|{req.path}|{(req.header? "x-forwarded-user").getD ""}|{(req.header? "host").getD ""}|{(req.header? "cookie").getD ""}"
(s!"{name}|{req.path}|{(req.header? "x-forwarded-user").getD ""}|{(req.header? "host").getD ""}|{(req.header? "cookie").getD ""}" ++
((req.header? "x-forwarded-prefix").map (s!"|prefix={·}")).getD "")

/-- `/slow` answers in two parts, 600 ms apart, with no length. -/
def slow : Server.Takeover := fun req => pure <|
if req.path == "/slow" then some fun c _ => do
-- An upstream that redirects to one of its own paths.
if req.path == "/redirect" then some fun c _ =>
c.send "HTTP/1.1 302 Found\r\nLocation: /login?x=1\r\nContent-Length: 0\r\n\r\n".toUTF8
else if req.path == "/slow" then some fun c _ => do
c.send "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nfirst\n".toUTF8
IO.sleep 600
c.send "second\n".toUTF8
Expand Down Expand Up @@ -855,7 +859,10 @@ def run : IO LSpec := do
s!"alice@example.com /stream unix:{aSock}\n" ++
s!"bob@example.com / unix:{bSock}\n" ++
s!"* /mcp deny\n" ++
s!"* /health unix:{bSock}\n"
s!"* /health unix:{bSock}\n" ++
s!"alice@example.com,bob@example.com /manager unix:{bSock} strip\n" ++
s!"alice@example.com /app unix:{aSock} strip\n" ++
s!"- /guest unix:{bSock} strip\n"
let routes ← IO.ofExcept (parseRoutes table)
let cfg ← GateGroup.idpConfig
let g : GateConfig := {
Expand All @@ -869,6 +876,14 @@ def run : IO LSpec := do
let alice ← sessions.create (userOf "alice@example.com") exp
let bob ← sessions.create (userOf "bob@example.com") exp
let carol ← sessions.create (userOf "carol@example.com") exp
-- Apps under path prefixes, one sign-in for all of them.
let mAlice ← ask "/manager/x" alice
let mBob ← ask "/manager" bob
let mCarol ← ask "/manager/x" carol
let mAnon ← ask "/manager/x"
let guestAnon ← ask "/guest/play"
let guestAlice ← ask "/guest/play" alice
let moved ← ask "/app/redirect" alice

let aGet ← ask "/api/x" alice "X-Forwarded-User: mallory\r\nX-Forwarded_User: mallory\r\n"
let bGet ← ask "/api/x" bob
Expand Down Expand Up @@ -1031,6 +1046,29 @@ def run : IO LSpec := do
let deny : Route := { login := "*", pathPrefix := "/mcp", target := .deny }
[[deny, allow], [allow, deny]].all fun rs =>
["/mcp", "/mcp/", "/mcp/tools"].all fun p => pick rs (some "alice") p == some .deny),
it "strip: the upstream sees the path without the prefix, and the prefix in X-Forwarded-Prefix"
(bodyOf mAlice == "bob|/x|alice@example.com|localhost|theme=dark|prefix=/manager" &&
bodyOf mBob == "bob|/|bob@example.com|localhost|theme=dark|prefix=/manager") s!"{mAlice} / {mBob}",
it "a login list: someone signed in but not on it gets 403" (statusOf mCarol == "403") mCarol,
it "without a session, a signed-in route asks to sign in (not 403)"
(statusOf mAnon == "302" && hasSubstr mAnon "next=%2Fmanager%2Fx") mAnon,
it "a `-` route needs no sign-in, and still names a signed-in user"
(bodyOf guestAnon == "bob|/play||localhost||prefix=/guest" &&
bodyOf guestAlice == "bob|/play|alice@example.com|localhost|theme=dark|prefix=/guest")
s!"{guestAnon} / {guestAlice}",
it "a Location the upstream sends gets the stripped prefix back"
(statusOf moved == "302" && hasSubstr moved "Location: /app/login?x=1") moved,
it "one session covers every route (the cookie is Path=/)"
(statusOf aGet == "200" && statusOf mAlice == "200" && statusOf guestAlice == "200"),
it "stripPrefix and relocate"
(stripPrefix "/manager" "/manager" == "/" && stripPrefix "/manager/" "/manager/" == "/" &&
stripPrefix "/manager" "/manager/a/b" == "/a/b" && stripPrefix "/a/b" "/a/b/c" == "/c" &&
relocate "/m" "/x" == "/m/x" && relocate "/m" "//evil.test/x" == "//evil.test/x" &&
relocate "/m/" "https://other.test/" == "https://other.test/"),
it "table lines: login lists, `-`, strip; unknown options and empty logins are refused"
(namedLogins routes == ["alice@example.com", "bob@example.com"] &&
(match parseRoutes "a / unix:/s bogus" with | .error e => hasSubstr e "unknown option" | .ok _ => false) &&
(match parseRoutes "a,,b / unix:/s" with | .error e => hasSubstr e "empty login" | .ok _ => false)),
it "targets: unix needs an absolute path, TCP an IPv4 address"
(Target.parse? "unix:rel" == none && Target.parse? "example.com:80" == none &&
Target.parse? "http://127.0.0.1:8080/" == some (.tcp "127.0.0.1" 8080))
Expand Down
Loading