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
8 changes: 8 additions & 0 deletions docs/developer-guide/Backend-Scheduling.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,14 @@ A skipped run isn't a failure. A lock that can't be claimed for any other reason
the database refusing the statement -- is recorded as one, so a broken lock table
doesn't look like a job that's always somebody else's turn.

==== Turning every job off

`cn1.scheduler.enabled=false` keeps every scheduled job from starting. It's meant
for a server pointed at a copy of production data for a read-only preview, where
push dispatch, billing polls and exports must not run. The jobs are still listed
under `/manage/jobs`, and starting one by hand with `backend_run_job` still runs it.
The server prints one line at start-up saying how many jobs it held back.

==== Watching the jobs

A job is named after its class's simple name and its method, `Cleanup.run`. When
Expand Down
17 changes: 13 additions & 4 deletions docs/developer-guide/Backend-Security.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,13 @@ token or an API key gets a 401 with the reason in `WWW-Authenticate`. A chain
with no way of signing in answers 403. A signed-in caller that's denied gets a
403. Change either one with `exceptionHandling`:

`new HttpStatusEntryPoint(401)` answers with the status and a body in the shape of
Spring Boot's default error body,
`{"timestamp":"...","status":401,"error":"Unauthorized","path":"/api/me"}`, so a
client that reads the error body learns why it was refused. Spring's entry point
sends no body at all; a Codename One client's `RequestBuilder` needs one to report
the error.

[source,java,role=cn1-no-try]
----
include::../demos/backend/src/main/java/com/codenameone/developerguide/backend/security/SecuritySnippets.java[tag=backend-security-handling,indent=0]
Expand Down Expand Up @@ -1494,10 +1501,12 @@ It also carries `nonce`, `auth_time`, `azp` and `at_hash`. Without a
`email` scope yields nothing, because the server doesn't know that a username
is an address.

Authorizing a client or approving a device requires a sign-in stored in the
current HTTP session. API keys, bearer tokens, HTTP Basic credentials and
authentication restored from a remembered sign-in don't satisfy this check. Sign in through the
chain's form, OAuth2 login or passkey flow first.
Authorizing a client or approving a device requires a browser sign-in: one
stored in the current HTTP session, or one restored from a remembered sign-in, as
Spring Authorization Server accepts. A silent refresh (`prompt=none` in a hidden
frame) therefore keeps working for a remembered user after the session is gone.
API keys, bearer tokens and HTTP Basic credentials don't satisfy this check. Sign
in through the chain's form, OAuth2 login or passkey flow first.

The authorization endpoint returns `login_required` for `prompt=login`,
`max_age=0`, or a session whose last credential check is older than `max_age`.
Expand Down
16 changes: 14 additions & 2 deletions docs/developer-guide/Backend-Sessions.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,14 @@ browser closes; how long the session lasts is the server's decision.
Anything else stops the server at start-up.
|===

An application ported from Spring Boot can keep its own keys. When the
`cn1.session.*` key is unset, `server.servlet.session.timeout` sets the timeout as
a Boot duration (`1800`, `30m`, `12h`, `7d` or `PT30M`), the
`server.servlet.session.cookie.name`, `.same-site` and `.secure` keys set the
cookie, and `spring.session.store-type` picks the store (`jdbc` is `db`, `redis`
is `kv`, `none` is `memory`). The server prints a line at start-up for any other
`server.servlet.session.*` key, such as `persistent`, because it does nothing here.

=== Where sessions are kept

`cn1.session.store=memory` keeps sessions in the server's own memory. It needs
Expand All @@ -150,8 +158,12 @@ called `cn1_http_session` that the server creates on first use. Every instance o
the server then sees every session, a restart loses nothing, and a deployment can
add or replace instances at will. The price is in what an attribute can be: the
attributes are stored as JSON, so a value must be a string, a number, a boolean, or
a map or list of those. Anything else is written as JSON can write it and read back
as whatever JSON reads, which isn't the object that was stored.
a map or list of those, or a class the build has written a JSON codec for. The
build writes one for the type of every value passed to `setAttribute`, so a record
or a plain class put in the session is stored as its fields. It comes back as the
JSON tree, a `Map`; `getAttribute(name, Type.class)` reads it into the class, and
under the memory store it returns the stored object, so code that uses it works
with every store.

