Skip to content

Commit 850517c

Browse files
committed
feat(console): accept the session cookie in a version 1 hello
A browser sends no secret in its hello, so the dashboard console has only its session cookie to show. A browser attaches that cookie to a WebSocket opened by a page of any site, so a cookie hello is accepted only when the Origin of the upgrade request names the host it reached (the forwarded host when a trusted proxy sent one). Any other Origin, or none, closes the connection with 1008 and the error code unauthorized before the session is looked at. A token in the hello is not affected, because a page of another site cannot read it. Signed-off-by: TheMeinerLP <github@themeinerlp.dev>
1 parent 08935c7 commit 850517c

5 files changed

Lines changed: 230 additions & 6 deletions

File tree

‎reposilite-backend/src/main/kotlin/com/reposilite/console/infrastructure/ConsoleAuthenticator.kt‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,18 +32,18 @@ import panda.std.asSuccess
3232
* the credentials of a token, as the console has always taken them, and the session token of a browser login, the same
3333
* one the HTTP API accepts from its session cookie.
3434
*/
35-
internal class ConsoleAuthenticator(
35+
internal open class ConsoleAuthenticator(
3636
private val accessTokenFacade: AccessTokenFacade,
3737
private val authenticationFacade: AuthenticationFacade,
3838
private val loginFacade: LoginFacade,
3939
) {
4040

41-
fun authenticate(credentials: Credentials): Result<AccessTokenDto, ErrorResponse> =
41+
open fun authenticate(credentials: Credentials): Result<AccessTokenDto, ErrorResponse> =
4242
authenticationFacade.authenticateByCredentials(credentials, path = SignInPath.CONSOLE)
4343
.flatMap { requireConsoleArea(it, credentials.ip) }
4444

4545
/** A session token from a browser login. Fails like a wrong secret when the session is not valid or has no user. */
46-
fun authenticateSession(sessionJwt: String, ip: String): Result<AccessTokenDto, ErrorResponse> {
46+
open fun authenticateSession(sessionJwt: String, ip: String): Result<AccessTokenDto, ErrorResponse> {
4747
val identifier = loginFacade.authenticateSession(sessionJwt)
4848
?: return unauthorizedError("Invalid or expired session")
4949
val identity = accessTokenFacade.getAccessTokenById(identifier)
@@ -55,7 +55,7 @@ internal class ConsoleAuthenticator(
5555
* Whether [identity], authenticated earlier, may still use the console: the token still exists and still has the console
5656
* area, and [sessionJwt], when it came from a browser login, is still a valid session.
5757
*/
58-
fun isStillAuthorized(identity: AccessTokenDto, sessionJwt: String?): Boolean {
58+
open fun isStillAuthorized(identity: AccessTokenDto, sessionJwt: String?): Boolean {
5959
if (sessionJwt != null && loginFacade.authenticateSession(sessionJwt) == null) {
6060
return false
6161
}

‎reposilite-backend/src/main/kotlin/com/reposilite/console/infrastructure/ConsoleConnection.kt‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ internal interface ConsoleConnection {
2424
/** The address the client connected from, after the forwarded header and the trusted proxies are applied. */
2525
val host: String
2626

27+
/** The `Origin` header of the upgrade request, or null when the client sent none. */
28+
val origin: String?
29+
30+
/** The host and port the upgrade request reached, as a trusted proxy forwards it, or null when it names none. */
31+
val requestHost: String?
32+
33+
/** The value of the cookie [name] of the upgrade request, or null when there is none. */
34+
fun cookie(name: String): String?
35+
2736
/** Sends one text frame as it is. */
2837
fun send(text: String)
2938

‎reposilite-backend/src/main/kotlin/com/reposilite/console/infrastructure/ConsoleWebSocketHandler.kt‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,12 @@ import com.fasterxml.jackson.databind.JsonNode
4141
import com.fasterxml.jackson.databind.ObjectMapper
4242
import java.io.IOException
4343
import java.net.InetSocketAddress
44+
import java.net.URI
45+
import java.net.URISyntaxException
4446
import java.nio.charset.StandardCharsets
4547
import java.time.Duration
4648
import java.nio.channels.ClosedChannelException
49+
import net.onelitefeather.ingot.identity.session.SessionCookies
4750
import net.onelitefeather.ingot.web.TrustedProxies
4851
import java.util.Collections
4952
import java.util.UUID
@@ -320,7 +323,16 @@ internal class ConsoleWebSocketHandler(
320323
return
321324
}
322325

323-
authenticateContext(connection, AUTHORIZATION_PREFIX + hello.text("token").orEmpty())
326+
val token = hello.text("token")?.takeIf { it.isNotEmpty() }
327+
val cookie = if (token == null) connection.cookie(SessionCookies.SESSION) else null
328+
if (cookie != null && !originNamesHost(connection)) {
329+
journalist.logger.info("CLI | refused a cookie hello from ${connection.host}: its Origin does not name the host it reached")
330+
connection.sendJson(ErrorFrame(code = "unauthorized", message = "the origin of the request is not this host"))
331+
connection.close(CLOSE_POLICY_VIOLATION, "unauthorized")
332+
return
333+
}
334+
val authorization = if (cookie != null) AUTHORIZATION_PREFIX + SESSION_PREFIX + cookie else AUTHORIZATION_PREFIX + token.orEmpty()
335+
authenticateContext(connection, authorization)
324336
.peek { identity ->
325337
journalist.logger.info("CLI | ${identity.identifier} accessed remote console (protocol $protocol)")
326338
val outbox = scheduler.openFrameOutbox(
@@ -357,6 +369,21 @@ internal class ConsoleWebSocketHandler(
357369
}
358370
}
359371

372+
/**
373+
* Whether the `Origin` of the upgrade request names the host it reached. A browser sends its cookies on a cross-site
374+
* WebSocket too, so a connection that has only a cookie to show has to come from a page of this host.
375+
*/
376+
private fun originNamesHost(connection: ConsoleConnection): Boolean {
377+
val origin = connection.origin ?: return false
378+
val host = connection.requestHost ?: return false
379+
val authority = try {
380+
URI(origin).takeIf { it.scheme != null }?.rawAuthority
381+
} catch (_: URISyntaxException) {
382+
null
383+
}
384+
return authority != null && authority.equals(host, ignoreCase = true)
385+
}
386+
360387
/** The level of the log lines a hello asks for. It can raise the visible threshold but never lower it. */
361388
private fun levelOf(hello: JsonNode): Channel {
362389
val visible = journalist.visibleThreshold
@@ -543,9 +570,19 @@ internal class ConsoleWebSocketHandler(
543570
?: "unknown host"
544571
}
545572

573+
/** The host the request reached: the forwarded one when a trusted proxy sent it, the `Host` header otherwise. */
574+
private fun WsContext.getRequestHost(): String? {
575+
val peer = (session.remoteSocketAddress as? InetSocketAddress)?.address?.hostAddress
576+
val forwarded = if (trustedProxies.enabled && peer != null && trustedProxies.isTrusted(peer)) header("X-Forwarded-Host") else null
577+
return forwarded?.substringBefore(',')?.trim()?.takeIf { it.isNotEmpty() } ?: header("Host")
578+
}
579+
546580
/** A Javalin context as a [ConsoleConnection]. Every callback gets a new context, and contexts of one socket are equal. */
547581
private inner class JavalinConsoleConnection(private val ctx: WsContext) : ConsoleConnection {
548582
override val host: String get() = ctx.getHost()
583+
override val origin: String? get() = ctx.header("Origin")
584+
override val requestHost: String? get() = ctx.getRequestHost()
585+
override fun cookie(name: String): String? = ctx.cookie(name)
549586
override fun send(text: String) = ctx.send(text)
550587
override fun sendJson(value: Any) = ctx.send(value)
551588
override fun disconnect() = ctx.session.disconnect()

‎reposilite-backend/src/test/kotlin/com/reposilite/console/infrastructure/ConsoleSocketFakes.kt‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,14 @@ import java.time.Instant
2222
import java.time.ZoneOffset
2323

2424
/** A console socket that records what the handler sends. Equal only to itself, like one real socket. */
25-
internal class FakeConsoleConnection(override val host: String = "203.0.113.7") : ConsoleConnection {
25+
internal class FakeConsoleConnection(
26+
override val host: String = "203.0.113.7",
27+
override val origin: String? = null,
28+
override val requestHost: String? = null,
29+
private val cookies: Map<String, String> = emptyMap(),
30+
) : ConsoleConnection {
31+
32+
override fun cookie(name: String): String? = cookies[name]
2633

2734
val texts = mutableListOf<String>()
2835
val json = mutableListOf<Any>()
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
/*
2+
* Copyright (c) 2026 OneLiteFeather
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.reposilite.console.infrastructure
17+
18+
import com.reposilite.ReposiliteJournalist
19+
import com.reposilite.auth.specification.AuthenticationSpecification
20+
import com.reposilite.console.CommandExecutor
21+
import com.reposilite.console.ConsoleFacade
22+
import com.reposilite.journalist.backend.InMemoryLogger
23+
import com.reposilite.shared.ErrorResponse
24+
import com.reposilite.status.FailureFacade
25+
import com.reposilite.token.AccessTokenPermission.MANAGER
26+
import com.reposilite.token.AccessTokenType.TEMPORARY
27+
import com.reposilite.token.api.AccessTokenDto
28+
import com.reposilite.token.api.CreateAccessTokenRequest
29+
import net.onelitefeather.ingot.identity.login.LoginFacade
30+
import net.onelitefeather.ingot.identity.session.SessionCookies
31+
import org.assertj.core.api.Assertions.assertThat
32+
import org.junit.jupiter.api.AfterEach
33+
import org.junit.jupiter.api.BeforeEach
34+
import org.junit.jupiter.api.Test
35+
import panda.std.Result
36+
import panda.std.asSuccess
37+
import panda.std.reactive.Reference
38+
import java.io.ByteArrayInputStream
39+
import java.time.Clock
40+
import java.time.Instant
41+
import java.time.ZoneOffset
42+
43+
/**
44+
* The hello of a browser (task 4.6): without a token it authenticates with the session cookie of the upgrade request, and the
45+
* `Origin` of that request has to name the host it reached. Driven through the connection seam, with no server and no wait.
46+
*/
47+
internal class ConsoleWebSocketCookieHelloTest : AuthenticationSpecification() {
48+
49+
private val journalist = ReposiliteJournalist(InMemoryLogger(), 100, testEnv = true, noColor = true)
50+
private val sessionsSeen = mutableListOf<String>()
51+
private lateinit var handler: ConsoleWebSocketHandler
52+
53+
@BeforeEach
54+
fun createHandler() {
55+
accessTokenFacade.createAccessToken(
56+
CreateAccessTokenRequest(TEMPORARY, "browser-admin", secret = "s3cret", permissions = setOf(MANAGER))
57+
)
58+
val executor = CommandExecutor(
59+
journalist = journalist,
60+
failureFacade = FailureFacade(InMemoryLogger(), Clock.fixed(Instant.EPOCH, ZoneOffset.UTC)),
61+
source = ByteArrayInputStream(ByteArray(0)),
62+
)
63+
// A real session needs the login store, so a stand-in resolves the one cookie value the tests use.
64+
val authenticator = object : ConsoleAuthenticator(
65+
accessTokenFacade,
66+
authenticationFacade,
67+
LoginFacade(service = null, sessions = null, ownTokens = null),
68+
) {
69+
override fun authenticateSession(sessionJwt: String, ip: String): Result<AccessTokenDto, ErrorResponse> {
70+
sessionsSeen += sessionJwt
71+
return accessTokenFacade.getAccessToken("browser-admin")!!.asSuccess()
72+
}
73+
}
74+
handler = ConsoleWebSocketHandler(
75+
journalist = journalist,
76+
consoleAuthenticator = authenticator,
77+
consoleFacade = ConsoleFacade(journalist, executor),
78+
forwardedIp = Reference.reference("X-Forwarded-For"),
79+
audit = {},
80+
scheduler = FakeConsoleScheduler(),
81+
nodeId = "node-a",
82+
)
83+
}
84+
85+
@AfterEach
86+
fun shutDownJournalist() {
87+
journalist.shutdown()
88+
}
89+
90+
@Test
91+
fun `accepts a hello without a token when the cookie session and the origin name the host`() {
92+
// given: a browser that sends its session cookie and an Origin of the host it reached
93+
val connection = browser(origin = "https://repo.example.org", host = "repo.example.org")
94+
95+
// when: it says hello without a token
96+
handler.handleMessage(connection, HELLO)
97+
98+
// then: the session of the cookie was checked and the welcome follows
99+
assertThat(sessionsSeen).`as`("sessions checked").containsExactly("jwt-of-browser")
100+
assertThat(connection.json.first()).`as`("first frame").isInstanceOf(WelcomeFrame::class.java)
101+
assertThat(connection.closeCode).`as`("close code").isNull()
102+
}
103+
104+
@Test
105+
fun `accepts an origin with a port that equals the host with its port`() {
106+
val connection = browser(origin = "http://localhost:8080", host = "localhost:8080")
107+
108+
handler.handleMessage(connection, HELLO)
109+
110+
assertThat(connection.json.first()).`as`("first frame").isInstanceOf(WelcomeFrame::class.java)
111+
}
112+
113+
@Test
114+
fun `closes a cookie hello whose origin names another site with 1008 and unauthorized`() {
115+
val connection = browser(origin = "https://evil.example.net", host = "repo.example.org")
116+
117+
handler.handleMessage(connection, HELLO)
118+
119+
assertThat((connection.json.single() as ErrorFrame).code).`as`("error code").isEqualTo("unauthorized")
120+
assertThat(connection.closeCode).`as`("close code").isEqualTo(1008)
121+
assertThat(sessionsSeen).`as`("sessions checked before the origin was refused").isEmpty()
122+
}
123+
124+
@Test
125+
fun `closes a cookie hello without an origin with 1008`() {
126+
val connection = browser(origin = null, host = "repo.example.org")
127+
128+
handler.handleMessage(connection, HELLO)
129+
130+
assertThat(connection.closeCode).`as`("close code").isEqualTo(1008)
131+
assertThat(sessionsSeen).`as`("sessions checked").isEmpty()
132+
}
133+
134+
@Test
135+
fun `closes a cookie hello whose origin is not a URL with 1008`() {
136+
val connection = browser(origin = "null", host = "repo.example.org")
137+
138+
handler.handleMessage(connection, HELLO)
139+
140+
assertThat(connection.closeCode).`as`("close code").isEqualTo(1008)
141+
}
142+
143+
@Test
144+
fun `lets a token hello pass whatever its origin is`() {
145+
// given: a client with a token in the hello that happens to send a foreign Origin
146+
val connection = FakeConsoleConnection(origin = "https://evil.example.net", requestHost = "repo.example.org")
147+
148+
handler.handleMessage(connection, "{\"type\":\"hello\",\"protocols\":[1],\"token\":\"browser-admin:s3cret\"}")
149+
150+
// then: a page of another site cannot read the token, so the origin is not asked
151+
assertThat(connection.json.first()).`as`("first frame").isInstanceOf(WelcomeFrame::class.java)
152+
}
153+
154+
@Test
155+
fun `closes a hello without a token and without a cookie with 1008`() {
156+
val connection = FakeConsoleConnection(origin = "https://repo.example.org", requestHost = "repo.example.org")
157+
158+
handler.handleMessage(connection, HELLO)
159+
160+
assertThat((connection.json.single() as ErrorFrame).code).`as`("error code").isEqualTo("unauthorized")
161+
assertThat(connection.closeCode).`as`("close code").isEqualTo(1008)
162+
}
163+
164+
private fun browser(origin: String?, host: String) =
165+
FakeConsoleConnection(origin = origin, requestHost = host, cookies = mapOf(SessionCookies.SESSION to "jwt-of-browser"))
166+
167+
private companion object {
168+
const val HELLO = "{\"type\":\"hello\",\"protocols\":[1]}"
169+
}
170+
171+
}

0 commit comments

Comments
 (0)