From b46d41c36380e04f6388970b5ef05c687f4d1819 Mon Sep 17 00:00:00 2001
From: Nobuyoshi Nakada <nobu@ruby-lang.org>
Date: Tue, 22 Nov 2022 11:05:52 +0900
Subject: [PATCH] Relax domain label restrictions

---
 lib/cgi/cookie.rb           |  2 +-
 test/cgi/test_cgi_cookie.rb | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/lib/cgi/cookie.rb b/lib/cgi/cookie.rb
index 4b11a6a..1a9c1a8 100644
--- a/lib/cgi/cookie.rb
+++ b/lib/cgi/cookie.rb
@@ -42,7 +42,7 @@ class CGI
 
     TOKEN_RE = %r"\A[[!-~]&&[^()<>@,;:\\\"/?=\[\]{}]]+\z"
     PATH_VALUE_RE = %r"\A[[ -~]&&[^;]]*\z"
-    DOMAIN_VALUE_RE = %r"\A(?<label>[A-Za-z][-A-Za-z0-9]*[A-Za-z0-9])(?:\.\g<label>)*\z"
+    DOMAIN_VALUE_RE = %r"\A(?<label>(?!-)[-A-Za-z0-9]+(?<!-))(?:\.\g<label>)*\z"
 
     # Create a new CGI::Cookie object.
     #
diff --git a/test/cgi/test_cgi_cookie.rb b/test/cgi/test_cgi_cookie.rb
index 2f09d0f..e3ec4be 100644
--- a/test/cgi/test_cgi_cookie.rb
+++ b/test/cgi/test_cgi_cookie.rb
@@ -60,6 +60,24 @@ class CGICookieTest < Test::Unit::TestCase
   end
 
 
+  def test_cgi_cookie_new_with_domain
+    h = {'name'=>'name1', 'value'=>'value1'}
+    cookie = CGI::Cookie.new('domain'=>'a.example.com', **h)
+    assert_equal('a.example.com', cookie.domain)
+
+    cookie = CGI::Cookie.new('domain'=>'1.example.com', **h)
+    assert_equal('1.example.com', cookie.domain, 'enhanced by RFC 1123')
+
+    assert_raise(ArgumentError) {
+      CGI::Cookie.new('domain'=>'-a.example.com', **h)
+    }
+
+    assert_raise(ArgumentError) {
+      CGI::Cookie.new('domain'=>'a-.example.com', **h)
+    }
+  end
+
+
   def test_cgi_cookie_scriptname
     cookie = CGI::Cookie.new('name1', 'value1')
     assert_equal('', cookie.path)
-- 
2.33.0

