Skip to content

Commit 6ec54bd

Browse files
committed
feat(console): ping version 1 sockets and close them at session expiry
A proxy in front of the server closes a socket that stays silent, so a version 1 connection now gets a WebSocket ping every 20 seconds. A ping that cannot be written drops the connection of a client that is gone. A connection that authenticated with a browser session is closed with 1008 and the error code unauthorized when that session reaches its expiry time, instead of staying open until its next command. The web server does not hand pongs to the handler, so the 60 second pong deadline is not part of this change. Signed-off-by: TheMeinerLP <github@themeinerlp.dev>
1 parent 850517c commit 6ec54bd

5 files changed

Lines changed: 249 additions & 1 deletion

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import com.reposilite.token.api.AccessTokenDto
2626
import net.onelitefeather.ingot.identity.login.LoginFacade
2727
import panda.std.Result
2828
import panda.std.asSuccess
29+
import java.time.Instant
2930

3031
/**
3132
* Decides who may open the remote console. Two ways in end at the same check, the instance admin role:
@@ -51,6 +52,10 @@ internal open class ConsoleAuthenticator(
5152
return requireConsoleArea(identity, ip)
5253
}
5354

55+
/** The time [sessionJwt] stops being valid, or null when it is not a valid session. */
56+
open fun sessionExpiry(sessionJwt: String): Instant? =
57+
loginFacade.verifySession(sessionJwt)?.expiresAt
58+
5459
/**
5560
* Whether [identity], authenticated earlier, may still use the console: the token still exists and still has the console
5661
* area, and [sessionJwt], when it came from a browser login, is still a valid session.

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ internal interface ConsoleConnection {
3939
/** Sends [value] as one JSON text frame. */
4040
fun sendJson(value: Any)
4141

42+
/** Sends a WebSocket ping control frame. */
43+
fun ping()
44+
4245
/** Drops the connection without a close handshake. */
4346
fun disconnect()
4447

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

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,9 @@ private val SUPPORTED_PROTOCOLS = setOf(PROTOCOL_VERSION)
8686
/** How long a dangerous command waits for its confirm before it is declined. */
8787
private val CONFIRM_DEADLINE: Duration = Duration.ofSeconds(120)
8888

89+
/** How often the server pings a version 1 connection, so a proxy in front never sees it idle. */
90+
private val PING_INTERVAL: Duration = Duration.ofSeconds(20)
91+
8992
/** The largest version 1 frame, in UTF-8 bytes. */
9093
private const val MAX_FRAME_BYTES = 4096
9194

