diff --git a/docs/developer-guide/Backend-Scheduling.asciidoc b/docs/developer-guide/Backend-Scheduling.asciidoc index 3a9057be697..f0123bf79bc 100644 --- a/docs/developer-guide/Backend-Scheduling.asciidoc +++ b/docs/developer-guide/Backend-Scheduling.asciidoc @@ -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 diff --git a/docs/developer-guide/Backend-Security.asciidoc b/docs/developer-guide/Backend-Security.asciidoc index 27641a1e379..5ef2824b435 100644 --- a/docs/developer-guide/Backend-Security.asciidoc +++ b/docs/developer-guide/Backend-Security.asciidoc @@ -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] @@ -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`. diff --git a/docs/developer-guide/Backend-Sessions.asciidoc b/docs/developer-guide/Backend-Sessions.asciidoc index c84c7593854..cef9314d893 100644 --- a/docs/developer-guide/Backend-Sessions.asciidoc +++ b/docs/developer-guide/Backend-Sessions.asciidoc @@ -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 @@ -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 diff --git a/docs/developer-guide/Backend-Views.asciidoc b/docs/developer-guide/Backend-Views.asciidoc index a6533d06940..2dfae7d985f 100644 --- a/docs/developer-guide/Backend-Views.asciidoc +++ b/docs/developer-guide/Backend-Views.asciidoc @@ -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 diff --git a/maven/backend/src/test/java/com/codename1/backend/SessionsSpringKeysTest.java b/maven/backend/src/test/java/com/codename1/backend/SessionsSpringKeysTest.java new file mode 100644 index 00000000000..0810164ac96 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/backend/SessionsSpringKeysTest.java @@ -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(); + } +} diff --git a/maven/backend/src/test/java/com/codename1/backend/security/AuthorizationServerTest.java b/maven/backend/src/test/java/com/codename1/backend/security/AuthorizationServerTest.java index e67486d4de1..b70a11b6a51 100644 --- a/maven/backend/src/test/java/com/codename1/backend/security/AuthorizationServerTest.java +++ b/maven/backend/src/test/java/com/codename1/backend/security/AuthorizationServerTest.java @@ -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 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 none = java.util.Collections.emptyList(); diff --git a/maven/backend/src/test/java/com/codename1/backend/security/HttpStatusEntryPointTest.java b/maven/backend/src/test/java/com/codename1/backend/security/HttpStatusEntryPointTest.java new file mode 100644 index 00000000000..717f4dcb175 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/backend/security/HttpStatusEntryPointTest.java @@ -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 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)); + } +} diff --git a/maven/backend/src/test/java/com/codename1/impl/backend/SchedulerSwitchTest.java b/maven/backend/src/test/java/com/codename1/impl/backend/SchedulerSwitchTest.java new file mode 100644 index 00000000000..71ad9eecd10 --- /dev/null +++ b/maven/backend/src/test/java/com/codename1/impl/backend/SchedulerSwitchTest.java @@ -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()); + } +} diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/JsonCallSites.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/JsonCallSites.java index 244128779c7..ee920038010 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/JsonCallSites.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/JsonCallSites.java @@ -53,6 +53,7 @@ final class JsonCallSites { private static final String JSON = "com/codename1/backend/Json"; private static final String TEMPLATE = "com/codename1/backend/messaging/MessageTemplate"; + private static final String SESSION = "com/codename1/backend/HttpSession"; private JsonCallSites() { } @@ -132,7 +133,11 @@ private static final class Sites extends MethodVisitor { /// The local the last instruction loaded, or -1. private int lastLocal = -1; private final List writtenLocals = new ArrayList(); + private final List sessionLocals = new ArrayList(); private final Map> localTypes = new HashMap>(); + /// NEWs whose constructor has not been called yet: an `` with + /// none pending is a `super(..)` or `this(..)` and leaves nothing. + private int pendingNew; Sites(ProcessorContext ctx, BackendJsonCodecs codecs, AnnotatedClass cls, String method) { super(Opcodes.ASM9); @@ -168,6 +173,9 @@ public void visitVarInsn(int opcode, int var) { @Override public void visitTypeInsn(int opcode, String type) { + if (opcode == Opcodes.NEW) { + pendingNew++; + } pushed(opcode == Opcodes.CHECKCAST ? objectType(Type.getObjectType(type)) : null); } @@ -191,6 +199,26 @@ public void visitMethodInsn(int opcode, String owner, String name, String desc, use(last, false, "write"); } } + if (opcode == Opcodes.INVOKEVIRTUAL && SESSION.equals(owner)) { + // A session attribute is JSON in the database and key/value + // stores, so its class needs a codec there -- and without one + // the request failed at run time, only once a deployment + // switched stores (issue 6353). Registered leniently: under the + // memory store any object is a valid attribute, so a class that + // cannot be JSON is not a build error here. + if ("setAttribute".equals(name) + && "(Ljava/lang/String;Ljava/lang/Object;)V".equals(desc)) { + if (lastLocal >= 0) { + sessionLocals.add(Integer.valueOf(lastLocal)); + } else if (last != null) { + session(last); + } + } else if ("getAttribute".equals(name) + && "(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;".equals(desc) + && last != null) { + codecs.typedUse(last, true); + } + } if (opcode == Opcodes.INVOKESTATIC && JSON.equals(owner)) { if (("read".equals(name) || "readList".equals(name)) && "(Ljava/lang/String;Ljava/lang/Class;)".equals(params(desc)) @@ -206,7 +234,23 @@ public void visitMethodInsn(int opcode, String owner, String name, String desc, } } } - pushed(objectType(Type.getReturnType(desc))); + if (opcode == Opcodes.INVOKESPECIAL && "".equals(name)) { + // NEW; DUP; args; leaves the new object on the stack, so + // `setAttribute("k", new Visit(..))` or `Json.write(new Reply(..))` + // names its class here rather than nothing. An anonymous or + // local class -- `new HashMap<..>() {{ put(..); }}` -- names + // nothing: Json writes it by its JDK supertype, as it did before + // constructors were typed, and checking it as an application + // class would fail a build that runs. + String made = null; + if (pendingNew > 0) { + pendingNew--; + made = anonymousOrLocal(owner) ? null : objectType(Type.getObjectType(owner)); + } + pushed(made); + } else { + pushed(objectType(Type.getReturnType(desc))); + } } @Override @@ -257,6 +301,16 @@ private void local(int index, String type) { @Override public void visitEnd() { + for (Integer local : sessionLocals) { + List types = localTypes.get(local); + if (types != null) { + for (String type : types) { + if (!type.startsWith("java.")) { + session(type); + } + } + } + } for (Integer local : writtenLocals) { List types = localTypes.get(local); if (types != null) { @@ -269,6 +323,15 @@ public void visitEnd() { } } + /// A session attribute's class: written into the db and kv stores, and + /// read back by `getAttribute(name, Class)`. Lenient, because under the + /// memory store any object is a valid attribute: a class that cannot be + /// JSON just gets no codec, and its writer does not wait on its reader. + private void session(String type) { + codecs.typedUse(type, false); + codecs.typedUse(type, true); + } + private void use(String type, boolean read, String call) { if (!read && (type == null || type.startsWith("java."))) { // Json writes the JDK's shapes itself, and an Object says nothing. @@ -284,6 +347,13 @@ private void use(String type, boolean read, String call) { } } + /// `Outer$1` or `Outer$1Local`: javac's names for anonymous and local classes. + private static boolean anonymousOrLocal(String internalName) { + int dollar = internalName.lastIndexOf('$'); + return dollar >= 0 && dollar + 1 < internalName.length() + && Character.isDigit(internalName.charAt(dollar + 1)); + } + private static String params(String desc) { return desc.substring(0, desc.indexOf(')') + 1); } diff --git a/maven/build-engine/src/main/java/com/codename1/maven/processors/MvcAssets.java b/maven/build-engine/src/main/java/com/codename1/maven/processors/MvcAssets.java index be97bfa6cc6..d672c8b6e0d 100644 --- a/maven/build-engine/src/main/java/com/codename1/maven/processors/MvcAssets.java +++ b/maven/build-engine/src/main/java/com/codename1/maven/processors/MvcAssets.java @@ -61,7 +61,7 @@ static void removeObsoleteClasses(File output, Set currentSources) if (files == null) return; for (File file : files) { String name = file.getName(); - if (!name.matches("(Views|Assets|Asset[0-9]+)\\.class")) continue; + if (!name.matches("(Views|Assets|Asset[0-9]+(_[0-9]+)?)\\.class")) continue; String type = "com.codename1.generated.mvc." + name.substring(0, name.length() - 6); if (!currentSources.contains(type) && ClassScanner.readClass(file) @@ -102,7 +102,17 @@ private static void collect( throw new IllegalArgumentException("Cannot read asset " + file, e); } checkSize(data.length, file); - String name = "Asset" + sources.size(); + int index = 0; + for (String key : sources.keySet()) + if (key.matches("com\\.codename1\\.generated\\.mvc\\.Asset[0-9]+")) index++; + // Numbered by asset, not by source: the part classes must not move + // the next asset's name, which incremental builds compare. + String name = "Asset" + index; + // One class per MiB of the asset, each with 1024 methods of 1 KiB: + // a method stays far below the JVM's 64 KiB code limit, the class + // below its method count, and load() makes one call per MiB -- so + // the size cap is a build-cost choice, not a class-file limit. + int groups = (data.length + GROUP - 1) / GROUP; StringBuilder s = new StringBuilder( "package com.codename1.generated.mvc;\n" @@ -113,26 +123,40 @@ private static void collect( + "static byte[] load() { byte[] data = new byte[" + data.length + "];\n"); - int chunks = (data.length + 1023) / 1024; - for (int chunk = 0; chunk < chunks; chunk++) - s.append("System.arraycopy(part") - .append(chunk) - .append("(), 0, data, ") - .append(chunk * 1024) - .append(", ") - .append(Math.min(1024, data.length - chunk * 1024)) - .append(");\n"); - s.append("return data; }\n"); - for (int chunk = 0; chunk < chunks; chunk++) { - s.append("static byte[] part").append(chunk).append("() { return new byte[] {"); - for (int i = chunk * 1024; i < Math.min(data.length, (chunk + 1) * 1024); i++) { - if (i > chunk * 1024) s.append(','); - s.append(data[i]); + for (int group = 0; group < groups; group++) + s.append(name).append('_').append(group).append(".fill(data);\n"); + s.append("return data; }\n}\n"); + sources.put("com.codename1.generated.mvc." + name, s.toString()); + for (int group = 0; group < groups; group++) { + String part = name + "_" + group; + int from = group * GROUP; + int to = Math.min(data.length, from + GROUP); + StringBuilder g = + new StringBuilder( + "package com.codename1.generated.mvc;\n" + + "@com.codename1.backend.annotations.Generated final class " + + part + + " {\nstatic void fill(byte[] data) {\n"); + for (int chunk = from; chunk < to; chunk += 1024) + g.append("System.arraycopy(part") + .append(chunk) + .append("(), 0, data, ") + .append(chunk) + .append(", ") + .append(Math.min(1024, to - chunk)) + .append(");\n"); + g.append("}\n"); + for (int chunk = from; chunk < to; chunk += 1024) { + g.append("static byte[] part").append(chunk).append("() { return new byte[] {"); + for (int i = chunk; i < Math.min(to, chunk + 1024); i++) { + if (i > chunk) g.append(','); + g.append(data[i]); + } + g.append("}; }\n"); } - s.append("}; }\n"); + g.append("}\n"); + sources.put("com.codename1.generated.mvc." + part, g.toString()); } - s.append("}\n"); - sources.put("com.codename1.generated.mvc." + name, s.toString()); registry.append("if(") .append(MvcForms.q(path)) .append( @@ -148,10 +172,19 @@ private static void collect( } } + /// Bytes per generated part class. + private static final int GROUP = 1024 * 1024; + + /// The largest asset embedded in the jar. It was 2 MiB, which a Codename + /// One JavaScript-port bundle outgrows (issue 6353); past this the build's + /// own cost (about four characters of source per byte) argues for serving + /// the file from disk. + static final int MAX_ASSET = 32 * 1024 * 1024; + private static void checkSize(long size, File file) { - if (size > 2 * 1024 * 1024) + if (size > MAX_ASSET) throw new IllegalArgumentException( - "Embedded MVC assets must be at most 2 MiB; serve larger files with" + "Embedded MVC assets must be at most 32 MiB; serve larger files with" + " cn1.static.root: " + file); } diff --git a/maven/build-engine/src/test/java/com/codename1/maven/processors/MvcTemplatesTest.java b/maven/build-engine/src/test/java/com/codename1/maven/processors/MvcTemplatesTest.java index ab3de49ad1c..bb533ce35ea 100644 --- a/maven/build-engine/src/test/java/com/codename1/maven/processors/MvcTemplatesTest.java +++ b/maven/build-engine/src/test/java/com/codename1/maven/processors/MvcTemplatesTest.java @@ -375,6 +375,34 @@ public void packagedAssetsAreExactAndTemplatesArePrivate() throws Exception { assertNull(assets.handle(request("POST", "/static/probe.bin", null, false))); } + /// Issue 6353: an asset past the old 2 MiB cap (a JavaScript-port bundle) + /// is embedded across several part classes and served byte for byte. + @Test + public void assetsLargerThanOneGroupAreEmbeddedExactly() throws Exception { + setup(); + File asset = new File(project, "src/main/resources/static/bundle.js"); + asset.getParentFile().mkdirs(); + byte[] data = new byte[3 * 1024 * 1024 + 17]; + java.util.Random random = new java.util.Random(6353); + random.nextBytes(data); + Files.write(asset.toPath(), data); + java.util.Map sources = MvcAssets.sources(project); + assertTrue(sources.containsKey("com.codename1.generated.mvc.Asset0_3")); + JavaSourceCompiler.compile(sources, classes, classpath()); + loader = + new URLClassLoader( + new URL[] {classes.toURI().toURL()}, getClass().getClassLoader()); + HttpServer.Handler assets = + (HttpServer.Handler) + loader.loadClass("com.codename1.generated.mvc.Assets").newInstance(); + assertArrayEquals( + data, + (byte[]) + field( + assets.handle(request("GET", "/static/bundle.js", null, false)), + "body")); + } + @Test public void nullsBooleanAttributesAndUnsafeContexts() throws Exception { setup(); @@ -1170,7 +1198,7 @@ public void hugeAssetsAreRejectedBeforeAllocation() throws Exception { MvcAssets.sources(project); fail("Oversize asset accepted"); } catch (IllegalArgumentException expected) { - assertTrue(expected.getMessage().contains("2 MiB")); + assertTrue(expected.getMessage().contains("32 MiB")); } catch (OutOfMemoryError allocation) { fail("Asset size was not checked before allocation"); } diff --git a/maven/build-engine/src/test/java/com/codename1/maven/processors/RestControllerAnnotationProcessorTest.java b/maven/build-engine/src/test/java/com/codename1/maven/processors/RestControllerAnnotationProcessorTest.java index e9337558040..5f18d27698e 100644 --- a/maven/build-engine/src/test/java/com/codename1/maven/processors/RestControllerAnnotationProcessorTest.java +++ b/maven/build-engine/src/test/java/com/codename1/maven/processors/RestControllerAnnotationProcessorTest.java @@ -1807,6 +1807,64 @@ public void registeredClassesGetCodecsNoCallSiteNames() throws Exception { } } + @Test + public void sessionAttributeClassesGetCodecs() throws Exception { + // Issue 6353: a record put in the session failed at run time under + // cn1.session.store=db ("No JSON codec"), only once a deployment + // switched stores. setAttribute's argument type now gets a codec, and + // getAttribute(name, Class) reads the stored tree back into it. + Map sources = new LinkedHashMap(); + sources.put("com.example.FirstTouch", "package com.example;\n" + + "public class FirstTouch { public String source; public int visits;\n" + + " public FirstTouch() {}\n" + + " public FirstTouch(String s, int v) { source = s; visits = v; } }\n"); + sources.put("com.example.Stamp", "package com.example;\n" + + "public class Stamp { private final String id;\n" + + " public Stamp(String id) { this.id = id; }\n" + + " public String getId() { return id; } }\n"); + sources.put("com.example.Opaque", "package com.example;\n" + + "public class Opaque { private final Thread t = null; }\n"); + sources.put("com.example.Track", "package com.example;\n" + + "import com.codename1.backend.annotations.*;\n" + + "@RestController\n" + + "public class Track {\n" + + " @GetMapping(\"/t\")\n" + + " public String t(com.codename1.backend.HttpServer.Request request) {\n" + + " com.codename1.backend.HttpSession s = request.getSession(true);\n" + + " s.setAttribute(\"touch\", new FirstTouch(\"ad\", 2));\n" + + " // Not JSON-able, and still not a build error: memory sessions\n" + + " // hold any object.\n" + + " s.setAttribute(\"opaque\", new Opaque());\n" + + " // Writable but not readable: the stores still need its writer.\n" + + " s.setAttribute(\"stamp\", new Stamp(\"x\"));\n" + + " // Double-brace: Json writes it as the Map it extends.\n" + + " return com.codename1.backend.Json.write(\n" + + " new java.util.HashMap() {{ put(\"a\", 1); }});\n" + + " }\n" + + "}\n"); + File classes = tmp.newFolder(); + JavaSourceCompiler.compile(sources, classes, backendClasspath()); + ProcessorContext ctx = run(classes); + assertFalse(ctx.getErrors().toString(), ctx.hasErrors()); + URLClassLoader loader = new URLClassLoader(new URL[]{ classes.toURI().toURL() }, + getClass().getClassLoader()); + com.codename1.impl.backend.JsonCodec.install((com.codename1.impl.backend.JsonCodec.Registry) + loader.loadClass("cn1app.JsonCodecs").newInstance()); + try { + Object touch = loader.loadClass("com.example.FirstTouch") + .getConstructor(String.class, int.class).newInstance("ad", 2); + String json = com.codename1.backend.Json.write(touch); + assertEquals("{\"source\":\"ad\",\"visits\":2}", json); + assertEquals("{\"id\":\"x\"}", com.codename1.backend.Json.write( + loader.loadClass("com.example.Stamp").getConstructor(String.class).newInstance("x"))); + Object back = com.codename1.backend.Json.convert( + com.codename1.backend.Json.parse(json), touch.getClass()); + assertEquals(json, com.codename1.backend.Json.write(back)); + } finally { + com.codename1.impl.backend.JsonCodec.install(null); + } + } + @Test public void aParameterWithTwoBindingAnnotationsIsRefused() throws Exception { // The binding chain is priority-ordered, so this used to bind the header diff --git a/vm/backend/src/com/codename1/backend/HttpServer.java b/vm/backend/src/com/codename1/backend/HttpServer.java index 60651020b17..59cad0b3681 100644 --- a/vm/backend/src/com/codename1/backend/HttpServer.java +++ b/vm/backend/src/com/codename1/backend/HttpServer.java @@ -10567,6 +10567,12 @@ private static boolean sliceEquals(byte[] data, int start, int length, byte[] as return true; } + /// The reason phrase of a status (`401` -> `Unauthorized`), as written on + /// the status line and in the `error` member of a default error body. + public static String reasonPhrase(int status) { + return reason(status); + } + /// The reason phrase of a status, as RFC 9110 and the registry it points to /// have it. Nothing reads the phrase, but a status line that says /// `302 OK` is the first thing anybody debugging with curl sees. diff --git a/vm/backend/src/com/codename1/backend/HttpSession.java b/vm/backend/src/com/codename1/backend/HttpSession.java index 3bd6ec99da5..d140fae6d59 100644 --- a/vm/backend/src/com/codename1/backend/HttpSession.java +++ b/vm/backend/src/com/codename1/backend/HttpSession.java @@ -119,6 +119,29 @@ public synchronized Object getAttribute(String name) { return attributes.get(name); } + /// The attribute as a `type`, whichever store holds the session. + /// + /// The memory store hands back the object that was set; the database and + /// key/value stores keep attributes as JSON and hand back its tree (a + /// `Map` for a record or other class). This reads either into `type`, so + /// code that switches stores keeps working. The build writes the JSON codec + /// for a class passed here literally, and for the type of a value given to + /// [#setAttribute] (issue 6353). + /// + /// @return the attribute, or null when there is none + /// @throws IllegalArgumentException when it does not fit `type` + @SuppressWarnings("unchecked") + public synchronized T getAttribute(String name, Class type) { + Object value = getAttribute(name); + if (value == null || type.isInstance(value)) { + // Checked above rather than by Class.cast: the server runtime's + // Class.cast returns Object, and the translated runtime does not + // check a cast. + return (T) value; + } + return Json.convert(value, type); + } + public synchronized void setAttribute(String name, Object value) { checkValid(); if (value == null) { diff --git a/vm/backend/src/com/codename1/backend/Sessions.java b/vm/backend/src/com/codename1/backend/Sessions.java index 3b7cf0ad2a0..aa43e7a66c6 100644 --- a/vm/backend/src/com/codename1/backend/Sessions.java +++ b/vm/backend/src/com/codename1/backend/Sessions.java @@ -44,6 +44,12 @@ /// cn1.session.secure=auto # true, false, or auto (on under TLS) /// ``` /// +/// Spring Boot's keys work too when the `cn1.session.*` one is unset: +/// `server.servlet.session.timeout` (a Duration such as `30m` or `PT12H`), +/// `server.servlet.session.cookie.name`, `.same-site` and `.secure`, and +/// `spring.session.store-type` (`jdbc`, `redis`, `none`). Any other +/// `server.servlet.session.*` key is reported at start-up. +/// /// Nothing here runs for a request that does not ask for its session: the /// cookie is parsed on the first `getSession`, and a request that never /// calls it costs one field check when it ends. @@ -92,16 +98,18 @@ public Sessions() { public static Sessions configure(Config config, boolean tls, DataSource pool, com.codename1.impl.backend.BackendApplication application) throws IOException { Sessions out = new Sessions(application); - out.cookieName = config.get("cn1.session.cookie", "CN1SESSION"); + warnUnmappedSpringKeys(config); + out.cookieName = setting(config, "cn1.session.cookie", + "server.servlet.session.cookie.name", "CN1SESSION"); if (!isToken(out.cookieName)) { // Emitted verbatim in Set-Cookie: an empty name, a space, a ';' or a // control character makes a header the browser ignores or the writer // drops, and every request then starts another session nobody can // come back to. - throw new IOException("cn1.session.cookie is \"" + out.cookieName + "\"; a cookie " + throw new IOException("cn1.session.cookie (or server.servlet.session.cookie.name) is \"" + out.cookieName + "\"; a cookie " + "name is one or more letters, digits and !#$%&'*+-.^_`|~"); } - out.timeoutSeconds = config.getInt("cn1.session.timeout", 1800); + out.timeoutSeconds = timeout(config); if (out.timeoutSeconds < 0) { // Zero is the documented "never"; a negative one is a typo that // isExpired() would also read as never, silently making every @@ -110,14 +118,16 @@ public static Sessions configure(Config config, boolean tls, DataSource pool, + "; it must be a number of seconds, or 0 for sessions that never " + "expire"); } - String site = config.get("cn1.session.same-site", "Lax"); + String site = setting(config, "cn1.session.same-site", + "server.servlet.session.cookie.same-site", "Lax"); if (!"Lax".equalsIgnoreCase(site) && !"Strict".equalsIgnoreCase(site) && !"None".equalsIgnoreCase(site)) { - throw new IOException("cn1.session.same-site is \"" + site + throw new IOException("cn1.session.same-site (or server.servlet.session.cookie.same-site) is \"" + site + "\"; it must be Lax, Strict or None"); } out.sameSite = site; - String secureSetting = config.get("cn1.session.secure", "auto").trim(); + String secureSetting = setting(config, "cn1.session.secure", + "server.servlet.session.cookie.secure", "auto").trim(); if ("auto".equalsIgnoreCase(secureSetting)) { out.secure = tls; } else if ("true".equalsIgnoreCase(secureSetting)) { @@ -137,7 +147,7 @@ public static Sessions configure(Config config, boolean tls, DataSource pool, throw new IOException("cn1.session.same-site=None needs a Secure cookie; " + "set cn1.session.secure=true or serve TLS"); } - String kind = config.get("cn1.session.store", "memory"); + String kind = store(config); if ("db".equalsIgnoreCase(kind)) { if (pool == null) { throw new IOException("cn1.session.store=db needs a database, and this " @@ -155,6 +165,189 @@ public static Sessions configure(Config config, boolean tls, DataSource pool, return out; } + // ------------------------------------------------------------------ + // Spring Boot's keys (issue 6353). An application ported from Boot keeps + // its application.properties, and ignoring server.servlet.session.* there + // silently gave every user a 30 minute in-memory session that a restart + // ended. The cn1.session.* key wins when both are set. + // ------------------------------------------------------------------ + + /// The Boot keys read below; any other server.servlet.session.* key is + /// reported at start-up instead of being ignored in silence. + private static final String[] SPRING_KEYS = { + "server.servlet.session.timeout", + "server.servlet.session.cookie.name", + "server.servlet.session.cookie.same-site", + "server.servlet.session.cookie.secure", + }; + + static String setting(Config config, String key, String springKey, String fallback) + throws IOException { + // Only an UNSET key falls through: an empty cn1.session.cookie is + // still refused by the validation that follows, not defaulted. + String value = config.get(key, null); + if (value == null) { + value = config.get(springKey, null); + } + return value == null ? fallback : value; + } + + /// `cn1.session.timeout` in seconds, else Boot's + /// `server.servlet.session.timeout`, which is a Duration: `1800` (seconds), + /// `30m`, `2h`, `7d`, `500ms` or ISO-8601 such as `PT30M`. + static int timeout(Config config) throws IOException { + String own = config.get("cn1.session.timeout"); + if (own != null && own.trim().length() > 0) { + return config.getInt("cn1.session.timeout", 1800); + } + String spring = config.get("server.servlet.session.timeout"); + if (spring == null || spring.trim().length() == 0) { + return 1800; + } + long seconds = durationSeconds(spring.trim()); + if (seconds < 0) { + throw new IOException("server.servlet.session.timeout is \"" + spring + + "\"; it must be a duration such as 1800, 30m, 12h, 7d or PT30M"); + } + return seconds > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) seconds; + } + + /// A Spring Boot Duration in seconds (sub-second values round up, so a + /// short timeout never becomes "never"), or -1 when it is not one. + static long durationSeconds(String text) { + String t = text.trim(); + if (t.length() > 1 && (t.charAt(0) == 'P' || t.charAt(0) == 'p')) { + return isoSeconds(t); + } + int end = 0; + while (end < t.length() && Character.isDigit(t.charAt(end))) { + end++; + } + if (end == 0 || end > 12) { + // Twelve digits of days still fit a long in seconds; more would wrap. + return -1; + } + long n = Long.parseLong(t.substring(0, end)); + String unit = t.substring(end).trim(); + if (unit.length() == 0 || "s".equalsIgnoreCase(unit)) { + return n; + } + if ("ms".equalsIgnoreCase(unit)) { + return (n + 999) / 1000; + } + if ("us".equalsIgnoreCase(unit)) { + return (n + 999999) / 1000000; + } + if ("ns".equalsIgnoreCase(unit)) { + return (n + 999999999L) / 1000000000L; + } + if ("m".equalsIgnoreCase(unit)) { + return n * 60; + } + if ("h".equalsIgnoreCase(unit)) { + return n * 3600; + } + if ("d".equalsIgnoreCase(unit)) { + return n * 86400; + } + return -1; + } + + /// `PnDTnHnMnS` with whole numbers (fractional seconds rounded up). + private static long isoSeconds(String t) { + long total = 0; + boolean time = false; + boolean any = false; + boolean timeUnits = false; + int i = 1; + while (i < t.length()) { + char c = t.charAt(i); + if (c == 'T' || c == 't') { + time = true; + i++; + continue; + } + int start = i; + while (i < t.length() && (Character.isDigit(t.charAt(i)) || t.charAt(i) == '.')) { + i++; + } + if (start == i || i >= t.length() || i - start > 12) { + return -1; + } + String number = t.substring(start, i); + char unit = Character.toUpperCase(t.charAt(i++)); + int dot = number.indexOf('.'); + if (dot >= 0 && unit != 'S') { + return -1; + } + long whole = dot < 0 ? Long.parseLong(number) + : (dot == 0 ? 0 : Long.parseLong(number.substring(0, dot))); + boolean fraction = dot >= 0 && number.substring(dot + 1).replace('0', ' ').trim().length() > 0; + if (unit == 'D' && !time) { + total += whole * 86400; + } else if (unit == 'H' && time) { + total += whole * 3600; + } else if (unit == 'M' && time) { + total += whole * 60; + } else if (unit == 'S' && time) { + total += whole + (fraction ? 1 : 0); + } else { + return -1; + } + any = true; + timeUnits = timeUnits || time; + } + // Duration.parse refuses a `T` with nothing after it ("P1DT"). + return any && time == timeUnits ? total : -1; + } + + /// `cn1.session.store`, else Boot 2's `spring.session.store-type` + /// (`jdbc` is the database store, `redis` the key/value one, `none` memory). + static String store(Config config) throws IOException { + String own = config.get("cn1.session.store"); + if (own != null && own.trim().length() > 0) { + return own.trim(); + } + String spring = config.get("spring.session.store-type"); + if (spring == null || spring.trim().length() == 0) { + return "memory"; + } + String t = spring.trim(); + if ("jdbc".equalsIgnoreCase(t)) { + return "db"; + } + if ("redis".equalsIgnoreCase(t)) { + return "kv"; + } + if ("none".equalsIgnoreCase(t)) { + return "memory"; + } + throw new IOException("spring.session.store-type is \"" + spring + + "\"; the backend supports jdbc, redis and none (or set cn1.session.store " + + "to memory, db or kv)"); + } + + /// One start-up line per server.servlet.session.* key nothing here reads, + /// such as `persistent` or `tracking-modes`: a key that does nothing should + /// say so rather than look like it worked. + private static void warnUnmappedSpringKeys(Config config) { + for (Object key : config.keys()) { + String name = String.valueOf(key); + if (!name.startsWith("server.servlet.session.")) { + continue; + } + boolean read = false; + for (String known : SPRING_KEYS) { + read |= known.equals(name); + } + if (!read) { + System.err.println(name + " is a Spring Boot setting the backend does not " + + "read; see the cn1.session.* keys (timeout, store, cookie, " + + "same-site, secure)"); + } + } + } + /// Whether `name` is an RFC 6265 cookie-name: an HTTP token. static boolean isToken(String name) { if (name == null || name.length() == 0) { diff --git a/vm/backend/src/com/codename1/backend/security/HttpStatusEntryPoint.java b/vm/backend/src/com/codename1/backend/security/HttpStatusEntryPoint.java index 4fab0c22360..e3edb3883cb 100644 --- a/vm/backend/src/com/codename1/backend/security/HttpStatusEntryPoint.java +++ b/vm/backend/src/com/codename1/backend/security/HttpStatusEntryPoint.java @@ -23,9 +23,19 @@ package com.codename1.backend.security; import com.codename1.backend.HttpServer; +import com.codename1.backend.Json; -/// Answers with a status and nothing else: `new HttpStatusEntryPoint(401)` for -/// an API whose clients know how to authenticate without being told. +/// Answers with a status and a body in the shape of Spring Boot's default error body: +/// `new HttpStatusEntryPoint(401)` for an API whose clients know how to +/// authenticate without being told. +/// +/// The body is `{"timestamp":..,"status":401,"error":"Unauthorized","path":"/x"}`, +/// the shape of Boot's `/error` responses. This differs from Spring on purpose: +/// Spring's entry point only sets the status, so Boot sends no body. An empty +/// body broke clients that read the error body -- a +/// Codename One client's `RequestBuilder` reports an error code while reading +/// it, so with `Content-Length: 0` no error callback ever saw the 401 +/// (issue 6353). public final class HttpStatusEntryPoint implements AuthenticationEntryPoint { private final int status; @@ -39,6 +49,51 @@ public HttpStatusEntryPoint(int status) { @Override public HttpServer.Response commence(HttpServer.Request request, AuthenticationException authException) { - return HttpServer.Response.empty(status, "text/plain; charset=utf-8", null); + return HttpServer.Response.json(status, errorBody(status, SecurityExchange.path(request), + System.currentTimeMillis())); + } + + /// Boot's `DefaultErrorAttributes` shape, with its timestamp format + /// (`2026-01-31T09:05:07.123+00:00`, always UTC here). + static String errorBody(int status, String path, long now) { + java.util.Map body = new java.util.LinkedHashMap(); + body.put("timestamp", timestamp(now)); + body.put("status", Integer.valueOf(status)); + body.put("error", HttpServer.reasonPhrase(status)); + body.put("path", path == null ? "" : path); + return Json.write(body); + } + + static String timestamp(long millis) { + long days = Math.floorDiv(millis, 86400000L); + long ms = Math.floorMod(millis, 86400000L); + // Days since 1970-01-01 to a civil date (H. Hinnant's algorithm), as + // java.time is not part of every runtime the backend is built for. + long z = days + 719468; + long era = (z >= 0 ? z : z - 146096) / 146097; + long doe = z - era * 146097; + long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + long doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + long mp = (5 * doy + 2) / 153; + long day = doy - (153 * mp + 2) / 5 + 1; + long month = mp < 10 ? mp + 3 : mp - 9; + long year = yoe + era * 400 + (month <= 2 ? 1 : 0); + StringBuilder sb = new StringBuilder(29); + pad(sb, year, 4).append('-'); + pad(sb, month, 2).append('-'); + pad(sb, day, 2).append('T'); + pad(sb, ms / 3600000L, 2).append(':'); + pad(sb, ms / 60000L % 60, 2).append(':'); + pad(sb, ms / 1000L % 60, 2).append('.'); + pad(sb, ms % 1000L, 3).append("+00:00"); + return sb.toString(); + } + + private static StringBuilder pad(StringBuilder sb, long value, int width) { + String digits = Long.toString(value); + for (int i = digits.length(); i < width; i++) { + sb.append('0'); + } + return sb.append(digits); } } diff --git a/vm/backend/src/com/codename1/backend/security/OAuth2AuthorizationEndpointFilter.java b/vm/backend/src/com/codename1/backend/security/OAuth2AuthorizationEndpointFilter.java index 1d989f208a8..fdbbb9aa829 100644 --- a/vm/backend/src/com/codename1/backend/security/OAuth2AuthorizationEndpointFilter.java +++ b/vm/backend/src/com/codename1/backend/security/OAuth2AuthorizationEndpointFilter.java @@ -50,10 +50,21 @@ public HttpServer.Response doFilter(HttpServer.Request request, FilterChain chai SecurityExchange exchange = SecurityExchange.of(request); Object sessionAuthentication = exchange == null ? null : exchange.getAttribute(SecurityExchange.SESSION_AUTHENTICATION); + // A user is signed in here when the session says so, or when a + // remember-me cookie does. Spring Authorization Server accepts both (it + // asks only that the principal is authenticated and not anonymous), and + // refusing remember-me made every silent OIDC refresh (prompt=none in a + // hidden iframe) answer login_required once the session had gone -- after + // a restart or a timeout -- although the browser held a valid cookie + // (issue 6353). Remember-me is a browser credential, so it carries the + // same provenance as a session; what stays refused is a credential sent + // with the request itself (a bearer token, HTTP basic), which signs in no + // browser and must not grant a code. + boolean rememberedBrowser = authentication instanceof RememberMeAuthenticationToken; if (authentication == null || authentication instanceof AnonymousAuthenticationToken - || authentication instanceof RememberMeAuthenticationToken || !authentication.isAuthenticated() - || authentication != sessionAuthentication) { //NOPMD CompareObjectsWithEquals - session provenance + || !rememberedBrowser + && authentication != sessionAuthentication) { //NOPMD CompareObjectsWithEquals - session provenance authentication = null; } CsrfToken token = CsrfFilter.getToken(request); diff --git a/vm/backend/src/com/codename1/impl/backend/Scheduler.java b/vm/backend/src/com/codename1/impl/backend/Scheduler.java index 244929f9b33..eff96aed8ae 100644 --- a/vm/backend/src/com/codename1/impl/backend/Scheduler.java +++ b/vm/backend/src/com/codename1/impl/backend/Scheduler.java @@ -134,6 +134,8 @@ public String describeSchedule() { /// the next run took after it expired. private long claims; private boolean started; + /// cn1.scheduler.enabled=false: no job ever comes due, however it ran. + private boolean held; private boolean stopped; /// Whether this scheduler's server records metrics. Per scheduler: the job /// histogram is the process's, and a second server that turned metrics off @@ -163,6 +165,23 @@ public synchronized void bind(Backend backend) { /// The server's configuration, for the key/value store locks fall back to. private com.codename1.backend.Config config; + + /// The configuration alone, for a scheduler started without a server. + synchronized void configure(com.codename1.backend.Config config) { + this.config = config; + } + + /// Whether `cn1.scheduler.enabled` lets the timetable run; true when unset. + private boolean enabled() { + if (config == null) { + return true; + } + try { + return config.getBoolean("cn1.scheduler.enabled", true); + } catch (IOException e) { + throw new IllegalStateException(e.getMessage(), e); + } + } /// The store locks are claimed in when there is no database; opened on the /// first claim and closed when the scheduler stops. private com.codename1.backend.kv.KeyValueStore kvLocks; @@ -271,11 +290,15 @@ public synchronized void start() { return; } started = true; + boolean enabled = enabled(); + held = !enabled; long now = System.currentTimeMillis(); for (Object element : jobs) { Job job = (Job) element; job.executor = BackendAccess.get().executor(job.executorName, job.threadKind); - if (job.kind == CRON) { + if (!enabled) { + job.next = Long.MAX_VALUE; + } else if (job.kind == CRON) { job.next = job.cron.next(now); if (job.next < 0) { job.next = Long.MAX_VALUE; @@ -286,6 +309,20 @@ public synchronized void start() { job.next = AsyncTask.deadline(now, Math.max(0, job.initialDelay)); } } + if (!enabled) { + // cn1.scheduler.enabled=false: a server pointed at a copy of + // production data for a read-only preview must not run its crons + // against it (issue 6353). Spring's equivalent is a conditional on + // every scheduled bean; one switch is what that was used for. The + // jobs stay registered with their executors and never come due, so + // the management endpoints still list them and a deliberate manual + // trigger still runs one. + if (!jobs.isEmpty()) { + System.err.println("cn1.scheduler.enabled=false: " + jobs.size() + + " scheduled job(s) will not run"); + } + return; + } if (jobs.isEmpty()) { return; } @@ -403,6 +440,10 @@ public void run() { } private long following(Job job, long now) { + if (held) { + // A manual run of a held-back job must not put it back on its timetable. + return Long.MAX_VALUE; + } if (job.kind == CRON) { long next = job.cron.next(now); return next < 0 ? Long.MAX_VALUE : next;