Skip to content

fix http set cookie headers #5428

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Sep 15, 2023
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
94 changes: 94 additions & 0 deletions src/bun.js/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,89 @@ JSC_DEFINE_HOST_FUNCTION(jsTTYSetMode, (JSC::JSGlobalObject * globalObject, Call
return JSValue::encode(jsNumber(err));
}

JSC_DEFINE_HOST_FUNCTION(jsHTTPGetHeader, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
auto& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);

JSValue headersValue = callFrame->argument(0);

if (auto* headers = jsDynamicCast<WebCore::JSFetchHeaders*>(headersValue)) {
JSValue nameValue = callFrame->argument(1);
if (nameValue.isString()) {
FetchHeaders* impl = &headers->wrapped();
String name = nameValue.toWTFString(globalObject);
if (WTF::equalIgnoringASCIICase(name, "set-cookie"_s)) {
return fetchHeadersGetSetCookie(globalObject, vm, impl);
}

WebCore::ExceptionOr<String> res = impl->get(name);
if (res.hasException()) {
WebCore::propagateException(globalObject, scope, res.releaseException());
return JSValue::encode(jsUndefined());
}

String value = res.returnValue();
if (value.isEmpty()) {
return JSValue::encode(jsUndefined());
}

return JSC::JSValue::encode(jsString(vm, value));
}
}

return JSValue::encode(jsUndefined());
}

JSC_DEFINE_HOST_FUNCTION(jsHTTPSetHeader, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
auto& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);

JSValue headersValue = callFrame->argument(0);

if (auto* headers = jsDynamicCast<WebCore::JSFetchHeaders*>(headersValue)) {
JSValue nameValue = callFrame->argument(1);
if (nameValue.isString()) {
String name = nameValue.toWTFString(globalObject).convertToASCIILowercase();
FetchHeaders* impl = &headers->wrapped();

JSValue valueValue = callFrame->argument(2);
if (valueValue.isUndefined())
return JSValue::encode(jsUndefined());

if (isArray(globalObject, valueValue)) {
auto* array = jsCast<JSArray*>(valueValue);
unsigned length = array->length();
if (length > 0) {
JSValue item = array->getIndex(globalObject, 0);
if (UNLIKELY(scope.exception()))
return JSValue::encode(jsUndefined());
impl->set(name, item.getString(globalObject));
RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined()));
}
for (unsigned i = 1; i < length; ++i) {
JSValue value = array->getIndex(globalObject, i);
if (UNLIKELY(scope.exception()))
return JSValue::encode(jsUndefined());
if (!value.isString())
continue;
impl->append(name, value.getString(globalObject));
RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined()));
}
RELEASE_AND_RETURN(scope, JSValue::encode(jsUndefined()));
return JSValue::encode(jsUndefined());
}

impl->set(name, valueValue.getString(globalObject));
RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined()));
return JSValue::encode(jsUndefined());
}
}

return JSValue::encode(jsUndefined());
}

JSC_DEFINE_CUSTOM_GETTER(noop_getter, (JSGlobalObject*, EncodedJSValue, PropertyName))
{
return JSC::JSValue::encode(JSC::jsUndefined());
Expand Down Expand Up @@ -1686,6 +1769,17 @@ static JSC_DEFINE_HOST_FUNCTION(functionLazyLoad,
return JSC::JSValue::encode(JSSQLStatementConstructor::create(vm, globalObject, JSSQLStatementConstructor::createStructure(vm, globalObject, globalObject->m_functionPrototype.get())));
}

if (string == "http"_s) {
auto* obj = constructEmptyObject(globalObject);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "setHeader"_s)),
JSC::JSFunction::create(vm, globalObject, 3, "setHeader"_s, jsHTTPSetHeader, ImplementationVisibility::Public), NoIntrinsic);
obj->putDirect(
vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "getHeader"_s)),
JSC::JSFunction::create(vm, globalObject, 2, "getHeader"_s, jsHTTPGetHeader, ImplementationVisibility::Public), NoIntrinsic);
return JSC::JSValue::encode(obj);
}

if (string == "worker_threads"_s) {

JSValue workerData = jsUndefined();
Expand Down
28 changes: 16 additions & 12 deletions src/bun.js/bindings/webcore/JSFetchHeaders.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -245,38 +245,43 @@ JSC_DEFINE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_getAll, (JSGlobalObject
return JSValue::encode(array);
}

JSC_DEFINE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_getSetCookie, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
JSC_DEFINE_HOST_FUNCTION(fetchHeadersGetSetCookie, (JSC::JSGlobalObject * lexicalGlobalObject, VM& vm, WebCore::FetchHeaders* impl))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
JSFetchHeaders* castedThis = jsDynamicCast<JSFetchHeaders*>(callFrame->thisValue());
if (UNLIKELY(!castedThis)) {
return JSValue::encode(jsUndefined());
}

auto& impl = castedThis->wrapped();
auto values = impl.getSetCookieHeaders();
auto values = impl->getSetCookieHeaders();
unsigned count = values.size();

if (!count) {
return JSValue::encode(JSC::constructEmptyArray(lexicalGlobalObject, nullptr, 0));
}

JSC::JSArray* array = constructEmptyArray(lexicalGlobalObject, nullptr, count);
RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined()));
RETURN_IF_EXCEPTION(scope, encodedJSValue());
if (UNLIKELY(!array)) {
throwOutOfMemoryError(lexicalGlobalObject, scope);
return JSValue::encode(jsUndefined());
return encodedJSValue();
}