Each row belongs to a namespace, and a server only reads the rows of its own.
By default the namespace is empty, so every server that uses the database shares
Expand Down
2 changes: 1 addition & 1 deletion docs/developer-guide/Backend-Views.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ HTML controllers doesn't enable a security chain automatically.
Files in `src/main/resources/static` are embedded at build time and served under
`/static/` after controller routes. Only enumerated assets are accessible; templates
are private. Embedded assets use `Cache-Control: no-cache` and `nosniff`. Use URL-safe
ASCII filenames. Each embedded asset is limited to 2 MiB; use the existing
ASCII filenames. Each embedded asset is limited to 32 MiB; use the existing
`cn1.static.root` facility for larger files.

=== Building and porting
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.backend;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.IOException;
import java.util.Properties;
import org.junit.jupiter.api.Test;

/// Issue 6353: Spring Boot's session keys are read when the cn1.session.* key
/// is unset.
class SessionsSpringKeysTest {
private static Config config(String... pairs) {
Properties p = new Properties();
for (int i = 0; i < pairs.length; i += 2) {
p.setProperty(pairs[i], pairs[i + 1]);
}
return Config.of(p, "test");
}

@Test
void durationsReadAsBootReadsThem() {
assertEquals(1800, Sessions.durationSeconds("1800"));
assertEquals(30, Sessions.durationSeconds("30s"));
assertEquals(1800, Sessions.durationSeconds("30m"));
assertEquals(43200, Sessions.durationSeconds("12h"));
assertEquals(7 * 86400, Sessions.durationSeconds("7d"));
assertEquals(1, Sessions.durationSeconds("500ms"));
assertEquals(1800, Sessions.durationSeconds("PT30M"));
assertEquals(86400 + 3600 + 1, Sessions.durationSeconds("P1DT1H0.5S"));
assertEquals(-1, Sessions.durationSeconds("thirty"));
assertEquals(-1, Sessions.durationSeconds("30w"));
assertEquals(-1, Sessions.durationSeconds("P1DT"));
assertEquals(86400, Sessions.durationSeconds("P1D"));
// Would wrap a long in seconds.
assertEquals(-1, Sessions.durationSeconds("999999999999999d"));
assertEquals(-1, Sessions.durationSeconds("PT"));
}

@Test
void springKeysApplyAndOwnKeysWin() throws IOException {
Sessions s = Sessions.configure(config("server.servlet.session.timeout", "12h",
"server.servlet.session.cookie.name", "SESSION",
"spring.session.store-type", "none"), false, null, null);
assertEquals(43200, Sessions.timeout(config("server.servlet.session.timeout", "12h")));
assertEquals(60, Sessions.timeout(config("server.servlet.session.timeout", "12h",
"cn1.session.timeout", "60")));
assertEquals(1800, Sessions.timeout(config()));
assertEquals("db", Sessions.store(config("spring.session.store-type", "jdbc")));
assertEquals("kv", Sessions.store(config("spring.session.store-type", "redis")));
assertEquals("memory", Sessions.store(config("spring.session.store-type", "jdbc",
"cn1.session.store", "memory")));
assertEquals("SESSION", Sessions.setting(config("server.servlet.session.cookie.name",
"SESSION"), "cn1.session.cookie", "server.servlet.session.cookie.name", "X"));
assertThrows(IOException.class, () -> Sessions.configure(
config("server.servlet.session.timeout", "soon"), false, null, null));
assertThrows(IOException.class, () -> Sessions.configure(
config("server.servlet.session.timeout", "1h", "spring.session.store-type",
"jdbc"), false, null, null));
s.close();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,41 @@ void statelessCredentialsCannotAuthorizeUserGrants(boolean apiKey) throws Except
}
}

