test_hostnames.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Hostname resolution: which surface a `Host` names and whose project it is.
  2. //
  3. // This is a TENANCY BOUNDARY, so almost every test below is about what must NOT
  4. // resolve. A test suite for this that only checked the happy path would pass
  5. // just as well against a registry that answered "the first project it could
  6. // find" for every unknown name - which is the single failure that matters.
  7. #include <gtest/gtest.h>
  8. #include "hostnames.hpp"
  9. using svapi::HostBinding;
  10. using svapi::HostEntry;
  11. using svapi::HostKind;
  12. using svapi::HostRegistry;
  13. using svapi::normaliseHost;
  14. using svapi::PathStyle;
  15. using svapi::validHostname;
  16. namespace {
  17. HostRegistry twoTenants(std::vector<std::string>* dropped = nullptr) {
  18. return HostRegistry::build(
  19. "admin.smartbotics.ai", {"global-api-01.smartbotics.ai"},
  20. {{"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}},
  21. {"justice-pa", {{"pa.smartbotics.ai", PathStyle::Full},
  22. {"assistant.smartbotics.ai", PathStyle::Short}}}},
  23. dropped);
  24. }
  25. } // namespace
  26. // --- normalisation: every arm is a spelling a caller controls ----------------
  27. TEST(NormaliseHost, LowercasesBecauseDnsIsCaseInsensitive) {
  28. EXPECT_EQ(normaliseHost("NT.KB.Smartbotics.AI"), "nt.kb.smartbotics.ai");
  29. }
  30. TEST(NormaliseHost, StripsThePort) {
  31. EXPECT_EQ(normaliseHost("example.com:8443"), "example.com");
  32. EXPECT_EQ(normaliseHost("example.com:443"), "example.com");
  33. }
  34. TEST(NormaliseHost, AnIPv6LiteralKeepsItsAddressAndLosesOnlyThePort) {
  35. // The trap: truncating at the FIRST colon turns `[::1]:8080` into `[`,
  36. // which then matches nothing - or worse, matches a registry entry somebody
  37. // created by pasting a bracket.
  38. EXPECT_EQ(normaliseHost("[::1]:8080"), "[::1]");
  39. EXPECT_EQ(normaliseHost("[2001:db8::5]"), "[2001:db8::5]");
  40. EXPECT_EQ(normaliseHost("[2001:DB8::5]:443"), "[2001:db8::5]");
  41. }
  42. TEST(NormaliseHost, StripsExactlyOneTrailingDot) {
  43. // `example.com.` is the fully-qualified spelling and resolves identically,
  44. // so a client using it must not miss.
  45. EXPECT_EQ(normaliseHost("example.com."), "example.com");
  46. // But only one: `example.com..` is not a name anybody registered, and
  47. // normalising it would invent a match.
  48. EXPECT_EQ(normaliseHost("example.com.."), "example.com.");
  49. }
  50. TEST(NormaliseHost, TrimsTheOptionalWhitespaceAHeaderMayCarry) {
  51. EXPECT_EQ(normaliseHost(" example.com\t"), "example.com");
  52. }
  53. // --- what a project may register --------------------------------------------
  54. TEST(ValidHostname, RefusesAWildcardOutright) {
  55. // THE one that matters. `*.smartbotics.ai` would catch every subdomain
  56. // nobody had claimed YET, so a tenancy boundary would move whenever an
  57. // unrelated DNS record appeared. Wildcards belong in certificate selection,
  58. // where the wrong match fails a handshake rather than serving data.
  59. EXPECT_FALSE(validHostname("*.smartbotics.ai"));
  60. EXPECT_FALSE(validHostname("*"));
  61. EXPECT_FALSE(validHostname("nt.*.smartbotics.ai"));
  62. }
  63. TEST(ValidHostname, RefusesAnythingThatIsNotJustAName) {
  64. EXPECT_FALSE(validHostname("https://nt.kb.smartbotics.ai"));
  65. EXPECT_FALSE(validHostname("nt.kb.smartbotics.ai/admin"));
  66. EXPECT_FALSE(validHostname("nt.kb.smartbotics.ai:8443"));
  67. EXPECT_FALSE(validHostname("user@nt.kb.smartbotics.ai"));
  68. EXPECT_FALSE(validHostname("nt kb.smartbotics.ai"));
  69. }
  70. TEST(ValidHostname, RefusesASingleLabelSoAnIntranetAliasCannotBecomeATenant) {
  71. EXPECT_FALSE(validHostname("localhost"));
  72. EXPECT_FALSE(validHostname("api"));
  73. EXPECT_TRUE(validHostname("api.example.com"));
  74. }
  75. TEST(ValidHostname, RefusesMalformedLabels) {
  76. EXPECT_FALSE(validHostname(""));
  77. EXPECT_FALSE(validHostname(".example.com"));
  78. EXPECT_FALSE(validHostname("example.com.")); // normalise first, then validate
  79. EXPECT_FALSE(validHostname("a..b.com"));
  80. EXPECT_FALSE(validHostname("-bad.example.com"));
  81. EXPECT_FALSE(validHostname("bad-.example.com"));
  82. EXPECT_FALSE(validHostname(std::string(254, 'a') + ".com"));
  83. }
  84. // --- resolution -------------------------------------------------------------
  85. TEST(HostRegistry, ResolvesEachKind) {
  86. const HostRegistry r = twoTenants();
  87. EXPECT_EQ(r.resolve("admin.smartbotics.ai").kind, HostKind::Admin);
  88. EXPECT_EQ(r.resolve("global-api-01.smartbotics.ai").kind, HostKind::Global);
  89. const HostBinding nt = r.resolve("nt.kb.smartbotics.ai");
  90. EXPECT_EQ(nt.kind, HostKind::Project);
  91. EXPECT_EQ(nt.project, "novitax");
  92. EXPECT_EQ(nt.pathStyle, PathStyle::Short) << "short is the default shape";
  93. const HostBinding pa = r.resolve("pa.smartbotics.ai");
  94. EXPECT_EQ(pa.project, "justice-pa");
  95. EXPECT_EQ(pa.pathStyle, PathStyle::Full) << "the per-hostname setting is honoured";
  96. }
  97. TEST(HostRegistry, OneProjectMayHoldSeveralHostnames) {
  98. const HostRegistry r = twoTenants();
  99. EXPECT_EQ(r.resolve("pa.smartbotics.ai").project, "justice-pa");
  100. EXPECT_EQ(r.resolve("assistant.smartbotics.ai").project, "justice-pa");
  101. }
  102. TEST(HostRegistry, AnUnknownHostIsUNKNOWNAndNEVERAProject) {
  103. // The failure this file exists to prevent. Note the second and third cases:
  104. // a SUFFIX of a registered name and a PARENT of one must both miss, because
  105. // a closest-parent match would hand every unclaimed subdomain to whoever
  106. // owns something above it.
  107. const HostRegistry r = twoTenants();
  108. for (const char* h : {"nobody.example.com", "kb.smartbotics.ai", "smartbotics.ai",
  109. "evil.nt.kb.smartbotics.ai", "nt.kb.smartbotics.ai.evil.com", ""}) {
  110. const HostBinding b = r.resolve(h);
  111. EXPECT_EQ(b.kind, HostKind::Unknown) << h;
  112. EXPECT_TRUE(b.project.empty()) << h << " resolved to project '" << b.project << "'";
  113. }
  114. }
  115. TEST(HostRegistry, ResolutionIsCaseAndPortInsensitive) {
  116. const HostRegistry r = twoTenants();
  117. EXPECT_EQ(r.resolve("NT.KB.SMARTBOTICS.AI:8443").project, "novitax");
  118. EXPECT_EQ(r.resolve("nt.kb.smartbotics.ai.").project, "novitax");
  119. }
  120. // --- collisions: the two directions, and they resolve differently -----------
  121. TEST(HostRegistry, ADeploymentNameCANNOTBeTakenByAProject) {
  122. // A project claiming the admin hostname would hand it the web UI and the
  123. // docs catalogue. The deployment keeps its name; the claim is dropped.
  124. std::vector<std::string> dropped;
  125. const HostRegistry r = HostRegistry::build(
  126. "admin.smartbotics.ai", {"global.smartbotics.ai"},
  127. {{"evil", {{"admin.smartbotics.ai", PathStyle::Short},
  128. {"global.smartbotics.ai", PathStyle::Short}}}},
  129. &dropped);
  130. EXPECT_EQ(r.resolve("admin.smartbotics.ai").kind, HostKind::Admin);
  131. EXPECT_EQ(r.resolve("global.smartbotics.ai").kind, HostKind::Global);
  132. EXPECT_TRUE(r.resolve("admin.smartbotics.ai").project.empty());
  133. EXPECT_EQ(dropped.size(), 2u) << "both claims reported, so the operator can see them";
  134. }
  135. TEST(HostRegistry, AHostClaimedByTWOProjectsGoesToNEITHER) {
  136. // Last-writer-wins would move a tenancy boundary silently. Refusing both
  137. // makes it a 404 on a name nobody can reach - visible, and recoverable.
  138. std::vector<std::string> dropped;
  139. const HostRegistry r = HostRegistry::build(
  140. "admin.example.com", {},
  141. {{"alpha", {{"shared.example.com", PathStyle::Short}}},
  142. {"beta", {{"shared.example.com", PathStyle::Short}}}},
  143. &dropped);
  144. const HostBinding b = r.resolve("shared.example.com");
  145. EXPECT_EQ(b.kind, HostKind::Unknown);
  146. EXPECT_TRUE(b.project.empty()) << "contested host served '" << b.project << "'";
  147. EXPECT_EQ(dropped.size(), 1u);
  148. }
  149. TEST(HostRegistry, OneProjectListingTheSameHostTwiceIsHarmless) {
  150. const HostRegistry r = HostRegistry::build(
  151. "admin.example.com", {},
  152. {{"alpha", {{"a.example.com", PathStyle::Short}, {"A.example.com.", PathStyle::Full}}}},
  153. nullptr);
  154. // Kept, and the FIRST entry's style wins - stated by a test so a later
  155. // change to "last wins" is a deliberate decision rather than a surprise.
  156. const HostBinding b = r.resolve("a.example.com");
  157. EXPECT_EQ(b.project, "alpha");
  158. EXPECT_EQ(b.pathStyle, PathStyle::Short);
  159. }
  160. TEST(HostRegistry, AnInvalidRegisteredHostIsDroppedRatherThanStored) {
  161. std::vector<std::string> dropped;
  162. const HostRegistry r = HostRegistry::build(
  163. "admin.example.com", {},
  164. {{"alpha", {{"*.example.com", PathStyle::Short}, {"localhost", PathStyle::Short}}}},
  165. &dropped);
  166. EXPECT_EQ(r.resolve("*.example.com").kind, HostKind::Unknown);
  167. EXPECT_EQ(r.resolve("anything.example.com").kind, HostKind::Unknown)
  168. << "a stored wildcard must not have become a live wildcard";
  169. EXPECT_EQ(dropped.size(), 2u);
  170. }
  171. // --- empty: the ordinary case for a deployment behind someone else's proxy ---
  172. TEST(HostRegistry, NoHostnamesConfiguredMeansEmptyNotEverythingRefused) {
  173. // The signal to skip host gating entirely. Without this, adding the feature
  174. // would 404 every request on every existing deployment - an outage caused
  175. // by shipping a control, which this codebase has done once already
  176. // (network_egress defaulting to deny would have done exactly that).
  177. const HostRegistry r = HostRegistry::build("", {}, {}, nullptr);
  178. EXPECT_TRUE(r.empty());
  179. EXPECT_EQ(r.resolve("anything.example.com").kind, HostKind::Unknown);
  180. }
  181. TEST(HostRegistry, SizeCountsEveryRegisteredName) {
  182. const HostRegistry r = twoTenants();
  183. EXPECT_EQ(r.size(), 5u) << "admin + global + 3 project hostnames";
  184. EXPECT_FALSE(r.empty());
  185. }
  186. // --- serialisation: a hostname has to survive the document round trip -------
  187. //
  188. // These live here rather than in test_stores.cpp because they are pure: the
  189. // store's job is tested there, and what a STORED document means is tested here.
  190. #include "project_settings.hpp"
  191. using svapi::ProjectSettings;
  192. TEST(ProjectSettingsHostnames, RoundTripsHostAndStyle) {
  193. ProjectSettings p;
  194. p.project = "novitax";
  195. p.hostnames = {{"nt.kb.smartbotics.ai", PathStyle::Short},
  196. {"portal.novitax.example", PathStyle::Full}};
  197. const ProjectSettings back = ProjectSettings::fromJson(p.toJson());
  198. ASSERT_EQ(back.hostnames.size(), 2u);
  199. EXPECT_EQ(back.hostnames[0].host, "nt.kb.smartbotics.ai");
  200. EXPECT_EQ(back.hostnames[0].pathStyle, PathStyle::Short);
  201. EXPECT_EQ(back.hostnames[1].host, "portal.novitax.example");
  202. EXPECT_EQ(back.hostnames[1].pathStyle, PathStyle::Full)
  203. << "the per-hostname style must survive storage, or every hostname silently "
  204. "becomes the default shape after a restart";
  205. }
  206. TEST(ProjectSettingsHostnames, EmittedAsAnArrayEvenWhenEmpty) {
  207. // "No hostnames" and "a server that does not know about hostnames" must not
  208. // look the same to a reader - this file's most repeated trap.
  209. const nlohmann::json j = ProjectSettings{}.toJson();
  210. ASSERT_TRUE(j.contains("hostnames"));
  211. EXPECT_TRUE(j.at("hostnames").is_array());
  212. EXPECT_TRUE(j.at("hostnames").empty());
  213. }
  214. TEST(ProjectSettingsHostnames, AcceptsTheBareStringSpellingAndDefaultsToShort) {
  215. // So a hand-written document stays readable.
  216. const nlohmann::json j = {{"project", "p"}, {"hostnames", {"a.example.com"}}};
  217. const ProjectSettings p = ProjectSettings::fromJson(j);
  218. ASSERT_EQ(p.hostnames.size(), 1u);
  219. EXPECT_EQ(p.hostnames[0].host, "a.example.com");
  220. EXPECT_EQ(p.hostnames[0].pathStyle, PathStyle::Short);
  221. }
  222. TEST(ProjectSettingsHostnames, AnUnknownStyleIsShortRatherThanAnError) {
  223. // A document written by a NEWER server must not take a project offline -
  224. // the same forward-compatibility rule the function descriptor follows for
  225. // an unknown key.
  226. const nlohmann::json j = {{"project", "p"},
  227. {"hostnames", {{{"host", "a.example.com"}, {"path_style", "sideways"}}}}};
  228. const ProjectSettings p = ProjectSettings::fromJson(j);
  229. ASSERT_EQ(p.hostnames.size(), 1u);
  230. EXPECT_EQ(p.hostnames[0].pathStyle, PathStyle::Short);
  231. }
  232. TEST(ProjectSettingsHostnames, AMalformedEntryIsSkippedWithoutLosingTheRest) {
  233. // A typo in one hostname must not cost the project its embedding overrides.
  234. const nlohmann::json j = {{"project", "p"},
  235. {"default_embedding_model", "m"},
  236. {"hostnames", {7, nlohmann::json::object(), "ok.example.com"}}};
  237. const ProjectSettings p = ProjectSettings::fromJson(j);
  238. EXPECT_EQ(p.defaultEmbeddingModel, "m") << "the rest of the document survived";
  239. ASSERT_EQ(p.hostnames.size(), 1u);
  240. EXPECT_EQ(p.hostnames[0].host, "ok.example.com");
  241. }