test_hostnames.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. }
  242. // --- the four rules: WHICH PROJECT a request is about -----------------------
  243. //
  244. // Mostly refusals, because an over-permissive rule here is a cross-tenant hole
  245. // and an over-strict one is a 404 somebody reports in an hour.
  246. using svapi::ProjectResolution;
  247. using svapi::resolveProject;
  248. namespace {
  249. HostBinding projectHost(const char* p, PathStyle s = PathStyle::Short) {
  250. return HostBinding{HostKind::Project, p, s};
  251. }
  252. const HostBinding kAdmin{HostKind::Admin, {}, PathStyle::Full};
  253. const HostBinding kGlobal{HostKind::Global, {}, PathStyle::Full};
  254. const HostBinding kUnknown{};
  255. } // namespace
  256. TEST(ResolveProject, Rule1_APathOnItsOwnProjectHostIsAccepted) {
  257. const ProjectResolution r = resolveProject("novitax", projectHost("novitax"), true);
  258. EXPECT_TRUE(r.ok);
  259. EXPECT_EQ(r.project, "novitax");
  260. }
  261. TEST(ResolveProject, Rule1_APathNamingANOTHERProjectOnAProjectHostIsREFUSED) {
  262. // THE cross-tenant test. novitax's hostname must not serve justice-pa,
  263. // however the caller spells the path.
  264. for (const char* other : {"justice-pa", "toloajto", "", " novitax", "novitax "}) {
  265. const ProjectResolution r = resolveProject(other, projectHost("novitax"), true);
  266. if (std::string(other).empty()) continue; // covered by rule 3 below
  267. EXPECT_FALSE(r.ok) << "a project host served '" << other << "'";
  268. EXPECT_TRUE(r.project.empty());
  269. }
  270. }
  271. TEST(ResolveProject, Rule2_TheAdminAndGlobalHostsUseThePathUnchanged) {
  272. // Today's behaviour, which must not move.
  273. for (const HostBinding& h : {kAdmin, kGlobal}) {
  274. const ProjectResolution r = resolveProject("justice-pa", h, true);
  275. EXPECT_TRUE(r.ok);
  276. EXPECT_EQ(r.project, "justice-pa");
  277. }
  278. }
  279. TEST(ResolveProject, Rule3_TheShortFormOnAShortStyleProjectHostUsesTheHost) {
  280. const ProjectResolution r = resolveProject("", projectHost("novitax", PathStyle::Short), true);
  281. EXPECT_TRUE(r.ok);
  282. EXPECT_EQ(r.project, "novitax");
  283. }
  284. TEST(ResolveProject, Rule4_AShortPathOnTheADMINorGLOBALHostIsREFUSED) {
  285. // The load-bearing refusal. A short path there names NO project, and
  286. // falling back to a default - the first project, the only project, any
  287. // project - would be a cross-tenant hole wearing routing's clothes.
  288. for (const HostBinding& h : {kAdmin, kGlobal}) {
  289. const ProjectResolution r = resolveProject("", h, true);
  290. EXPECT_FALSE(r.ok) << "a short path resolved to '" << r.project << "'";
  291. EXPECT_TRUE(r.project.empty());
  292. }
  293. }
  294. TEST(ResolveProject, Rule4_AShortPathOnAFULLStyleProjectHostIsREFUSED) {
  295. // path_style is a SETTING, not a hint. A hostname that answered to both
  296. // shapes would silently make the choice meaningless, and an operator who
  297. // picked `full` did so to keep the project visible in their own logs.
  298. const ProjectResolution r = resolveProject("", projectHost("novitax", PathStyle::Full), true);
  299. EXPECT_FALSE(r.ok);
  300. }
  301. TEST(ResolveProject, AnUNKNOWNHostResolvesToNothingEvenWithAPath) {
  302. // Defence in depth: the pre-routing gate answers this one more cheaply,
  303. // and this is the arm a route added later cannot forget about.
  304. EXPECT_FALSE(resolveProject("novitax", kUnknown, true).ok);
  305. EXPECT_FALSE(resolveProject("", kUnknown, true).ok);
  306. }
  307. // --- gating OFF: every existing deployment, and the reason it is a parameter -
  308. TEST(ResolveProject, WithGatingOffThePathIsTheOnlySourceExactlyAsBefore) {
  309. // No hostnames configured: the Host header decides nothing. This is what
  310. // every deployment does today and what the test fixture and devstack do.
  311. const ProjectResolution r = resolveProject("novitax", kUnknown, false);
  312. EXPECT_TRUE(r.ok);
  313. EXPECT_EQ(r.project, "novitax");
  314. }
  315. TEST(ResolveProject, WithGatingOffAShortPathIsStillREFUSED) {
  316. // There is no hostname to complete it, so it names no project. Refusing is
  317. // the only answer that cannot be a guess.
  318. EXPECT_FALSE(resolveProject("", kUnknown, false).ok);
  319. }
  320. TEST(ResolveProject, UNKNOWNMeansTwoOppositeThingsAndOnlyTheFlagTellsThemApart) {
  321. // The reason gatingOn is a PARAMETER rather than inferred from the binding.
  322. // Identical host value, opposite correct answers - so a reader inferring
  323. // from `host` alone would have to be wrong in one of these two cases, and
  324. // the dangerous direction is serving the request.
  325. EXPECT_TRUE(resolveProject("novitax", kUnknown, false).ok) << "gating off: serve it";
  326. EXPECT_FALSE(resolveProject("novitax", kUnknown, true).ok) << "gating on: an unregistered host";
  327. }
  328. // --- write-time collision refusal -------------------------------------------
  329. using svapi::HostClaimRefusal;
  330. using svapi::mayClaimHostname;
  331. namespace {
  332. const std::unordered_map<std::string, std::vector<HostEntry>> kHeld = {
  333. {"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}},
  334. {"justice-pa", {{"pa.smartbotics.ai", PathStyle::Full}}},
  335. };
  336. HostClaimRefusal claim(const char* host, const char* project) {
  337. return mayClaimHostname(host, project, "admin.smartbotics.ai",
  338. {"global-api-01.smartbotics.ai"}, kHeld);
  339. }
  340. } // namespace
  341. TEST(MayClaimHostname, AFreeNameIsAccepted) {
  342. EXPECT_EQ(claim("new.smartbotics.ai", "toloajto"), HostClaimRefusal::None);
  343. }
  344. TEST(MayClaimHostname, ANameHELDByANOTHERProjectIsTAKEN) {
  345. EXPECT_EQ(claim("nt.kb.smartbotics.ai", "toloajto"), HostClaimRefusal::Taken);
  346. // And case or a trailing dot must not get round it - otherwise the refusal
  347. // is a formality a caller can spell their way past.
  348. EXPECT_EQ(claim("NT.KB.Smartbotics.AI", "toloajto"), HostClaimRefusal::Taken);
  349. EXPECT_EQ(claim("nt.kb.smartbotics.ai.", "toloajto"), HostClaimRefusal::Taken);
  350. }
  351. TEST(MayClaimHostname, ReClaimingAHostnameYouAlreadyHoldIsIdempotent) {
  352. // The web UI reads the list, edits one entry and PUTs the whole thing, so a
  353. // self-collision would make the second save fail.
  354. EXPECT_EQ(claim("nt.kb.smartbotics.ai", "novitax"), HostClaimRefusal::None);
  355. }
  356. TEST(MayClaimHostname, TheDeploymentsOwnNamesAreRESERVED) {
  357. EXPECT_EQ(claim("admin.smartbotics.ai", "novitax"), HostClaimRefusal::Reserved);
  358. EXPECT_EQ(claim("global-api-01.smartbotics.ai", "novitax"), HostClaimRefusal::Reserved);
  359. }
  360. TEST(MayClaimHostname, AnUnservableNameIsINVALIDRatherThanAccepted) {
  361. // Distinct from Taken and Reserved because the remedy differs: a caller
  362. // meeting Invalid must change the VALUE, not negotiate for the name.
  363. EXPECT_EQ(claim("*.smartbotics.ai", "novitax"), HostClaimRefusal::Invalid);
  364. EXPECT_EQ(claim("localhost", "novitax"), HostClaimRefusal::Invalid);
  365. EXPECT_EQ(claim("has space.example.com", "novitax"), HostClaimRefusal::Invalid);
  366. EXPECT_EQ(claim("", "novitax"), HostClaimRefusal::Invalid);
  367. }
  368. TEST(MayClaimHostname, TheWriteTimeAnswerAGREESWithTheRegistrysOwnPrecedence) {
  369. // The two must never disagree: if a write is accepted, the registry must
  370. // serve it, and if the registry would drop it, the write must refuse. This
  371. // asserts the pairing rather than each side separately - a mismatch is how
  372. // a project gets a 200 for a hostname that silently never works.
  373. const char* free_ = "fresh.smartbotics.ai";
  374. ASSERT_EQ(claim(free_, "toloajto"), HostClaimRefusal::None);
  375. auto held = kHeld;
  376. held["toloajto"] = {{free_, PathStyle::Short}};
  377. const HostRegistry r = HostRegistry::build("admin.smartbotics.ai",
  378. {"global-api-01.smartbotics.ai"}, held, nullptr);
  379. EXPECT_EQ(r.resolve(free_).project, "toloajto") << "accepted at write time but not served";
  380. // And the converse, for each refusal reason.
  381. for (const char* bad : {"nt.kb.smartbotics.ai", "admin.smartbotics.ai", "*.smartbotics.ai"}) {
  382. EXPECT_NE(claim(bad, "toloajto"), HostClaimRefusal::None) << bad;
  383. auto h2 = kHeld;
  384. h2["toloajto"] = {{bad, PathStyle::Short}};
  385. const HostRegistry r2 = HostRegistry::build("admin.smartbotics.ai",
  386. {"global-api-01.smartbotics.ai"}, h2, nullptr);
  387. EXPECT_NE(r2.resolve(bad).project, "toloajto")
  388. << bad << " was refused at write time but the registry served it to the claimant";
  389. }
  390. }
  391. // --- gating is the DEPLOYMENT's decision, and the way back in ---------------
  392. //
  393. // Both of these come from a defect an integration test found rather than from
  394. // the design: keying gating on "the registry is non-empty" meant attaching the
  395. // first customer hostname to a project turned gating on service-wide and
  396. // answered the operator's own next request with a 404.
  397. using svapi::isLoopbackAddress;
  398. TEST(HostGating, APROJECTHostnameAloneDoesNOTTurnGatingOn) {
  399. // The defect. An admin adding a customer hostname must not lock themselves
  400. // out of the admin UI, and nothing would have connected the two.
  401. const HostRegistry r = HostRegistry::build(
  402. "", {}, {{"novitax", {{"nt.kb.smartbotics.ai", PathStyle::Short}}}}, nullptr);
  403. EXPECT_FALSE(r.gating()) << "a project hostname turned gating on by itself";
  404. EXPECT_FALSE(r.empty()) << "it is still STORED - inert, not discarded";
  405. EXPECT_EQ(r.resolve("nt.kb.smartbotics.ai").project, "novitax")
  406. << "and it still resolves, so switching gating on later needs no re-entry";
  407. }
  408. TEST(HostGating, THEDEPLOYMENTNamingItselfIsWhatTurnsGatingOn) {
  409. EXPECT_TRUE(HostRegistry::build("admin.example.com", {}, {}, nullptr).gating());
  410. EXPECT_TRUE(HostRegistry::build("", {"global.example.com"}, {}, nullptr).gating());
  411. EXPECT_FALSE(HostRegistry::build("", {}, {}, nullptr).gating());
  412. }
  413. TEST(HostGating, LoopbackIsRecognisedFromTheCONNECTIONAddress) {
  414. // The way back in after a deployment names itself. Keyed on the interface
  415. // the connection arrived on, which an outside client cannot forge.
  416. for (const char* a : {"127.0.0.1", "127.0.0.53", "::1", "[::1]", "localhost",
  417. "::ffff:127.0.0.1"})
  418. EXPECT_TRUE(isLoopbackAddress(a)) << a;
  419. }
  420. TEST(HostGating, APUBLICAddressIsNOTLoopback) {
  421. // THE test this file exists for now. The previous version of this rule read
  422. // the HOST HEADER, so an external client could send `Host: 127.0.0.1` to
  423. // the public address and be handed the admin surface - the web UI and the
  424. // docs catalogue - on a deployment whose whole point was to serve admin on
  425. // one name only.
  426. for (const char* a : {"85.155.246.191", "142.93.100.6", "10.0.0.5", "0.0.0.0",
  427. "", "127.example.com", "1270.0.0.1", "::2"})
  428. EXPECT_FALSE(isLoopbackAddress(a)) << a << " was treated as loopback";
  429. }
  430. TEST(HostGating, TheREGISTRYNoLongerKnowsAboutAddressesAtAll) {
  431. // resolve() is exact-match and nothing else now. A bare address resolves to
  432. // Unknown like any unregistered name; the loopback exception lives at the
  433. // one place that can see the connection, not in the pure lookup.
  434. const HostRegistry r = HostRegistry::build("admin.example.com", {}, {}, nullptr);
  435. EXPECT_EQ(r.resolve("127.0.0.1").kind, HostKind::Unknown);
  436. EXPECT_EQ(r.resolve("localhost").kind, HostKind::Unknown);
  437. EXPECT_EQ(r.resolve("admin.example.com").kind, HostKind::Admin);
  438. }
  439. TEST(HostGating, AShortPathOnTheLoopbackAdminSurfaceIsStillREFUSED) {
  440. // Loopback is a way back IN, not a way around the tenancy rules: it yields
  441. // the ADMIN binding, and rule 4 applies to that exactly as to a named admin
  442. // host.
  443. const HostBinding loopbackAdmin{HostKind::Admin, {}, PathStyle::Full};
  444. EXPECT_FALSE(resolveProject("", loopbackAdmin, true).ok);
  445. EXPECT_TRUE(resolveProject("novitax", loopbackAdmin, true).ok);
  446. }
  447. // --- the raw value, before normalisation can hide anything ------------------
  448. using svapi::rawHostnameError;
  449. TEST(RawHostname, APORTIsREFUSEDRatherThanStrippedSilently) {
  450. // THE REGRESSION. mayClaimHostname normalised BEFORE validating, and
  451. // normalisation strips the port - so `example.com:8443` was accepted as
  452. // `example.com` while the 422 text promised a port is refused. The check
  453. // was dead code and the message was a lie.
  454. EXPECT_FALSE(rawHostnameError("example.com:8443").empty());
  455. EXPECT_FALSE(rawHostnameError("Example.COM:8443").empty());
  456. EXPECT_EQ(mayClaimHostname("Example.COM:8443", "p", "admin.example.com", {}, {}),
  457. HostClaimRefusal::Invalid)
  458. << "a port was accepted and silently normalised away";
  459. }
  460. TEST(RawHostname, SchemePathAndUserinfoAreRefusedByNAMERatherThanByAccident) {
  461. // Each previously failed for an INCIDENTAL reason - `https://example.com`
  462. // normalises to `https`, a single label - so the caller was told the wrong
  463. // thing about their own input.
  464. EXPECT_FALSE(rawHostnameError("https://example.com").empty());
  465. EXPECT_FALSE(rawHostnameError("example.com/path").empty());
  466. EXPECT_FALSE(rawHostnameError("user@example.com").empty());
  467. }
  468. TEST(RawHostname, AnOrdinaryHostnameIsACCEPTED_thePairing) {
  469. // Without this the tests above would pass against a function that refused
  470. // everything.
  471. EXPECT_TRUE(rawHostnameError("nt.kb.smartbotics.ai").empty());
  472. EXPECT_TRUE(rawHostnameError(" ok.example.com ").empty()) << "OWS is trimmed, not refused";
  473. EXPECT_EQ(mayClaimHostname("nt.kb.smartbotics.ai", "p", "admin.example.com", {}, {}),
  474. HostClaimRefusal::None);
  475. }