/// Issue 6353: once the session is gone, a silent refresh (prompt=none)
/// from a browser holding a valid remember-me cookie gets a code, as it did
/// under Spring Authorization Server, instead of login_required.
@Test
void rememberedBrowserAuthorizesWithoutASession() throws Exception {
InMemoryUserDetailsManager users = new InMemoryUserDetailsManager(
User.withUsername("ada").password("{noop}ada-pw").roles("USER").build());
final com.codename1.backend.security.rememberme.PersistentTokenBasedRememberMeServices
services = new com.codename1.backend.security.rememberme
.PersistentTokenBasedRememberMeServices("key", users,
new com.codename1.backend.security.rememberme.InMemoryTokenRepositoryImpl());
Properties settings = SecuredServer.settings();
settings.setProperty(AuthorizationServerSettings.ISSUER, "https://issuer.example.com");
final RegisteredClientRepository clients = clients();
try (SecuredServer server = SecuredServer.start(settings, "test", new Object[] {users}, APP,
http -> http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.csrf(csrf -> csrf.disable()).formLogin(Customizer.withDefaults())
.rememberMe(remember -> remember.rememberMeServices(services))
.authorizationServer(as -> as.registeredClientRepository(clients)
.authorizationService(grants).clientSecretEncoder(OAuth2Testing.PLAIN))
.build())) {
String url = authorizeUrl("app", APP_REDIRECT, "openid orders:read",
OAuth2Parameters.random(32), "state", "nonce") + "&prompt=none";
server.post("/login", "username=ada&password=ada-pw&remember-me=on");
assertNotNull(server.cookies.get("remember-me"));
server.cookies.remove("CN1SESSION");
java.util.Map<String, String> answer = query(server.get(url).header("Location"));
assertNull(answer.get("error"), String.valueOf(answer));
assertNotNull(answer.get("code"), String.valueOf(answer));

server.cookies.clear();
assertEquals("login_required", query(server.get(url).header("Location")).get("error"));
}
}

@Test
void authenticationMethodsNameHowTheUserSignedIn() {
java.util.List<GrantedAuthority> none = java.util.Collections.emptyList();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.backend.security;

import static org.junit.jupiter.api.Assertions.assertEquals;

import com.codename1.backend.Json;
import java.util.Map;
import org.junit.jupiter.api.Test;

/// Issue 6353: the entry point answers with Spring Boot's default error body.
class HttpStatusEntryPointTest {
@Test
void bodyHasBootsShape() throws Exception {
Map<String, Object> body = Json.parseObject(
HttpStatusEntryPoint.errorBody(401, "/api/me", 0L));
assertEquals("1970-01-01T00:00:00.000+00:00", body.get("timestamp"));
assertEquals(401, ((Number) body.get("status")).intValue());
assertEquals("Unauthorized", body.get("error"));
assertEquals("/api/me", body.get("path"));
assertEquals(4, body.size());
}

@Test
void timestampsAreUtcIso() {
assertEquals("2026-11-29T13:05:07.042+00:00",
HttpStatusEntryPoint.timestamp(1795957507042L));
assertEquals("2000-02-29T23:59:59.999+00:00",
HttpStatusEntryPoint.timestamp(951868799999L));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.impl.backend;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.codename1.backend.Config;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;

/// Issue 6353: cn1.scheduler.enabled=false keeps every job from running.
class SchedulerSwitchTest {
@Test
void disabledSchedulerRunsNothing() throws Exception {
Properties settings = new Properties();
settings.setProperty("cn1.scheduler.enabled", "false");
Scheduler scheduler = new Scheduler(null);
scheduler.configure(Config.of(settings, "test"));
final AtomicInteger runs = new AtomicInteger();
scheduler.fixedRate("tick", 0, 10, null, 0, null, 0, new Runnable() {
@Override
public void run() {
runs.incrementAndGet();
}
});
scheduler.start();
Thread.sleep(300);
assertEquals(0, runs.get());
// A deliberate manual trigger still runs a held-back job.
assertTrue(scheduler.trigger("tick"));
for (int i = 0; i < 100 && runs.get() == 0; i++) {
Thread.sleep(20);
}
scheduler.stop(1000);
assertEquals(1, runs.get());
assertEquals(1, scheduler.getJobs().size());
}
}
Loading
Loading