for (unsigned i = 0; i < count; ++i) {
array->putDirectIndex(lexicalGlobalObject, i, jsString(vm, values[i]));
RETURN_IF_EXCEPTION(scope, JSValue::encode(jsUndefined()));
RETURN_IF_EXCEPTION(scope, encodedJSValue());
}

return JSValue::encode(array);
}

JSC_DEFINE_HOST_FUNCTION(jsFetchHeadersPrototypeFunction_getSetCookie, (JSGlobalObject * lexicalGlobalObject, CallFrame* callFrame))
{
auto& vm = JSC::getVM(lexicalGlobalObject);
JSFetchHeaders* castedThis = jsDynamicCast<JSFetchHeaders*>(callFrame->thisValue());
if (UNLIKELY(!castedThis)) {
return JSValue::encode(jsUndefined());
}
auto& impl = castedThis->wrapped();
return fetchHeadersGetSetCookie(lexicalGlobalObject, vm, &impl);
}

/* Hash table for prototype */

static const HashTableValue JSFetchHeadersPrototypeTableValues[] = {
Expand Down Expand Up @@ -688,7 +693,6 @@ extern void* _ZTVN7WebCore12FetchHeadersE[];

JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref<FetchHeaders>&& impl)
{

if constexpr (std::is_polymorphic_v<FetchHeaders>) {
#if ENABLE(BINDING_INTEGRITY)
const void* actualVTablePointer = getVTablePointer(impl.ptr());
Expand Down
2 changes: 2 additions & 0 deletions src/bun.js/bindings/webcore/JSFetchHeaders.h
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,6 @@ template<> struct JSDOMWrapperConverterTraits<FetchHeaders> {
using ToWrappedReturnType = FetchHeaders*;
};

JSC::EncodedJSValue fetchHeadersGetSetCookie(JSC::JSGlobalObject* lexicalGlobalObject, VM& vm, WebCore::FetchHeaders* impl);

} // namespace WebCore
18 changes: 6 additions & 12 deletions src/js/node/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const EventEmitter = require("node:events");
const { isTypedArray } = require("node:util/types");
const { Duplex, Readable, Writable } = require("node:stream");
const { getHeader, setHeader } = $lazy("http");

const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
/**
Expand Down Expand Up @@ -75,13 +76,9 @@ const searchParamsSymbol = Symbol.for("query"); // This is the symbol used in No
const StringPrototypeSlice = String.prototype.slice;
const StringPrototypeStartsWith = String.prototype.startsWith;
const StringPrototypeToUpperCase = String.prototype.toUpperCase;
const StringPrototypeIncludes = String.prototype.includes;
const StringPrototypeCharCodeAt = String.prototype.charCodeAt;
const StringPrototypeIndexOf = String.prototype.indexOf;
const ArrayIsArray = Array.isArray;
const RegExpPrototypeExec = RegExp.prototype.exec;
const ObjectAssign = Object.assign;
const ObjectPrototypeHasOwnProperty = Object.prototype.hasOwnProperty;

const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
const NODE_HTTP_WARNING =
Expand Down Expand Up @@ -126,12 +123,6 @@ function validateFunction(callable: any, field: string) {
return callable;
}

function getHeader(headers, name) {
if (!headers) return;
const result = headers.get(name);
return result == null ? undefined : result;
}

type FakeSocket = InstanceType<typeof FakeSocket>;
var FakeSocket = class Socket extends Duplex {
[kInternalSocketData]: any;
Expand Down Expand Up @@ -958,8 +949,11 @@ let OriginalWriteHeadFn, OriginalImplicitHeadFn;
class ServerResponse extends Writable {
declare _writableState: any;

constructor({ req, reply }) {
constructor(c) {
super();
if (!c) c = {};
var req = c.req || {};
var reply = c.reply;
this.req = req;
this._reply = reply;
this.sendDate = true;
Expand Down Expand Up @@ -1174,7 +1168,7 @@ class ServerResponse extends Writable {

setHeader(name, value) {
var headers = (this.#headers ??= new Headers());
headers.set(name, value);
setHeader(headers, name, value);
return this;
}

Expand Down
6 changes: 3 additions & 3 deletions src/js/out/InternalModuleRegistryConstants.h

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions test/js/node/http/node-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Server,
validateHeaderName,
validateHeaderValue,
ServerResponse,
} from "node:http";
import { createTest } from "node-harness";
import url from "node:url";
Expand Down Expand Up @@ -113,6 +114,23 @@ describe("node:http", () => {
});
});

describe("response", () => {
test("set-cookie works with getHeader", () => {
const res = new ServerResponse({});
res.setHeader("Set-Cookie", ["swag=true", "yolo=true"]);
expect(res.getHeader("Set-Cookie")).toEqual(["swag=true", "yolo=true"]);
});
test("set-cookie works with getHeaders", () => {
const res = new ServerResponse({});
res.setHeader("Set-Cookie", ["swag=true", "yolo=true"]);
res.setHeader("test", "test");
expect(res.getHeaders()).toEqual({
"Set-Cookie": ["swag=true", "yolo=true"],
"test": "test",
});
});
});

describe("request", () => {
function runTest(done: Function, callback: (server: Server, port: number, done: (err?: Error) => void) => void) {
var timer;
Expand Down