@@ -114,6 +117,24 @@ private class V1Session(val identity: WsIdentity, val outbox: ConsoleV1Outbox, v
114117

115118
private var pending: PendingConfirm? = null
116119

120+
/** True once the session is released or closed, so a timer that is already running starts nothing new. */
121+
@Volatile
122+
var closed: Boolean = false
123+
private set
124+
125+
private var liveness: ConsoleTimer? = null
126+
private var expiry: ConsoleTimer? = null
127+
128+
@Synchronized
129+
fun trackLiveness(timer: ConsoleTimer) {
130+
liveness = timer
131+
}
132+
133+
@Synchronized
134+
fun trackExpiry(timer: ConsoleTimer) {
135+
expiry = timer
136+
}
137+
117138
@Synchronized
118139
fun isBusy(): Boolean = pending != null
119140

@@ -134,8 +155,11 @@ private class V1Session(val identity: WsIdentity, val outbox: ConsoleV1Outbox, v
134155
/** Drops the pending command without running it, when the connection is released. */
135156
@Synchronized
136157
fun dropAll() {
158+
closed = true
137159
pending?.deadline?.cancel()
138160
pending = null
161+
liveness?.cancel()
162+
expiry?.cancel()
139163
}
140164

141165
}
@@ -360,7 +384,10 @@ internal class ConsoleWebSocketHandler(
360384
outbox.offerLog(LogLine(seq = line.seq, node = line.node ?: nodeId, level = line.level.name, text = line.text))
361385
}
362386
}
363-
v1Sessions[connection] = V1Session(identity, outbox, subscriberId)
387+
val session = V1Session(identity, outbox, subscriberId)
388+
v1Sessions[connection] = session
389+
scheduleLiveness(connection, session)
390+
identity.sessionJwt?.let { jwt -> scheduleExpiry(connection, session, jwt) }
364391
}
365392
.onError {
366393
journalist.logger.info("CLI | ${it.message} (${it.status})")
@@ -384,6 +411,43 @@ internal class ConsoleWebSocketHandler(
384411
return authority != null && authority.equals(host, ignoreCase = true)
385412
}
386413

414+
/**
415+
* Pings every [PING_INTERVAL]. A proxy in front of the server closes a connection that stays silent, and a ping that cannot
416+
* be written drops the connection of a client that is gone. The web server does not hand its pongs to the handler, so the
417+
* server cannot tell a client that never answers from one that does.
418+
*/
419+
private fun scheduleLiveness(connection: ConsoleConnection, session: V1Session) {
420+
session.trackLiveness(
421+
scheduler.schedule(PING_INTERVAL) {
422+
if (session.closed) {
423+
return@schedule
424+
}
425+
try {
426+
connection.ping()
427+
} catch (failure: Exception) {
428+
handleSendFailure(connection, session.identity.identifier, failure)
429+
return@schedule
430+
}
431+
scheduleLiveness(connection, session)
432+
}
433+
)
434+
}
435+
436+
/** Closes the connection with 1008 when the browser session it authenticated with reaches its expiry time. */
437+
private fun scheduleExpiry(connection: ConsoleConnection, session: V1Session, sessionJwt: String) {
438+
val expiresAt = consoleAuthenticator.sessionExpiry(sessionJwt) ?: return
439+
val delay = Duration.between(scheduler.clock.instant(), expiresAt).coerceAtLeast(Duration.ZERO)
440+
session.trackExpiry(
441+
scheduler.schedule(delay) {
442+
if (session.closed) {
443+
return@schedule
444+
}
445+
journalist.logger.info("CLI | the session of ${session.identity.identifier} expired")
446+
closeSession(connection, session, CLOSE_POLICY_VIOLATION, ErrorFrame(code = "unauthorized", message = "the session has expired"))
447+
}
448+
)
449+
}
450+
387451
/** The level of the log lines a hello asks for. It can raise the visible threshold but never lower it. */
388452
private fun levelOf(hello: JsonNode): Channel {
389453
val visible = journalist.visibleThreshold
@@ -585,6 +649,7 @@ internal class ConsoleWebSocketHandler(
585649
override fun cookie(name: String): String? = ctx.cookie(name)
586650
override fun send(text: String) = ctx.send(text)
587651
override fun sendJson(value: Any) = ctx.send(value)
652+
override fun ping() = ctx.sendPing()
588653
override fun disconnect() = ctx.session.disconnect()
589654
override fun close(code: Int, reason: String) {
590655
ctx.closeSession(code, reason)

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,15 @@ internal class FakeConsoleConnection(
2727
override val origin: String? = null,
2828
override val requestHost: String? = null,
2929
private val cookies: Map<String, String> = emptyMap(),
30+
private val failPing: Boolean = false,
3031
) : ConsoleConnection {
3132

3233
override fun cookie(name: String): String? = cookies[name]
3334

3435
val texts = mutableListOf<String>()
3536
val json = mutableListOf<Any>()
37+
var pings = 0
38+
private set
3639
var disconnected = false
3740
private set
3841
var closeCode: Int? = null
@@ -48,6 +51,13 @@ internal class FakeConsoleConnection(
4851
json += value
4952
}
5053

54+
override fun ping() {
55+
pings++
56+
if (failPing) {
57+
throw java.io.IOException("the socket is gone")
58+
}
59+
}
60+
5161
override fun disconnect() {
5262
disconnected = true
5363
}
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
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.Duration
41+
import java.time.Instant
42+
import java.time.ZoneOffset
43+
44+
/**
45+
* The liveness of a version 1 connection (task 4.7): a ping every 20 seconds, and a close at the expiry time of a browser session. The timers run on the fake scheduler, so no test waits.
46+
*/
47+
internal class ConsoleWebSocketLivenessTest : AuthenticationSpecification() {
48+
49+
private val journalist = ReposiliteJournalist(InMemoryLogger(), 100, testEnv = true, noColor = true)
50+
private val scheduler = FakeConsoleScheduler()
51+
private lateinit var handler: ConsoleWebSocketHandler
52+
53+
@BeforeEach
54+
fun createHandler() {
55+
accessTokenFacade.createAccessToken(
56+
CreateAccessTokenRequest(TEMPORARY, "deploy-bot", 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 accepts the one cookie value the tests use and ends it at a fixed time.
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+
accessTokenFacade.getAccessToken("deploy-bot")!!.asSuccess()
71+
72+
override fun sessionExpiry(sessionJwt: String): Instant? = Instant.EPOCH.plus(SESSION_LIFETIME)
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 = scheduler,
81+
nodeId = "node-a",
82+
)
83+
}
84+
85+
@AfterEach
86+
fun shutDownJournalist() {
87+
journalist.shutdown()
88+
}
89+
90+
@Test
91+
fun `sends a ping every 20 seconds`() {
92+
val connection = connected()
93+
94+
scheduler.advance(Duration.ofSeconds(19))
95+
assertThat(connection.pings).`as`("pings after 19 seconds").isEqualTo(0)
96+
97+
scheduler.advance(Duration.ofSeconds(1))
98+
assertThat(connection.pings).`as`("pings after 20 seconds").isEqualTo(1)
99+
100+
scheduler.advance(Duration.ofSeconds(20))
101+
assertThat(connection.pings).`as`("pings after 40 seconds").isEqualTo(2)
102+
}
103+
104+
@Test
105+
fun `drops a connection whose ping cannot be written and pings it no more`() {
106+
val connection = FakeConsoleConnection(failPing = true)
107+
handler.handleMessage(connection, "{\"type\":\"hello\",\"protocols\":[1],\"token\":\"deploy-bot:s3cret\"}")
108+
109+
scheduler.advance(Duration.ofSeconds(20))
110+
scheduler.advance(Duration.ofSeconds(20))
111+
112+
assertThat(connection.disconnected).`as`("disconnected").isTrue()
113+
assertThat(connection.pings).`as`("ping attempts").isEqualTo(1)
114+
}
115+
116+
@Test
117+
fun `sends no ping to a connection that was released`() {
118+
val connection = connected()
119+
120+
handler.release(connection)
121+
scheduler.advance(Duration.ofMinutes(5))
122+
123+
assertThat(connection.pings).`as`("pings after the release").isEqualTo(0)
124+
assertThat(connection.closeCode).`as`("close code after the release").isNull()
125+
}
126+
127+
@Test
128+
fun `closes a browser session at its expiry with 1008 and unauthorized`() {
129+
val connection = FakeConsoleConnection(
130+
origin = "https://repo.example.org",
131+
requestHost = "repo.example.org",
132+
cookies = mapOf(SessionCookies.SESSION to "jwt-of-browser"),
133+
)
134+
handler.handleMessage(connection, "{\"type\":\"hello\",\"protocols\":[1]}")
135+
connection.json.clear()
136+
scheduler.advance(Duration.ofSeconds(SESSION_LIFETIME.seconds - 1))
137+
assertThat(connection.closeCode).`as`("close code before the expiry").isNull()
138+
139+
scheduler.advance(Duration.ofSeconds(1))
140+
141+
assertThat((connection.json.last() as ErrorFrame).code).`as`("error code").isEqualTo("unauthorized")
142+
assertThat(connection.closeCode).`as`("close code at the expiry").isEqualTo(1008)
143+
}
144+
145+
@Test
146+
fun `leaves a token connection open past the time a session would expire`() {
147+
val connection = connected()
148+
149+
scheduler.advance(SESSION_LIFETIME.plusSeconds(60))
150+
151+
assertThat(connection.closeCode).`as`("close code").isNull()
152+
}
153+
154+
private fun connected(): FakeConsoleConnection {
155+
val connection = FakeConsoleConnection()
156+
handler.handleMessage(connection, "{\"type\":\"hello\",\"protocols\":[1],\"token\":\"deploy-bot:s3cret\"}")
157+
assertThat(connection.json.first()).`as`("first frame").isInstanceOf(WelcomeFrame::class.java)
158+
return connection
159+
}
160+
161+
private companion object {
162+
val SESSION_LIFETIME: Duration = Duration.ofMinutes(5)
163+
}
164+
165+
}

0 commit comments

Comments
 (0)