diff --git a/src/jsc/bindings/JSEnvironmentVariableMap.cpp b/src/jsc/bindings/JSEnvironmentVariableMap.cpp index fc29c4c824fa..2576fa790a0c 100644 --- a/src/jsc/bindings/JSEnvironmentVariableMap.cpp +++ b/src/jsc/bindings/JSEnvironmentVariableMap.cpp @@ -23,6 +23,13 @@ #include "SharedEnvStore.h" #include "wtf/NeverDestroyed.h" #include "WebCoreJSBuiltins.h" +#include +#include + +#if OS(UNIX) +#include +#include +#endif using namespace JSC; @@ -482,15 +489,105 @@ static constexpr ASCIILiteral kProxyEnvVarNames[] = { "no_proxy"_s, }; +// POSIX "STD[+|-]hh" -> "Etc/GMT[+|-]h"; both count hours west of UTC so the sign carries over. +static String posixStdOffsetToEtcGMT(StringView v) +{ + size_t i = 0; + if (!v.isEmpty() && v[0] == '<') { + size_t end = v.find('>'); + if (end == notFound) + return String(); + i = end + 1; + } else { + while (i < v.length() && isASCIIAlpha(v[i])) + ++i; + if (i < 3) + return String(); + } + bool negative = false; + if (i < v.length() && (v[i] == '+' || v[i] == '-')) { + negative = v[i] == '-'; + ++i; + } + size_t hstart = i; + while (i < v.length() && isASCIIDigit(v[i])) + ++i; + if (i == hstart || i - hstart > 2 || i != v.length()) + return String(); + int hours = 0; + for (size_t j = hstart; j < i; ++j) + hours = hours * 10 + (v[j] - '0'); + if (hours == 0) + return "UTC"_s; + if (negative ? hours > 14 : hours > 12) + return String(); + return makeString("Etc/GMT"_s, negative ? '-' : '+', hours); +} + +bool setTimeZoneFromEnvValue(JSC::JSGlobalObject* globalObject, const WTF::String& raw) +{ + auto& vm = JSC::getVM(globalObject); + auto commit = [&](const String& name) -> bool { + if (!WTF::setTimeZoneOverride(name)) + return false; + WTF::timeZoneDidChange(); + vm.dateCache.clearForTimeZoneChange(); + return true; + }; + + if (raw.isEmpty()) + return commit(emptyString()); + + String tz = raw.startsWith(':') ? raw.substring(1) : raw; + +#if OS(UNIX) + if (tz.startsWith('/')) { + auto extractZoneInfoSuffix = [](StringView path) -> String { + constexpr auto marker = "/zoneinfo/"_s; + size_t pos = path.reverseFind(marker); + if (pos == notFound) + return String(); + StringView suffix = path.substring(pos + marker.length()); + if (suffix.startsWith("posix/"_s) || suffix.startsWith("right/"_s)) + suffix = suffix.substring(6); + if (suffix.isEmpty() || suffix == "posixrules"_s || suffix == "localtime"_s) + return String(); + return suffix.toString(); + }; + String zone = extractZoneInfoSuffix(tz); + if (zone.isNull()) { + CString utf8 = tz.utf8(); + char buf[PATH_MAX]; + if (const char* resolved = realpath(utf8.data(), buf)) + zone = extractZoneInfoSuffix(StringView::fromLatin1(resolved)); + } + if (!zone.isNull()) + tz = WTF::move(zone); + } +#endif + + if (JSC::intlResolveTimeZoneID(tz)) + return commit(tz); + + if (!tz.isEmpty()) { + String primary = JSC::toPrimaryIanaTimeZoneIdentifier(StringView(tz)); + if (!primary.isEmpty() && primary != tz && JSC::intlResolveTimeZoneID(primary)) + return commit(primary); + } + + if (String etc = posixStdOffsetToEtcGMT(tz); !etc.isNull() && JSC::intlResolveTimeZoneID(etc)) + return commit(etc); + + commit(emptyString()); + return false; +} + // The parse-and-apply bodies for the three side-effecting env vars, shared by // the regular process.env CustomSetters and applySharedEnvSideEffects so a new // side-effecting var need only be added in one place. static void applyTZFromString(JSGlobalObject* globalObject, const String& value) { - if (value.length() < 32 && WTF::setTimeZoneOverride(value)) { - WTF::timeZoneDidChange(); - JSC::getVM(globalObject).dateCache.clearForTimeZoneChange(); - } + setTimeZoneFromEnvValue(globalObject, value); } static void applyTLSRejectFromString(JSGlobalObject*, const String& value) { diff --git a/src/jsc/bindings/JSEnvironmentVariableMap.h b/src/jsc/bindings/JSEnvironmentVariableMap.h index 0c77d82ac27e..eefdcd10349e 100644 --- a/src/jsc/bindings/JSEnvironmentVariableMap.h +++ b/src/jsc/bindings/JSEnvironmentVariableMap.h @@ -13,6 +13,9 @@ namespace Bun { JSC::JSValue createEnvironmentVariablesMap(Zig::GlobalObject* globalObject); +// process.env.TZ -> JSC date cache; accepts POSIX forms beyond IANA names. +bool setTimeZoneFromEnvValue(JSC::JSGlobalObject*, const WTF::String&); + // worker_threads SHARE_ENV: a `process.env` whose reads/writes/enumeration go // through the SharedEnvStore of the tree its global belongs to. JSC::JSValue createSharedEnvironmentVariablesMap(Zig::GlobalObject* globalObject); diff --git a/src/jsc/bindings/ZigGlobalObject.cpp b/src/jsc/bindings/ZigGlobalObject.cpp index a45cf0016dfe..aff9efad572b 100644 --- a/src/jsc/bindings/ZigGlobalObject.cpp +++ b/src/jsc/bindings/ZigGlobalObject.cpp @@ -3351,15 +3351,7 @@ void GlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) extern "C" bool JSGlobalObject__setTimeZone(JSC::JSGlobalObject* globalObject, const ZigString* timeZone) { - auto& vm = JSC::getVM(globalObject); - - if (WTF::setTimeZoneOverride(Zig::toString(*timeZone))) { - WTF::timeZoneDidChange(); - vm.dateCache.clearForTimeZoneChange(); - return true; - } - - return false; + return Bun::setTimeZoneFromEnvValue(globalObject, Zig::toString(*timeZone)); } extern "C" void JSGlobalObject__requestTermination(JSC::JSGlobalObject* globalObject) diff --git a/test/js/node/process/process-env-tz.test.ts b/test/js/node/process/process-env-tz.test.ts new file mode 100644 index 000000000000..ec1daaeb8403 --- /dev/null +++ b/test/js/node/process/process-env-tz.test.ts @@ -0,0 +1,148 @@ +// https://github.com/oven-sh/bun/issues/8060 +// +// JSC resolves the default time zone by name through intlResolveTimeZoneID; a +// TZ value it cannot name collapses to UTC. Bun now normalizes POSIX TZ forms +// (leading ':', absolute tzfile paths, "std offset" specs) to an IANA name +// before handing them to JSC so Date offsets match Node. +import { describe, expect, test } from "bun:test"; +import { bunEnv, bunExe, isPosix, tempDir } from "harness"; +import { existsSync, symlinkSync } from "node:fs"; +import { join } from "node:path"; + +const script = + "process.stdout.write(String(new Date().getTimezoneOffset()) + ' ' + Intl.DateTimeFormat().resolvedOptions().timeZone)"; + +async function offset(tz: string) { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", script], + env: { ...bunEnv, TZ: tz }, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(exitCode).toBe(0); + const [off, intl] = stdout.split(" "); + return { offset: Number(off), intl }; +} + +describe.concurrent("process.env.TZ POSIX std+offset form", () => { + test.each([ + // POSIX offset sign is hours *west* of UTC, so MSK-3 is UTC+3. + ["MSK-3", -180, "Etc/GMT-3"], + ["UTC+5", 300, "Etc/GMT+5"], + ["ABC5", 300, "Etc/GMT+5"], + ["ABC-5", -300, "Etc/GMT-5"], + ["STD-14", -840, "Etc/GMT-14"], + ["STD+12", 720, "Etc/GMT+12"], + ["<+03>-3", -180, "Etc/GMT-3"], + ["ABC0", 0, "UTC"], + ] as const)("TZ=%s", async (tz, expectedOffset, expectedIntl) => { + const { offset: off, intl } = await offset(tz); + expect(off).toBe(expectedOffset); + expect(intl).toBe(expectedIntl); + }); + + test("runtime assignment: process.env.TZ = 'MSK-3'", async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), "-e", "process.env.TZ = 'MSK-3'; process.stdout.write(String(new Date().getTimezoneOffset()))"], + env: { ...bunEnv, TZ: "Etc/UTC" }, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("-180"); + expect(exitCode).toBe(0); + }); + + // Forms the normalizer must NOT map to an offset. Spawn with the OS TZ pinned + // to UTC and assign at runtime so the fall-through is deterministic on POSIX + // (Bun's setter doesn't setenv there, so getenv("TZ") stays "Etc/UTC"). + test.skipIf(!isPosix).each(["IST-5:30", "FOO4BAR", "XX-3", "ABC-05:00", "<+03-3"])( + "TZ=%s is not parsed as an offset", + async tz => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `process.env.TZ = ${JSON.stringify(tz)};` + + `process.stdout.write(Intl.DateTimeFormat().resolvedOptions().timeZone);`, + ], + env: { ...bunEnv, TZ: "Etc/UTC" }, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("UTC"); + expect(exitCode).toBe(0); + }, + ); +}); + +describe.concurrent("process.env.TZ leading colon", () => { + test("':America/New_York' strips the colon", async () => { + const { intl } = await offset(":America/New_York"); + expect(intl).toBe("America/New_York"); + }); +}); + +describe.concurrent.skipIf(!isPosix)("process.env.TZ absolute tzfile path", () => { + const target = "Australia/Sydney"; + const zoneinfo = ["/usr/share/zoneinfo", "/usr/lib/zoneinfo", "/etc/zoneinfo"] + .map(dir => join(dir, target)) + .find(p => existsSync(p)); + + test.skipIf(!zoneinfo)("':/etc/localtime' style symlink resolves to the zone it points at", async () => { + using dir = tempDir("tz-localtime", {}); + const link = join(String(dir), "localtime"); + symlinkSync(zoneinfo!, link); + // Resolve through the symlink just like a container-mounted /etc/localtime. + const { intl } = await offset(":" + link); + expect(intl).toBe(target); + }); + + test.skipIf(!zoneinfo)("'/usr/share/zoneinfo/...' prefix is stripped", async () => { + const { intl } = await offset(zoneinfo!); + expect(intl).toBe(target); + }); + + test.skipIf(!zoneinfo)("':/usr/share/zoneinfo/...'", async () => { + const { intl } = await offset(":" + zoneinfo!); + expect(intl).toBe(target); + }); +}); + +describe.concurrent("process.env.TZ IANA name unchanged", () => { + test.each([ + ["America/New_York", "America/New_York"], + ["Etc/GMT-3", "Etc/GMT-3"], + ["UTC", "UTC"], + ] as const)("TZ=%s", async (tz, expectedIntl) => { + const { intl } = await offset(tz); + expect(intl).toBe(expectedIntl); + }); +}); + +// On Windows `b` is the registry zone after the override is cleared, which the +// test cannot pin, so this check is POSIX-only. +test.skipIf(!isPosix)("runtime assignment of an unrecognized TZ clears a prior override", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `const host = new Date().getTimezoneOffset(); + process.env.TZ = 'Asia/Tokyo'; + const a = new Date().getTimezoneOffset(); + process.env.TZ = 'not a real zone'; + const b = new Date().getTimezoneOffset(); + process.stdout.write(host + ' ' + a + ' ' + b);`, + ], + env: { ...bunEnv, TZ: "Etc/UTC" }, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + const [host, a, b] = stdout.split(" ").map(Number); + expect(a).toBe(-540); + expect(b).toBe(host); + expect(exitCode).toBe(0); +});