url_request_unittest.cc 501 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <stdint.h>
  5. #include <algorithm>
  6. #include <iterator>
  7. #include <limits>
  8. #include <memory>
  9. #include <utility>
  10. #include "base/memory/raw_ptr.h"
  11. // This must be before Windows headers
  12. #include "base/callback_helpers.h"
  13. #include "base/memory/ptr_util.h"
  14. #include "base/time/time.h"
  15. #include "build/build_config.h"
  16. #include "net/dns/public/secure_dns_policy.h"
  17. #include "net/log/net_log.h"
  18. #include "url/url_constants.h"
  19. #if BUILDFLAG(IS_WIN)
  20. #include <objbase.h>
  21. #include <shlobj.h>
  22. #include <windows.h>
  23. #include <wrl/client.h>
  24. #endif
  25. #include "base/base64url.h"
  26. #include "base/bind.h"
  27. #include "base/compiler_specific.h"
  28. #include "base/files/file_path.h"
  29. #include "base/files/file_util.h"
  30. #include "base/files/scoped_temp_dir.h"
  31. #include "base/format_macros.h"
  32. #include "base/json/json_reader.h"
  33. #include "base/location.h"
  34. #include "base/memory/weak_ptr.h"
  35. #include "base/path_service.h"
  36. #include "base/run_loop.h"
  37. #include "base/strings/escape.h"
  38. #include "base/strings/strcat.h"
  39. #include "base/strings/string_number_conversions.h"
  40. #include "base/strings/string_piece.h"
  41. #include "base/strings/string_split.h"
  42. #include "base/strings/string_util.h"
  43. #include "base/strings/stringprintf.h"
  44. #include "base/strings/utf_string_conversions.h"
  45. #include "base/task/single_thread_task_runner.h"
  46. #include "base/test/bind.h"
  47. #include "base/test/metrics/histogram_tester.h"
  48. #include "base/test/scoped_feature_list.h"
  49. #include "base/threading/thread_task_runner_handle.h"
  50. #include "base/values.h"
  51. #include "build/buildflag.h"
  52. #include "crypto/sha2.h"
  53. #include "net/base/chunked_upload_data_stream.h"
  54. #include "net/base/directory_listing.h"
  55. #include "net/base/elements_upload_data_stream.h"
  56. #include "net/base/features.h"
  57. #include "net/base/hash_value.h"
  58. #include "net/base/ip_address.h"
  59. #include "net/base/ip_endpoint.h"
  60. #include "net/base/isolation_info.h"
  61. #include "net/base/load_flags.h"
  62. #include "net/base/load_timing_info.h"
  63. #include "net/base/load_timing_info_test_util.h"
  64. #include "net/base/net_errors.h"
  65. #include "net/base/net_module.h"
  66. #include "net/base/proxy_server.h"
  67. #include "net/base/proxy_string_util.h"
  68. #include "net/base/request_priority.h"
  69. #include "net/base/test_completion_callback.h"
  70. #include "net/base/transport_info.h"
  71. #include "net/base/upload_bytes_element_reader.h"
  72. #include "net/base/upload_data_stream.h"
  73. #include "net/base/upload_file_element_reader.h"
  74. #include "net/base/url_util.h"
  75. #include "net/cert/asn1_util.h"
  76. #include "net/cert/cert_net_fetcher.h"
  77. #include "net/cert/crl_set.h"
  78. #include "net/cert/ct_policy_enforcer.h"
  79. #include "net/cert/ct_policy_status.h"
  80. #include "net/cert/do_nothing_ct_verifier.h"
  81. #include "net/cert/ev_root_ca_metadata.h"
  82. #include "net/cert/mock_cert_verifier.h"
  83. #include "net/cert/multi_log_ct_verifier.h"
  84. #include "net/cert/signed_certificate_timestamp_and_status.h"
  85. #include "net/cert/test_root_certs.h"
  86. #include "net/cert/x509_util.h"
  87. #include "net/cert_net/cert_net_fetcher_url_request.h"
  88. #include "net/cookies/canonical_cookie_test_helpers.h"
  89. #include "net/cookies/cookie_inclusion_status.h"
  90. #include "net/cookies/cookie_monster.h"
  91. #include "net/cookies/cookie_store_test_helpers.h"
  92. #include "net/cookies/test_cookie_access_delegate.h"
  93. #include "net/disk_cache/disk_cache.h"
  94. #include "net/dns/host_resolver_results.h"
  95. #include "net/dns/mock_host_resolver.h"
  96. #include "net/dns/public/secure_dns_policy.h"
  97. #include "net/http/http_byte_range.h"
  98. #include "net/http/http_cache.h"
  99. #include "net/http/http_network_layer.h"
  100. #include "net/http/http_network_session.h"
  101. #include "net/http/http_request_headers.h"
  102. #include "net/http/http_response_headers.h"
  103. #include "net/http/http_server_properties.h"
  104. #include "net/http/http_transaction_test_util.h"
  105. #include "net/http/http_util.h"
  106. #include "net/http/transport_security_state.h"
  107. #include "net/http/transport_security_state_source.h"
  108. #include "net/log/file_net_log_observer.h"
  109. #include "net/log/net_log_event_type.h"
  110. #include "net/log/net_log_source.h"
  111. #include "net/log/test_net_log.h"
  112. #include "net/log/test_net_log_util.h"
  113. #include "net/net_buildflags.h"
  114. #include "net/proxy_resolution/configured_proxy_resolution_service.h"
  115. #include "net/quic/mock_crypto_client_stream_factory.h"
  116. #include "net/quic/quic_server_info.h"
  117. #include "net/socket/read_buffering_stream_socket.h"
  118. #include "net/socket/socket_test_util.h"
  119. #include "net/socket/ssl_client_socket.h"
  120. #include "net/ssl/client_cert_identity_test_util.h"
  121. #include "net/ssl/ssl_connection_status_flags.h"
  122. #include "net/ssl/ssl_private_key.h"
  123. #include "net/ssl/ssl_server_config.h"
  124. #include "net/ssl/test_ssl_config_service.h"
  125. #include "net/test/cert_test_util.h"
  126. #include "net/test/embedded_test_server/http_request.h"
  127. #include "net/test/embedded_test_server/http_response.h"
  128. #include "net/test/gtest_util.h"
  129. #include "net/test/spawned_test_server/spawned_test_server.h"
  130. #include "net/test/test_data_directory.h"
  131. #include "net/test/test_with_task_environment.h"
  132. #include "net/test/url_request/url_request_failed_job.h"
  133. #include "net/test/url_request/url_request_mock_http_job.h"
  134. #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
  135. #include "net/url_request/redirect_util.h"
  136. #include "net/url_request/referrer_policy.h"
  137. #include "net/url_request/static_http_user_agent_settings.h"
  138. #include "net/url_request/url_request.h"
  139. #include "net/url_request/url_request_context.h"
  140. #include "net/url_request/url_request_context_builder.h"
  141. #include "net/url_request/url_request_filter.h"
  142. #include "net/url_request/url_request_http_job.h"
  143. #include "net/url_request/url_request_interceptor.h"
  144. #include "net/url_request/url_request_redirect_job.h"
  145. #include "net/url_request/url_request_test_job.h"
  146. #include "net/url_request/url_request_test_util.h"
  147. #include "net/url_request/websocket_handshake_userdata_key.h"
  148. #include "testing/gmock/include/gmock/gmock-matchers.h"
  149. #include "testing/gmock/include/gmock/gmock.h"
  150. #include "testing/gtest/include/gtest/gtest.h"
  151. #include "testing/platform_test.h"
  152. #include "third_party/abseil-cpp/absl/types/optional.h"
  153. #include "third_party/boringssl/src/include/openssl/ssl.h"
  154. #include "url/url_constants.h"
  155. #include "url/url_util.h"
  156. #if BUILDFLAG(IS_WIN)
  157. #include "base/win/scoped_com_initializer.h"
  158. #endif
  159. #if BUILDFLAG(IS_APPLE)
  160. #include "base/mac/mac_util.h"
  161. #endif
  162. #if BUILDFLAG(ENABLE_REPORTING)
  163. #include "net/network_error_logging/network_error_logging_service.h"
  164. #include "net/network_error_logging/network_error_logging_test_util.h"
  165. #endif // BUILDFLAG(ENABLE_REPORTING)
  166. #if BUILDFLAG(ENABLE_WEBSOCKETS)
  167. #include "net/websockets/websocket_test_util.h"
  168. #endif // BUILDFLAG(ENABLE_WEBSOCKETS)
  169. using net::test::IsError;
  170. using net::test::IsOk;
  171. using net::test_server::RegisterDefaultHandlers;
  172. using testing::_;
  173. using testing::AnyOf;
  174. using testing::ElementsAre;
  175. using testing::IsEmpty;
  176. using testing::Optional;
  177. using testing::UnorderedElementsAre;
  178. using base::ASCIIToUTF16;
  179. using base::Time;
  180. using std::string;
  181. namespace net {
  182. namespace {
  183. namespace test_default {
  184. #include "net/http/transport_security_state_static_unittest_default.h"
  185. }
  186. const std::u16string kChrome(u"chrome");
  187. const std::u16string kSecret(u"secret");
  188. const std::u16string kUser(u"user");
  189. const base::FilePath::CharType kTestFilePath[] =
  190. FILE_PATH_LITERAL("net/data/url_request_unittest");
  191. // Tests load timing information in the case a fresh connection was used, with
  192. // no proxy.
  193. void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
  194. int connect_timing_flags) {
  195. EXPECT_FALSE(load_timing_info.socket_reused);
  196. EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
  197. EXPECT_FALSE(load_timing_info.request_start_time.is_null());
  198. EXPECT_FALSE(load_timing_info.request_start.is_null());
  199. EXPECT_LE(load_timing_info.request_start,
  200. load_timing_info.connect_timing.connect_start);
  201. ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
  202. connect_timing_flags);
  203. EXPECT_LE(load_timing_info.connect_timing.connect_end,
  204. load_timing_info.send_start);
  205. EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
  206. EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
  207. EXPECT_LE(load_timing_info.receive_headers_start,
  208. load_timing_info.receive_headers_end);
  209. EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
  210. EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
  211. }
  212. // Same as above, but with proxy times.
  213. void TestLoadTimingNotReusedWithProxy(const LoadTimingInfo& load_timing_info,
  214. int connect_timing_flags) {
  215. EXPECT_FALSE(load_timing_info.socket_reused);
  216. EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
  217. EXPECT_FALSE(load_timing_info.request_start_time.is_null());
  218. EXPECT_FALSE(load_timing_info.request_start.is_null());
  219. EXPECT_LE(load_timing_info.request_start,
  220. load_timing_info.proxy_resolve_start);
  221. EXPECT_LE(load_timing_info.proxy_resolve_start,
  222. load_timing_info.proxy_resolve_end);
  223. EXPECT_LE(load_timing_info.proxy_resolve_end,
  224. load_timing_info.connect_timing.connect_start);
  225. ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
  226. connect_timing_flags);
  227. EXPECT_LE(load_timing_info.connect_timing.connect_end,
  228. load_timing_info.send_start);
  229. EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
  230. EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
  231. EXPECT_LE(load_timing_info.receive_headers_start,
  232. load_timing_info.receive_headers_end);
  233. }
  234. // Same as above, but with a reused socket and proxy times.
  235. void TestLoadTimingReusedWithProxy(const LoadTimingInfo& load_timing_info) {
  236. EXPECT_TRUE(load_timing_info.socket_reused);
  237. EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
  238. EXPECT_FALSE(load_timing_info.request_start_time.is_null());
  239. EXPECT_FALSE(load_timing_info.request_start.is_null());
  240. ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
  241. EXPECT_LE(load_timing_info.request_start,
  242. load_timing_info.proxy_resolve_start);
  243. EXPECT_LE(load_timing_info.proxy_resolve_start,
  244. load_timing_info.proxy_resolve_end);
  245. EXPECT_LE(load_timing_info.proxy_resolve_end, load_timing_info.send_start);
  246. EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
  247. EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
  248. EXPECT_LE(load_timing_info.receive_headers_start,
  249. load_timing_info.receive_headers_end);
  250. }
  251. CookieList GetAllCookies(URLRequestContext* request_context) {
  252. CookieList cookie_list;
  253. base::RunLoop run_loop;
  254. request_context->cookie_store()->GetAllCookiesAsync(
  255. base::BindLambdaForTesting([&](const CookieList& cookies) {
  256. cookie_list = cookies;
  257. run_loop.Quit();
  258. }));
  259. run_loop.Run();
  260. return cookie_list;
  261. }
  262. void TestLoadTimingCacheHitNoNetwork(const LoadTimingInfo& load_timing_info) {
  263. EXPECT_FALSE(load_timing_info.socket_reused);
  264. EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
  265. EXPECT_FALSE(load_timing_info.request_start_time.is_null());
  266. EXPECT_FALSE(load_timing_info.request_start.is_null());
  267. ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
  268. EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
  269. EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
  270. EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_start);
  271. EXPECT_LE(load_timing_info.receive_headers_start,
  272. load_timing_info.receive_headers_end);
  273. EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
  274. EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
  275. }
  276. // Job that allows monitoring of its priority.
  277. class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
  278. public:
  279. // The latest priority of the job is always written to |request_priority_|.
  280. PriorityMonitoringURLRequestJob(URLRequest* request,
  281. RequestPriority* request_priority)
  282. : URLRequestTestJob(request), request_priority_(request_priority) {
  283. *request_priority_ = DEFAULT_PRIORITY;
  284. }
  285. void SetPriority(RequestPriority priority) override {
  286. *request_priority_ = priority;
  287. URLRequestTestJob::SetPriority(priority);
  288. }
  289. private:
  290. const raw_ptr<RequestPriority> request_priority_;
  291. };
  292. // Do a case-insensitive search through |haystack| for |needle|.
  293. bool ContainsString(const std::string& haystack, const char* needle) {
  294. std::string::const_iterator it = std::search(
  295. haystack.begin(), haystack.end(), needle, needle + strlen(needle),
  296. base::CaseInsensitiveCompareASCII<char>());
  297. return it != haystack.end();
  298. }
  299. std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
  300. auto reader = std::make_unique<UploadBytesElementReader>(data, strlen(data));
  301. return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
  302. }
  303. // Verify that the SSLInfo of a successful SSL connection has valid values.
  304. void CheckSSLInfo(const SSLInfo& ssl_info) {
  305. // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
  306. uint16_t cipher_suite =
  307. SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
  308. EXPECT_NE(0U, cipher_suite);
  309. }
  310. // A network delegate that allows the user to choose a subset of request stages
  311. // to block in. When blocking, the delegate can do one of the following:
  312. // * synchronously return a pre-specified error code, or
  313. // * asynchronously return that value via an automatically called callback,
  314. // or
  315. // * block and wait for the user to do a callback.
  316. // Additionally, the user may also specify a redirect URL -- then each request
  317. // with the current URL different from the redirect target will be redirected
  318. // to that target, in the on-before-URL-request stage, independent of whether
  319. // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
  320. class BlockingNetworkDelegate : public TestNetworkDelegate {
  321. public:
  322. // Stages in which the delegate can block.
  323. enum Stage {
  324. NOT_BLOCKED = 0,
  325. ON_BEFORE_URL_REQUEST = 1 << 0,
  326. ON_BEFORE_SEND_HEADERS = 1 << 1,
  327. ON_HEADERS_RECEIVED = 1 << 2,
  328. };
  329. // Behavior during blocked stages. During other stages, just
  330. // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
  331. enum BlockMode {
  332. SYNCHRONOUS, // No callback, returns specified return values.
  333. AUTO_CALLBACK, // |this| posts a task to run the callback using the
  334. // specified return codes.
  335. USER_CALLBACK, // User takes care of doing a callback. |retval_| and
  336. // |auth_retval_| are ignored. In every blocking stage the
  337. // message loop is quit.
  338. };
  339. // Creates a delegate which does not block at all.
  340. explicit BlockingNetworkDelegate(BlockMode block_mode);
  341. BlockingNetworkDelegate(const BlockingNetworkDelegate&) = delete;
  342. BlockingNetworkDelegate& operator=(const BlockingNetworkDelegate&) = delete;
  343. // Runs the message loop until the delegate blocks.
  344. void RunUntilBlocked();
  345. // For users to trigger a callback returning |response|.
  346. // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
  347. // Only call if |block_mode_| == USER_CALLBACK.
  348. void DoCallback(int response);
  349. // Setters.
  350. void set_retval(int retval) {
  351. ASSERT_NE(USER_CALLBACK, block_mode_);
  352. ASSERT_NE(ERR_IO_PENDING, retval);
  353. ASSERT_NE(OK, retval);
  354. retval_ = retval;
  355. }
  356. void set_redirect_url(const GURL& url) { redirect_url_ = url; }
  357. void set_block_on(int block_on) { block_on_ = block_on; }
  358. // Allows the user to check in which state did we block.
  359. Stage stage_blocked_for_callback() const {
  360. EXPECT_EQ(USER_CALLBACK, block_mode_);
  361. return stage_blocked_for_callback_;
  362. }
  363. private:
  364. void OnBlocked();
  365. void RunCallback(int response, CompletionOnceCallback callback);
  366. // TestNetworkDelegate implementation.
  367. int OnBeforeURLRequest(URLRequest* request,
  368. CompletionOnceCallback callback,
  369. GURL* new_url) override;
  370. int OnBeforeStartTransaction(
  371. URLRequest* request,
  372. const HttpRequestHeaders& headers,
  373. OnBeforeStartTransactionCallback callback) override;
  374. int OnHeadersReceived(
  375. URLRequest* request,
  376. CompletionOnceCallback callback,
  377. const HttpResponseHeaders* original_response_headers,
  378. scoped_refptr<HttpResponseHeaders>* override_response_headers,
  379. const IPEndPoint& endpoint,
  380. absl::optional<GURL>* preserve_fragment_on_redirect_url) override;
  381. // Resets the callbacks and |stage_blocked_for_callback_|.
  382. void Reset();
  383. // Checks whether we should block in |stage|. If yes, returns an error code
  384. // and optionally sets up callback based on |block_mode_|. If no, returns OK.
  385. int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
  386. // Configuration parameters, can be adjusted by public methods:
  387. const BlockMode block_mode_;
  388. // Values returned on blocking stages when mode is SYNCHRONOUS or
  389. // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
  390. int retval_ = OK;
  391. GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
  392. int block_on_ = 0; // Bit mask: in which stages to block.
  393. // Internal variables, not set by not the user:
  394. // Last blocked stage waiting for user callback (unused if |block_mode_| !=
  395. // USER_CALLBACK).
  396. Stage stage_blocked_for_callback_ = NOT_BLOCKED;
  397. // Callback objects stored during blocking stages.
  398. CompletionOnceCallback callback_;
  399. // Closure to run to exit RunUntilBlocked().
  400. base::OnceClosure on_blocked_;
  401. base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_{this};
  402. };
  403. BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
  404. : block_mode_(block_mode) {}
  405. void BlockingNetworkDelegate::RunUntilBlocked() {
  406. base::RunLoop run_loop;
  407. on_blocked_ = run_loop.QuitClosure();
  408. run_loop.Run();
  409. }
  410. void BlockingNetworkDelegate::DoCallback(int response) {
  411. ASSERT_EQ(USER_CALLBACK, block_mode_);
  412. ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
  413. CompletionOnceCallback callback = std::move(callback_);
  414. Reset();
  415. // |callback| may trigger completion of a request, so post it as a task, so
  416. // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
  417. base::ThreadTaskRunnerHandle::Get()->PostTask(
  418. FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
  419. weak_factory_.GetWeakPtr(), response,
  420. std::move(callback)));
  421. }
  422. void BlockingNetworkDelegate::OnBlocked() {
  423. // If this fails due to |on_blocked_| being null then OnBlocked() was run by
  424. // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
  425. // test.
  426. std::move(on_blocked_).Run();
  427. }
  428. void BlockingNetworkDelegate::RunCallback(int response,
  429. CompletionOnceCallback callback) {
  430. std::move(callback).Run(response);
  431. }
  432. int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
  433. CompletionOnceCallback callback,
  434. GURL* new_url) {
  435. if (redirect_url_ == request->url())
  436. return OK; // We've already seen this request and redirected elsewhere.
  437. // TestNetworkDelegate always completes synchronously.
  438. CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
  439. request, base::NullCallback(), new_url));
  440. if (!redirect_url_.is_empty())
  441. *new_url = redirect_url_;
  442. return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
  443. }
  444. int BlockingNetworkDelegate::OnBeforeStartTransaction(
  445. URLRequest* request,
  446. const HttpRequestHeaders& headers,
  447. OnBeforeStartTransactionCallback callback) {
  448. // TestNetworkDelegate always completes synchronously.
  449. CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
  450. request, headers, base::NullCallback()));
  451. return MaybeBlockStage(
  452. ON_BEFORE_SEND_HEADERS,
  453. base::BindOnce(
  454. [](OnBeforeStartTransactionCallback callback, int result) {
  455. std::move(callback).Run(result, absl::nullopt);
  456. },
  457. std::move(callback)));
  458. }
  459. int BlockingNetworkDelegate::OnHeadersReceived(
  460. URLRequest* request,
  461. CompletionOnceCallback callback,
  462. const HttpResponseHeaders* original_response_headers,
  463. scoped_refptr<HttpResponseHeaders>* override_response_headers,
  464. const IPEndPoint& endpoint,
  465. absl::optional<GURL>* preserve_fragment_on_redirect_url) {
  466. // TestNetworkDelegate always completes synchronously.
  467. CHECK_NE(ERR_IO_PENDING,
  468. TestNetworkDelegate::OnHeadersReceived(
  469. request, base::NullCallback(), original_response_headers,
  470. override_response_headers, endpoint,
  471. preserve_fragment_on_redirect_url));
  472. return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
  473. }
  474. void BlockingNetworkDelegate::Reset() {
  475. EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
  476. stage_blocked_for_callback_ = NOT_BLOCKED;
  477. callback_.Reset();
  478. }
  479. int BlockingNetworkDelegate::MaybeBlockStage(
  480. BlockingNetworkDelegate::Stage stage,
  481. CompletionOnceCallback callback) {
  482. // Check that the user has provided callback for the previous blocked stage.
  483. EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
  484. if ((block_on_ & stage) == 0) {
  485. return OK;
  486. }
  487. switch (block_mode_) {
  488. case SYNCHRONOUS:
  489. EXPECT_NE(OK, retval_);
  490. return retval_;
  491. case AUTO_CALLBACK:
  492. base::ThreadTaskRunnerHandle::Get()->PostTask(
  493. FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
  494. weak_factory_.GetWeakPtr(), retval_,
  495. std::move(callback)));
  496. return ERR_IO_PENDING;
  497. case USER_CALLBACK:
  498. callback_ = std::move(callback);
  499. stage_blocked_for_callback_ = stage;
  500. // We may reach here via a callback prior to RunUntilBlocked(), so post
  501. // a task to fetch and run the |on_blocked_| closure.
  502. base::ThreadTaskRunnerHandle::Get()->PostTask(
  503. FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
  504. weak_factory_.GetWeakPtr()));
  505. return ERR_IO_PENDING;
  506. }
  507. NOTREACHED();
  508. return 0;
  509. }
  510. // A mock ReportSenderInterface that just remembers the latest report
  511. // URI and report to be sent.
  512. class MockCertificateReportSender
  513. : public TransportSecurityState::ReportSenderInterface {
  514. public:
  515. MockCertificateReportSender() = default;
  516. ~MockCertificateReportSender() override = default;
  517. void Send(
  518. const GURL& report_uri,
  519. base::StringPiece content_type,
  520. base::StringPiece report,
  521. const NetworkIsolationKey& network_isolation_key,
  522. base::OnceCallback<void()> success_callback,
  523. base::OnceCallback<void(const GURL&, int, int)> error_callback) override {
  524. latest_report_uri_ = report_uri;
  525. latest_report_.assign(report.data(), report.size());
  526. latest_content_type_.assign(content_type.data(), content_type.size());
  527. latest_network_isolation_key_ = network_isolation_key;
  528. }
  529. const GURL& latest_report_uri() { return latest_report_uri_; }
  530. const std::string& latest_report() { return latest_report_; }
  531. const std::string& latest_content_type() { return latest_content_type_; }
  532. const NetworkIsolationKey& latest_network_isolation_key() {
  533. return latest_network_isolation_key_;
  534. }
  535. private:
  536. GURL latest_report_uri_;
  537. std::string latest_report_;
  538. std::string latest_content_type_;
  539. NetworkIsolationKey latest_network_isolation_key_;
  540. };
  541. // OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
  542. // This is needed because after the certificate failure, the URLRequest will
  543. // retry the connection, and return a partial SSLInfo with a cached cert status.
  544. // The partial SSLInfo does not have the OCSP information filled out.
  545. class OCSPErrorTestDelegate : public TestDelegate {
  546. public:
  547. void OnSSLCertificateError(URLRequest* request,
  548. int net_error,
  549. const SSLInfo& ssl_info,
  550. bool fatal) override {
  551. ssl_info_ = ssl_info;
  552. on_ssl_certificate_error_called_ = true;
  553. TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
  554. }
  555. bool on_ssl_certificate_error_called() {
  556. return on_ssl_certificate_error_called_;
  557. }
  558. SSLInfo ssl_info() { return ssl_info_; }
  559. private:
  560. bool on_ssl_certificate_error_called_ = false;
  561. SSLInfo ssl_info_;
  562. };
  563. #if !BUILDFLAG(IS_IOS)
  564. // Compute the root cert's SPKI hash on the fly, to avoid hardcoding it within
  565. // tests.
  566. bool GetTestRootCertSPKIHash(SHA256HashValue* root_hash) {
  567. scoped_refptr<X509Certificate> root_cert =
  568. ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
  569. if (!root_cert)
  570. return false;
  571. base::StringPiece root_spki;
  572. if (!asn1::ExtractSPKIFromDERCert(
  573. x509_util::CryptoBufferAsStringPiece(root_cert->cert_buffer()),
  574. &root_spki)) {
  575. return false;
  576. }
  577. crypto::SHA256HashString(root_spki, root_hash, sizeof(SHA256HashValue));
  578. return true;
  579. }
  580. #endif
  581. } // namespace
  582. // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
  583. class URLRequestTest : public PlatformTest, public WithTaskEnvironment {
  584. public:
  585. URLRequestTest() = default;
  586. ~URLRequestTest() override {
  587. // URLRequestJobs may post clean-up tasks on destruction.
  588. base::RunLoop().RunUntilIdle();
  589. SetTransportSecurityStateSourceForTesting(nullptr);
  590. }
  591. void SetUp() override {
  592. auto context_builder = CreateTestURLRequestContextBuilder();
  593. context_builder->set_net_log(NetLog::Get());
  594. SetUpContextBuilder(*context_builder);
  595. // We set the TestNetworkDelegate after calling SetUpContextBuilder as
  596. // default_network_delegate() relies on this set up and we don't want to
  597. // allow subclasses to break the assumption.
  598. context_builder->set_network_delegate(
  599. std::make_unique<TestNetworkDelegate>());
  600. default_context_ = context_builder->Build();
  601. PlatformTest::SetUp();
  602. }
  603. void TearDown() override { default_context_.reset(); }
  604. virtual void SetUpContextBuilder(URLRequestContextBuilder& builder) {}
  605. TestNetworkDelegate& default_network_delegate() {
  606. // This cast is safe because we provided a TestNetworkDelegate in SetUp().
  607. return *static_cast<TestNetworkDelegate*>(
  608. default_context_->network_delegate());
  609. }
  610. URLRequestContext& default_context() const { return *default_context_; }
  611. // Creates a temp test file and writes |data| to the file. The file will be
  612. // deleted after the test completes.
  613. void CreateTestFile(const char* data,
  614. size_t data_size,
  615. base::FilePath* test_file) {
  616. ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
  617. // Get an absolute path since |temp_dir| can contain a symbolic link. As of
  618. // now, Mac and Android bots return a path with a symbolic link.
  619. base::FilePath absolute_temp_dir =
  620. base::MakeAbsoluteFilePath(temp_dir_.GetPath());
  621. ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
  622. ASSERT_EQ(static_cast<int>(data_size),
  623. base::WriteFile(*test_file, data, data_size));
  624. }
  625. static std::unique_ptr<ConfiguredProxyResolutionService>
  626. CreateFixedProxyResolutionService(const std::string& proxy) {
  627. return ConfiguredProxyResolutionService::CreateFixedForTest(
  628. proxy, TRAFFIC_ANNOTATION_FOR_TESTS);
  629. }
  630. std::unique_ptr<URLRequest> CreateFirstPartyRequest(
  631. const URLRequestContext& context,
  632. const GURL& url,
  633. URLRequest::Delegate* delegate) {
  634. auto req = context.CreateRequest(url, DEFAULT_PRIORITY, delegate,
  635. TRAFFIC_ANNOTATION_FOR_TESTS);
  636. req->set_initiator(url::Origin::Create(url));
  637. req->set_site_for_cookies(SiteForCookies::FromUrl(url));
  638. return req;
  639. }
  640. protected:
  641. RecordingNetLogObserver net_log_observer_;
  642. std::unique_ptr<URLRequestContext> default_context_;
  643. base::ScopedTempDir temp_dir_;
  644. };
  645. TEST_F(URLRequestTest, AboutBlankTest) {
  646. TestDelegate d;
  647. {
  648. std::unique_ptr<URLRequest> r(
  649. default_context().CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
  650. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  651. r->Start();
  652. EXPECT_TRUE(r->is_pending());
  653. d.RunUntilComplete();
  654. EXPECT_TRUE(!r->is_pending());
  655. EXPECT_FALSE(d.received_data_before_response());
  656. EXPECT_EQ(d.bytes_received(), 0);
  657. EXPECT_TRUE(r->GetResponseRemoteEndpoint().address().empty());
  658. EXPECT_EQ(0, r->GetResponseRemoteEndpoint().port());
  659. }
  660. }
  661. TEST_F(URLRequestTest, InvalidUrlTest) {
  662. TestDelegate d;
  663. {
  664. std::unique_ptr<URLRequest> r(
  665. default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
  666. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  667. r->Start();
  668. EXPECT_TRUE(r->is_pending());
  669. d.RunUntilComplete();
  670. EXPECT_TRUE(d.request_failed());
  671. }
  672. }
  673. // Test that URLRequest rejects WS URLs by default.
  674. TEST_F(URLRequestTest, WsUrlTest) {
  675. const url::Origin kOrigin = url::Origin::Create(GURL("http://foo.test/"));
  676. TestDelegate d;
  677. std::unique_ptr<URLRequest> r(
  678. default_context().CreateRequest(GURL("ws://foo.test/"), DEFAULT_PRIORITY,
  679. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  680. // This is not strictly necessary for this test, but used to trigger a DCHECK.
  681. // See https://crbug.com/1245115.
  682. r->set_isolation_info(
  683. IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
  684. kOrigin, SiteForCookies::FromOrigin(kOrigin)));
  685. r->Start();
  686. d.RunUntilComplete();
  687. EXPECT_TRUE(d.request_failed());
  688. EXPECT_THAT(d.request_status(), IsError(ERR_UNKNOWN_URL_SCHEME));
  689. }
  690. // Test that URLRequest rejects WSS URLs by default.
  691. TEST_F(URLRequestTest, WssUrlTest) {
  692. const url::Origin kOrigin = url::Origin::Create(GURL("https://foo.test/"));
  693. TestDelegate d;
  694. std::unique_ptr<URLRequest> r(
  695. default_context().CreateRequest(GURL("wss://foo.test/"), DEFAULT_PRIORITY,
  696. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  697. // This is not strictly necessary for this test, but used to trigger a DCHECK.
  698. // See https://crbug.com/1245115.
  699. r->set_isolation_info(
  700. IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
  701. kOrigin, SiteForCookies::FromOrigin(kOrigin)));
  702. r->Start();
  703. d.RunUntilComplete();
  704. EXPECT_TRUE(d.request_failed());
  705. EXPECT_THAT(d.request_status(), IsError(ERR_UNKNOWN_URL_SCHEME));
  706. }
  707. TEST_F(URLRequestTest, InvalidReferrerTest) {
  708. default_network_delegate().set_cancel_request_with_policy_violating_referrer(
  709. true);
  710. TestDelegate d;
  711. std::unique_ptr<URLRequest> req = default_context().CreateRequest(
  712. GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
  713. TRAFFIC_ANNOTATION_FOR_TESTS);
  714. req->SetReferrer("https://somewhere.com/");
  715. req->Start();
  716. d.RunUntilComplete();
  717. EXPECT_TRUE(d.request_failed());
  718. }
  719. TEST_F(URLRequestTest, RecordsSameOriginReferrerHistogram) {
  720. default_network_delegate().set_cancel_request_with_policy_violating_referrer(
  721. false);
  722. TestDelegate d;
  723. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  724. GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  725. TRAFFIC_ANNOTATION_FOR_TESTS));
  726. req->SetReferrer("http://google.com");
  727. req->set_referrer_policy(ReferrerPolicy::NEVER_CLEAR);
  728. base::HistogramTester histograms;
  729. req->Start();
  730. d.RunUntilComplete();
  731. histograms.ExpectUniqueSample(
  732. "Net.URLRequest.ReferrerPolicyForRequest.SameOrigin",
  733. static_cast<int>(ReferrerPolicy::NEVER_CLEAR), 1);
  734. }
  735. TEST_F(URLRequestTest, RecordsCrossOriginReferrerHistogram) {
  736. TestDelegate d;
  737. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  738. GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  739. TRAFFIC_ANNOTATION_FOR_TESTS));
  740. req->SetReferrer("http://origin.com");
  741. // Set a different policy just to make sure we aren't always logging the same
  742. // policy.
  743. req->set_referrer_policy(
  744. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE);
  745. base::HistogramTester histograms;
  746. req->Start();
  747. d.RunUntilComplete();
  748. histograms.ExpectUniqueSample(
  749. "Net.URLRequest.ReferrerPolicyForRequest.CrossOrigin",
  750. static_cast<int>(
  751. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
  752. 1);
  753. }
  754. TEST_F(URLRequestTest, RecordsReferrerHistogramAgainOnRedirect) {
  755. auto context_builder = CreateTestURLRequestContextBuilder();
  756. auto network_delegate = std::make_unique<BlockingNetworkDelegate>(
  757. BlockingNetworkDelegate::SYNCHRONOUS);
  758. network_delegate->set_redirect_url(GURL("http://redirect.com/"));
  759. context_builder->set_network_delegate(std::move(network_delegate));
  760. auto context = context_builder->Build();
  761. TestDelegate d;
  762. std::unique_ptr<URLRequest> req(
  763. context->CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  764. TRAFFIC_ANNOTATION_FOR_TESTS));
  765. req->SetReferrer("http://google.com");
  766. req->set_referrer_policy(
  767. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE);
  768. base::HistogramTester histograms;
  769. req->Start();
  770. d.RunUntilRedirect();
  771. histograms.ExpectUniqueSample(
  772. "Net.URLRequest.ReferrerPolicyForRequest.SameOrigin",
  773. static_cast<int>(
  774. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
  775. 1);
  776. req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
  777. /*modified_headers=*/absl::nullopt);
  778. d.RunUntilComplete();
  779. histograms.ExpectUniqueSample(
  780. "Net.URLRequest.ReferrerPolicyForRequest.CrossOrigin",
  781. static_cast<int>(
  782. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
  783. 1);
  784. }
  785. TEST_F(URLRequestTest, RecordsReferrrerWithInformativePath) {
  786. auto context_builder = CreateTestURLRequestContextBuilder();
  787. auto network_delegate = std::make_unique<BlockingNetworkDelegate>(
  788. BlockingNetworkDelegate::SYNCHRONOUS);
  789. network_delegate->set_cancel_request_with_policy_violating_referrer(true);
  790. network_delegate->set_redirect_url(GURL("http://redirect.com/"));
  791. context_builder->set_network_delegate(std::move(network_delegate));
  792. auto context = context_builder->Build();
  793. TestDelegate d;
  794. std::unique_ptr<URLRequest> req(
  795. context->CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  796. TRAFFIC_ANNOTATION_FOR_TESTS));
  797. // Since this referrer is much more informative than the initiating origin,
  798. // we should see the histograms' true buckets populated.
  799. req->SetReferrer("http://google.com/very-informative-path");
  800. base::HistogramTester histograms;
  801. req->Start();
  802. d.RunUntilRedirect();
  803. histograms.ExpectUniqueSample(
  804. "Net.URLRequest.ReferrerHasInformativePath.SameOrigin",
  805. /* Check the count of the "true" bucket in the boolean histogram. */ true,
  806. 1);
  807. req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
  808. /*modified_headers=*/absl::nullopt);
  809. d.RunUntilComplete();
  810. histograms.ExpectUniqueSample(
  811. "Net.URLRequest.ReferrerHasInformativePath.CrossOrigin", true, 1);
  812. }
  813. TEST_F(URLRequestTest, RecordsReferrerWithInformativeQuery) {
  814. auto context_builder = CreateTestURLRequestContextBuilder();
  815. auto network_delegate = std::make_unique<BlockingNetworkDelegate>(
  816. BlockingNetworkDelegate::SYNCHRONOUS);
  817. network_delegate->set_cancel_request_with_policy_violating_referrer(true);
  818. network_delegate->set_redirect_url(GURL("http://redirect.com/"));
  819. context_builder->set_network_delegate(std::move(network_delegate));
  820. auto context = context_builder->Build();
  821. TestDelegate d;
  822. std::unique_ptr<URLRequest> req(
  823. context->CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  824. TRAFFIC_ANNOTATION_FOR_TESTS));
  825. // Since this referrer is much more informative than the initiating origin,
  826. // we should see the histograms' true buckets populated.
  827. req->SetReferrer("http://google.com/?very-informative-query");
  828. base::HistogramTester histograms;
  829. req->Start();
  830. d.RunUntilRedirect();
  831. histograms.ExpectUniqueSample(
  832. "Net.URLRequest.ReferrerHasInformativePath.SameOrigin",
  833. /* Check the count of the "true" bucket in the boolean histogram. */ true,
  834. 1);
  835. req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
  836. /*modified_headers=*/absl::nullopt);
  837. d.RunUntilComplete();
  838. histograms.ExpectUniqueSample(
  839. "Net.URLRequest.ReferrerHasInformativePath.CrossOrigin", true, 1);
  840. }
  841. TEST_F(URLRequestTest, RecordsReferrerWithoutInformativePathOrQuery) {
  842. auto context_builder = CreateTestURLRequestContextBuilder();
  843. auto network_delegate = std::make_unique<BlockingNetworkDelegate>(
  844. BlockingNetworkDelegate::SYNCHRONOUS);
  845. network_delegate->set_cancel_request_with_policy_violating_referrer(false);
  846. network_delegate->set_redirect_url(GURL("http://origin.com/"));
  847. context_builder->set_network_delegate(std::move(network_delegate));
  848. auto context = context_builder->Build();
  849. TestDelegate d;
  850. std::unique_ptr<URLRequest> req(
  851. context->CreateRequest(GURL("http://google.com/"), DEFAULT_PRIORITY, &d,
  852. TRAFFIC_ANNOTATION_FOR_TESTS));
  853. // Since this referrer _isn't_ more informative than the initiating origin,
  854. // we should see the histograms' false buckets populated.
  855. req->SetReferrer("http://origin.com");
  856. base::HistogramTester histograms;
  857. req->Start();
  858. d.RunUntilRedirect();
  859. histograms.ExpectUniqueSample(
  860. "Net.URLRequest.ReferrerHasInformativePath.CrossOrigin", false, 1);
  861. req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
  862. /*modified_headers=*/absl::nullopt);
  863. d.RunUntilComplete();
  864. histograms.ExpectUniqueSample(
  865. "Net.URLRequest.ReferrerHasInformativePath.SameOrigin", false, 1);
  866. }
  867. // A URLRequestInterceptor that allows setting the LoadTimingInfo value of the
  868. // URLRequestJobs it creates.
  869. class URLRequestInterceptorWithLoadTimingInfo : public URLRequestInterceptor {
  870. public:
  871. // Static getters for canned response header and data strings.
  872. static std::string ok_data() { return URLRequestTestJob::test_data_1(); }
  873. static std::string ok_headers() { return URLRequestTestJob::test_headers(); }
  874. URLRequestInterceptorWithLoadTimingInfo() = default;
  875. ~URLRequestInterceptorWithLoadTimingInfo() override = default;
  876. // URLRequestInterceptor implementation:
  877. std::unique_ptr<URLRequestJob> MaybeInterceptRequest(
  878. URLRequest* request) const override {
  879. std::unique_ptr<URLRequestTestJob> job =
  880. std::make_unique<URLRequestTestJob>(request, ok_headers(), ok_data(),
  881. true);
  882. job->set_load_timing_info(main_request_load_timing_info_);
  883. return job;
  884. }
  885. void set_main_request_load_timing_info(
  886. const LoadTimingInfo& main_request_load_timing_info) {
  887. main_request_load_timing_info_ = main_request_load_timing_info;
  888. }
  889. private:
  890. mutable LoadTimingInfo main_request_load_timing_info_;
  891. };
  892. // These tests inject a MockURLRequestInterceptor
  893. class URLRequestLoadTimingTest : public URLRequestTest {
  894. public:
  895. URLRequestLoadTimingTest() {
  896. std::unique_ptr<URLRequestInterceptorWithLoadTimingInfo> interceptor =
  897. std::make_unique<URLRequestInterceptorWithLoadTimingInfo>();
  898. interceptor_ = interceptor.get();
  899. URLRequestFilter::GetInstance()->AddHostnameInterceptor(
  900. "http", "test_intercept", std::move(interceptor));
  901. }
  902. ~URLRequestLoadTimingTest() override {
  903. URLRequestFilter::GetInstance()->ClearHandlers();
  904. }
  905. URLRequestInterceptorWithLoadTimingInfo* interceptor() const {
  906. return interceptor_;
  907. }
  908. private:
  909. raw_ptr<URLRequestInterceptorWithLoadTimingInfo> interceptor_;
  910. };
  911. // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
  912. // reused. |connect_time_flags| is used to indicate if there should be dns
  913. // or SSL times, and |used_proxy| is used for proxy times.
  914. LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
  915. int connect_time_flags,
  916. bool used_proxy) {
  917. LoadTimingInfo load_timing;
  918. load_timing.socket_log_id = 1;
  919. if (used_proxy) {
  920. load_timing.proxy_resolve_start = now + base::Days(1);
  921. load_timing.proxy_resolve_end = now + base::Days(2);
  922. }
  923. LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
  924. if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
  925. connect_timing.dns_start = now + base::Days(3);
  926. connect_timing.dns_end = now + base::Days(4);
  927. }
  928. connect_timing.connect_start = now + base::Days(5);
  929. if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
  930. connect_timing.ssl_start = now + base::Days(6);
  931. connect_timing.ssl_end = now + base::Days(7);
  932. }
  933. connect_timing.connect_end = now + base::Days(8);
  934. load_timing.send_start = now + base::Days(9);
  935. load_timing.send_end = now + base::Days(10);
  936. load_timing.receive_headers_start = now + base::Days(11);
  937. load_timing.receive_headers_end = now + base::Days(12);
  938. return load_timing;
  939. }
  940. // Same as above, but in the case of a reused socket.
  941. LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
  942. bool used_proxy) {
  943. LoadTimingInfo load_timing;
  944. load_timing.socket_log_id = 1;
  945. load_timing.socket_reused = true;
  946. if (used_proxy) {
  947. load_timing.proxy_resolve_start = now + base::Days(1);
  948. load_timing.proxy_resolve_end = now + base::Days(2);
  949. }
  950. load_timing.send_start = now + base::Days(9);
  951. load_timing.send_end = now + base::Days(10);
  952. load_timing.receive_headers_start = now + base::Days(11);
  953. load_timing.receive_headers_end = now + base::Days(12);
  954. return load_timing;
  955. }
  956. LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
  957. const LoadTimingInfo& job_load_timing,
  958. const URLRequestContext& context,
  959. URLRequestInterceptorWithLoadTimingInfo* interceptor) {
  960. interceptor->set_main_request_load_timing_info(job_load_timing);
  961. TestDelegate d;
  962. std::unique_ptr<URLRequest> req(
  963. context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
  964. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  965. req->Start();
  966. d.RunUntilComplete();
  967. LoadTimingInfo resulting_load_timing;
  968. req->GetLoadTimingInfo(&resulting_load_timing);
  969. // None of these should be modified by the URLRequest.
  970. EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
  971. EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
  972. EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
  973. EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
  974. EXPECT_EQ(job_load_timing.receive_headers_start,
  975. resulting_load_timing.receive_headers_start);
  976. EXPECT_EQ(job_load_timing.receive_headers_end,
  977. resulting_load_timing.receive_headers_end);
  978. EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
  979. EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
  980. return resulting_load_timing;
  981. }
  982. // Basic test that the intercept + load timing tests work.
  983. TEST_F(URLRequestLoadTimingTest, InterceptLoadTiming) {
  984. base::TimeTicks now = base::TimeTicks::Now();
  985. LoadTimingInfo job_load_timing =
  986. NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
  987. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  988. job_load_timing, default_context(), interceptor());
  989. // Nothing should have been changed by the URLRequest.
  990. EXPECT_EQ(job_load_timing.proxy_resolve_start,
  991. load_timing_result.proxy_resolve_start);
  992. EXPECT_EQ(job_load_timing.proxy_resolve_end,
  993. load_timing_result.proxy_resolve_end);
  994. EXPECT_EQ(job_load_timing.connect_timing.dns_start,
  995. load_timing_result.connect_timing.dns_start);
  996. EXPECT_EQ(job_load_timing.connect_timing.dns_end,
  997. load_timing_result.connect_timing.dns_end);
  998. EXPECT_EQ(job_load_timing.connect_timing.connect_start,
  999. load_timing_result.connect_timing.connect_start);
  1000. EXPECT_EQ(job_load_timing.connect_timing.connect_end,
  1001. load_timing_result.connect_timing.connect_end);
  1002. EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
  1003. load_timing_result.connect_timing.ssl_start);
  1004. EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
  1005. load_timing_result.connect_timing.ssl_end);
  1006. // Redundant sanity check.
  1007. TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
  1008. }
  1009. // Another basic test, with proxy and SSL times, but no DNS times.
  1010. TEST_F(URLRequestLoadTimingTest, InterceptLoadTimingProxy) {
  1011. base::TimeTicks now = base::TimeTicks::Now();
  1012. LoadTimingInfo job_load_timing =
  1013. NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
  1014. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  1015. job_load_timing, default_context(), interceptor());
  1016. // Nothing should have been changed by the URLRequest.
  1017. EXPECT_EQ(job_load_timing.proxy_resolve_start,
  1018. load_timing_result.proxy_resolve_start);
  1019. EXPECT_EQ(job_load_timing.proxy_resolve_end,
  1020. load_timing_result.proxy_resolve_end);
  1021. EXPECT_EQ(job_load_timing.connect_timing.dns_start,
  1022. load_timing_result.connect_timing.dns_start);
  1023. EXPECT_EQ(job_load_timing.connect_timing.dns_end,
  1024. load_timing_result.connect_timing.dns_end);
  1025. EXPECT_EQ(job_load_timing.connect_timing.connect_start,
  1026. load_timing_result.connect_timing.connect_start);
  1027. EXPECT_EQ(job_load_timing.connect_timing.connect_end,
  1028. load_timing_result.connect_timing.connect_end);
  1029. EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
  1030. load_timing_result.connect_timing.ssl_start);
  1031. EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
  1032. load_timing_result.connect_timing.ssl_end);
  1033. // Redundant sanity check.
  1034. TestLoadTimingNotReusedWithProxy(load_timing_result,
  1035. CONNECT_TIMING_HAS_SSL_TIMES);
  1036. }
  1037. // Make sure that URLRequest correctly adjusts proxy times when they're before
  1038. // |request_start|, due to already having a connected socket. This happens in
  1039. // the case of reusing a SPDY session. The connected socket is not considered
  1040. // reused in this test (May be a preconnect).
  1041. //
  1042. // To mix things up from the test above, assumes DNS times but no SSL times.
  1043. TEST_F(URLRequestLoadTimingTest, InterceptLoadTimingEarlyProxyResolution) {
  1044. base::TimeTicks now = base::TimeTicks::Now();
  1045. LoadTimingInfo job_load_timing =
  1046. NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
  1047. job_load_timing.proxy_resolve_start = now - base::Days(6);
  1048. job_load_timing.proxy_resolve_end = now - base::Days(5);
  1049. job_load_timing.connect_timing.dns_start = now - base::Days(4);
  1050. job_load_timing.connect_timing.dns_end = now - base::Days(3);
  1051. job_load_timing.connect_timing.connect_start = now - base::Days(2);
  1052. job_load_timing.connect_timing.connect_end = now - base::Days(1);
  1053. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  1054. job_load_timing, default_context(), interceptor());
  1055. // Proxy times, connect times, and DNS times should all be replaced with
  1056. // request_start.
  1057. EXPECT_EQ(load_timing_result.request_start,
  1058. load_timing_result.proxy_resolve_start);
  1059. EXPECT_EQ(load_timing_result.request_start,
  1060. load_timing_result.proxy_resolve_end);
  1061. EXPECT_EQ(load_timing_result.request_start,
  1062. load_timing_result.connect_timing.dns_start);
  1063. EXPECT_EQ(load_timing_result.request_start,
  1064. load_timing_result.connect_timing.dns_end);
  1065. EXPECT_EQ(load_timing_result.request_start,
  1066. load_timing_result.connect_timing.connect_start);
  1067. EXPECT_EQ(load_timing_result.request_start,
  1068. load_timing_result.connect_timing.connect_end);
  1069. // Other times should have been left null.
  1070. TestLoadTimingNotReusedWithProxy(load_timing_result,
  1071. CONNECT_TIMING_HAS_DNS_TIMES);
  1072. }
  1073. // Same as above, but in the reused case.
  1074. TEST_F(URLRequestLoadTimingTest,
  1075. InterceptLoadTimingEarlyProxyResolutionReused) {
  1076. base::TimeTicks now = base::TimeTicks::Now();
  1077. LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
  1078. job_load_timing.proxy_resolve_start = now - base::Days(4);
  1079. job_load_timing.proxy_resolve_end = now - base::Days(3);
  1080. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  1081. job_load_timing, default_context(), interceptor());
  1082. // Proxy times and connect times should all be replaced with request_start.
  1083. EXPECT_EQ(load_timing_result.request_start,
  1084. load_timing_result.proxy_resolve_start);
  1085. EXPECT_EQ(load_timing_result.request_start,
  1086. load_timing_result.proxy_resolve_end);
  1087. // Other times should have been left null.
  1088. TestLoadTimingReusedWithProxy(load_timing_result);
  1089. }
  1090. // Make sure that URLRequest correctly adjusts connect times when they're before
  1091. // |request_start|, due to reusing a connected socket. The connected socket is
  1092. // not considered reused in this test (May be a preconnect).
  1093. //
  1094. // To mix things up, the request has SSL times, but no DNS times.
  1095. TEST_F(URLRequestLoadTimingTest, InterceptLoadTimingEarlyConnect) {
  1096. base::TimeTicks now = base::TimeTicks::Now();
  1097. LoadTimingInfo job_load_timing =
  1098. NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
  1099. job_load_timing.connect_timing.connect_start = now - base::Days(1);
  1100. job_load_timing.connect_timing.ssl_start = now - base::Days(2);
  1101. job_load_timing.connect_timing.ssl_end = now - base::Days(3);
  1102. job_load_timing.connect_timing.connect_end = now - base::Days(4);
  1103. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  1104. job_load_timing, default_context(), interceptor());
  1105. // Connect times, and SSL times should be replaced with request_start.
  1106. EXPECT_EQ(load_timing_result.request_start,
  1107. load_timing_result.connect_timing.connect_start);
  1108. EXPECT_EQ(load_timing_result.request_start,
  1109. load_timing_result.connect_timing.ssl_start);
  1110. EXPECT_EQ(load_timing_result.request_start,
  1111. load_timing_result.connect_timing.ssl_end);
  1112. EXPECT_EQ(load_timing_result.request_start,
  1113. load_timing_result.connect_timing.connect_end);
  1114. // Other times should have been left null.
  1115. TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
  1116. }
  1117. // Make sure that URLRequest correctly adjusts connect times when they're before
  1118. // |request_start|, due to reusing a connected socket in the case that there
  1119. // are also proxy times. The connected socket is not considered reused in this
  1120. // test (May be a preconnect).
  1121. //
  1122. // In this test, there are no SSL or DNS times.
  1123. TEST_F(URLRequestLoadTimingTest, InterceptLoadTimingEarlyConnectWithProxy) {
  1124. base::TimeTicks now = base::TimeTicks::Now();
  1125. LoadTimingInfo job_load_timing =
  1126. NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
  1127. job_load_timing.connect_timing.connect_start = now - base::Days(1);
  1128. job_load_timing.connect_timing.connect_end = now - base::Days(2);
  1129. LoadTimingInfo load_timing_result = RunURLRequestInterceptorLoadTimingTest(
  1130. job_load_timing, default_context(), interceptor());
  1131. // Connect times should be replaced with proxy_resolve_end.
  1132. EXPECT_EQ(load_timing_result.proxy_resolve_end,
  1133. load_timing_result.connect_timing.connect_start);
  1134. EXPECT_EQ(load_timing_result.proxy_resolve_end,
  1135. load_timing_result.connect_timing.connect_end);
  1136. // Other times should have been left null.
  1137. TestLoadTimingNotReusedWithProxy(load_timing_result,
  1138. CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
  1139. }
  1140. TEST_F(URLRequestTest, NetworkDelegateProxyError) {
  1141. auto context_builder = CreateTestURLRequestContextBuilder();
  1142. context_builder->set_proxy_resolution_service(
  1143. CreateFixedProxyResolutionService("myproxy:70"));
  1144. auto& network_delegate = *context_builder->set_network_delegate(
  1145. std::make_unique<TestNetworkDelegate>());
  1146. auto host_resolver = std::make_unique<MockHostResolver>();
  1147. host_resolver->rules()->AddSimulatedTimeoutFailure("*");
  1148. context_builder->set_host_resolver(std::move(host_resolver));
  1149. auto context = context_builder->Build();
  1150. TestDelegate d;
  1151. std::unique_ptr<URLRequest> req(
  1152. context->CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
  1153. TRAFFIC_ANNOTATION_FOR_TESTS));
  1154. req->set_method("GET");
  1155. req->Start();
  1156. d.RunUntilComplete();
  1157. // Check we see a failed request.
  1158. // The proxy server should be set before failure.
  1159. EXPECT_EQ(PacResultElementToProxyServer("PROXY myproxy:70"),
  1160. req->proxy_server());
  1161. EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
  1162. EXPECT_THAT(req->response_info().resolve_error_info.error,
  1163. IsError(ERR_DNS_TIMED_OUT));
  1164. EXPECT_EQ(1, network_delegate.error_count());
  1165. EXPECT_THAT(network_delegate.last_error(),
  1166. IsError(ERR_PROXY_CONNECTION_FAILED));
  1167. EXPECT_EQ(1, network_delegate.completed_requests());
  1168. }
  1169. // Test that when host resolution fails with `ERR_DNS_NAME_HTTPS_ONLY` for
  1170. // "http://" requests, scheme is upgraded to "https://".
  1171. TEST_F(URLRequestTest, DnsNameHttpsOnlyErrorCausesSchemeUpgrade) {
  1172. base::test::ScopedFeatureList features;
  1173. features.InitAndEnableFeatureWithParameters(
  1174. features::kUseDnsHttpsSvcb, {{"UseDnsHttpsSvcbHttpUpgrade", "true"}});
  1175. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  1176. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  1177. RegisterDefaultHandlers(&https_server);
  1178. ASSERT_TRUE(https_server.Start());
  1179. // Build an http URL that should be auto-upgraded to https.
  1180. const std::string kHost = "foo.a.test"; // Covered by CERT_TEST_NAMES.
  1181. const GURL https_url = https_server.GetURL(kHost, "/defaultresponse");
  1182. GURL::Replacements replacements;
  1183. replacements.SetSchemeStr(url::kHttpScheme);
  1184. const GURL http_url = https_url.ReplaceComponents(replacements);
  1185. // Return `ERR_DNS_NAME_HTTPS_ONLY` for "http://" requests and an address for
  1186. // "https://" requests. This simulates the HostResolver behavior for a domain
  1187. // with an HTTPS DNS record.
  1188. auto host_resolver = std::make_unique<MockHostResolver>();
  1189. MockHostResolverBase::RuleResolver::RuleKey unencrypted_resolve_key;
  1190. unencrypted_resolve_key.scheme = url::kHttpScheme;
  1191. unencrypted_resolve_key.hostname_pattern = kHost;
  1192. host_resolver->rules()->AddRule(std::move(unencrypted_resolve_key),
  1193. ERR_DNS_NAME_HTTPS_ONLY);
  1194. MockHostResolverBase::RuleResolver::RuleKey encrypted_resolve_key;
  1195. encrypted_resolve_key.scheme = url::kHttpsScheme;
  1196. encrypted_resolve_key.hostname_pattern = kHost;
  1197. host_resolver->rules()->AddRule(std::move(encrypted_resolve_key),
  1198. https_server.GetIPLiteralString());
  1199. auto context_builder = CreateTestURLRequestContextBuilder();
  1200. context_builder->set_host_resolver(std::move(host_resolver));
  1201. auto& network_delegate = *context_builder->set_network_delegate(
  1202. std::make_unique<TestNetworkDelegate>());
  1203. auto context = context_builder->Build();
  1204. TestDelegate d;
  1205. std::unique_ptr<URLRequest> req(context->CreateRequest(
  1206. http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  1207. EXPECT_FALSE(req->url().SchemeIsCryptographic());
  1208. // Note that there is no http server running, so the request should fail or
  1209. // hang if its scheme is not upgraded to https.
  1210. req->Start();
  1211. d.RunUntilComplete();
  1212. EXPECT_EQ(d.received_redirect_count(), 1);
  1213. EXPECT_EQ(0, network_delegate.error_count());
  1214. EXPECT_EQ(200, req->GetResponseCode());
  1215. ASSERT_TRUE(req->response_headers());
  1216. EXPECT_EQ(200, req->response_headers()->response_code());
  1217. // Observe that the scheme has been upgraded to https.
  1218. EXPECT_TRUE(req->url().SchemeIsCryptographic());
  1219. EXPECT_TRUE(req->url().SchemeIs(url::kHttpsScheme));
  1220. }
  1221. // Test that DNS-based scheme upgrade supports deferred redirect.
  1222. TEST_F(URLRequestTest, DnsNameHttpsOnlyErrorCausesSchemeUpgradeDeferred) {
  1223. base::test::ScopedFeatureList features;
  1224. features.InitAndEnableFeatureWithParameters(
  1225. features::kUseDnsHttpsSvcb, {{"UseDnsHttpsSvcbHttpUpgrade", "true"}});
  1226. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  1227. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  1228. RegisterDefaultHandlers(&https_server);
  1229. ASSERT_TRUE(https_server.Start());
  1230. // Build an http URL that should be auto-upgraded to https.
  1231. const std::string kHost = "foo.a.test"; // Covered by CERT_TEST_NAMES.
  1232. const GURL https_url = https_server.GetURL(kHost, "/defaultresponse");
  1233. GURL::Replacements replacements;
  1234. replacements.SetSchemeStr(url::kHttpScheme);
  1235. const GURL http_url = https_url.ReplaceComponents(replacements);
  1236. // Return `ERR_DNS_NAME_HTTPS_ONLY` for "http://" requests and an address for
  1237. // "https://" requests. This simulates the HostResolver behavior for a domain
  1238. // with an HTTPS DNS record.
  1239. auto host_resolver = std::make_unique<MockHostResolver>();
  1240. MockHostResolverBase::RuleResolver::RuleKey unencrypted_resolve_key;
  1241. unencrypted_resolve_key.scheme = url::kHttpScheme;
  1242. unencrypted_resolve_key.hostname_pattern = kHost;
  1243. host_resolver->rules()->AddRule(std::move(unencrypted_resolve_key),
  1244. ERR_DNS_NAME_HTTPS_ONLY);
  1245. MockHostResolverBase::RuleResolver::RuleKey encrypted_resolve_key;
  1246. encrypted_resolve_key.scheme = url::kHttpsScheme;
  1247. encrypted_resolve_key.hostname_pattern = kHost;
  1248. host_resolver->rules()->AddRule(std::move(encrypted_resolve_key),
  1249. https_server.GetIPLiteralString());
  1250. auto context_builder = CreateTestURLRequestContextBuilder();
  1251. context_builder->set_host_resolver(std::move(host_resolver));
  1252. auto& network_delegate = *context_builder->set_network_delegate(
  1253. std::make_unique<TestNetworkDelegate>());
  1254. auto context = context_builder->Build();
  1255. TestDelegate d;
  1256. std::unique_ptr<URLRequest> req(context->CreateRequest(
  1257. http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  1258. EXPECT_FALSE(req->url().SchemeIsCryptographic());
  1259. // Note that there is no http server running, so the request should fail or
  1260. // hang if its scheme is not upgraded to https.
  1261. req->Start();
  1262. d.RunUntilRedirect();
  1263. EXPECT_EQ(d.received_redirect_count(), 1);
  1264. req->FollowDeferredRedirect(/*removed_headers=*/absl::nullopt,
  1265. /*modified_headers=*/absl::nullopt);
  1266. d.RunUntilComplete();
  1267. EXPECT_EQ(0, network_delegate.error_count());
  1268. EXPECT_EQ(200, req->GetResponseCode());
  1269. ASSERT_TRUE(req->response_headers());
  1270. EXPECT_EQ(200, req->response_headers()->response_code());
  1271. // Observe that the scheme has been upgraded to https.
  1272. EXPECT_TRUE(req->url().SchemeIsCryptographic());
  1273. EXPECT_TRUE(req->url().SchemeIs(url::kHttpsScheme));
  1274. }
  1275. #if BUILDFLAG(ENABLE_WEBSOCKETS)
  1276. // Test that requests with "ws" scheme are upgraded to "wss" when DNS
  1277. // indicates that the name is HTTPS-only.
  1278. TEST_F(URLRequestTest, DnsHttpsRecordPresentCausesWsSchemeUpgrade) {
  1279. base::test::ScopedFeatureList features;
  1280. features.InitAndEnableFeatureWithParameters(
  1281. features::kUseDnsHttpsSvcb, {{"UseDnsHttpsSvcbHttpUpgrade", "true"}});
  1282. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  1283. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  1284. RegisterDefaultHandlers(&https_server);
  1285. ASSERT_TRUE(https_server.Start());
  1286. // Build an http URL that should be auto-upgraded to https.
  1287. const std::string kHost = "foo.a.test"; // Covered by CERT_TEST_NAMES.
  1288. const GURL https_url = https_server.GetURL(kHost, "/defaultresponse");
  1289. GURL::Replacements replacements;
  1290. replacements.SetSchemeStr(url::kWsScheme);
  1291. const GURL ws_url = https_url.ReplaceComponents(replacements);
  1292. auto host_resolver = std::make_unique<MockHostResolver>();
  1293. MockHostResolverBase::RuleResolver::RuleKey unencrypted_resolve_key;
  1294. unencrypted_resolve_key.scheme = url::kHttpScheme;
  1295. unencrypted_resolve_key.hostname_pattern = kHost;
  1296. host_resolver->rules()->AddRule(std::move(unencrypted_resolve_key),
  1297. ERR_DNS_NAME_HTTPS_ONLY);
  1298. MockHostResolverBase::RuleResolver::RuleKey encrypted_resolve_key;
  1299. encrypted_resolve_key.scheme = url::kHttpsScheme;
  1300. encrypted_resolve_key.hostname_pattern = kHost;
  1301. host_resolver->rules()->AddRule(std::move(encrypted_resolve_key),
  1302. https_server.GetIPLiteralString());
  1303. auto context_builder = CreateTestURLRequestContextBuilder();
  1304. context_builder->set_host_resolver(std::move(host_resolver));
  1305. auto& network_delegate = *context_builder->set_network_delegate(
  1306. std::make_unique<TestNetworkDelegate>());
  1307. auto context = context_builder->Build();
  1308. TestDelegate d;
  1309. std::unique_ptr<URLRequest> req(context->CreateRequest(
  1310. ws_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS,
  1311. /*is_for_websockets=*/true));
  1312. EXPECT_FALSE(req->url().SchemeIsCryptographic());
  1313. HttpRequestHeaders headers = WebSocketCommonTestHeaders();
  1314. req->SetExtraRequestHeaders(headers);
  1315. auto websocket_stream_create_helper =
  1316. std::make_unique<TestWebSocketHandshakeStreamCreateHelper>();
  1317. req->SetUserData(kWebSocketHandshakeUserDataKey,
  1318. std::move(websocket_stream_create_helper));
  1319. // Note that there is no ws server running, so the request should fail or hang
  1320. // if its scheme is not upgraded to wss.
  1321. req->Start();
  1322. d.RunUntilComplete();
  1323. EXPECT_EQ(d.received_redirect_count(), 1);
  1324. // Expect failure because test server is not set up to provide websocket
  1325. // responses.
  1326. EXPECT_EQ(network_delegate.error_count(), 1);
  1327. EXPECT_EQ(network_delegate.last_error(), ERR_INVALID_RESPONSE);
  1328. // Observe that the scheme has been upgraded to wss.
  1329. EXPECT_TRUE(req->url().SchemeIsCryptographic());
  1330. EXPECT_TRUE(req->url().SchemeIs(url::kWssScheme));
  1331. }
  1332. #endif // BUILDFLAG(ENABLE_WEBSOCKETS)
  1333. TEST_F(URLRequestTest, DnsHttpsRecordAbsentNoSchemeUpgrade) {
  1334. base::test::ScopedFeatureList features;
  1335. features.InitAndEnableFeatureWithParameters(
  1336. features::kUseDnsHttpsSvcb, {{"UseDnsHttpsSvcbHttpUpgrade", "true"}});
  1337. EmbeddedTestServer http_server(EmbeddedTestServer::TYPE_HTTP);
  1338. RegisterDefaultHandlers(&http_server);
  1339. ASSERT_TRUE(http_server.Start());
  1340. // Build an http URL that should be auto-upgraded to https.
  1341. const std::string kHost = "foo.a.test"; // Covered by CERT_TEST_NAMES.
  1342. const GURL http_url = http_server.GetURL(kHost, "/defaultresponse");
  1343. auto context_builder = CreateTestURLRequestContextBuilder();
  1344. auto host_resolver = std::make_unique<MockHostResolver>();
  1345. host_resolver->rules()->AddRule(kHost, http_server.GetIPLiteralString());
  1346. context_builder->set_host_resolver(std::move(host_resolver));
  1347. auto& network_delegate = *context_builder->set_network_delegate(
  1348. std::make_unique<TestNetworkDelegate>());
  1349. auto context = context_builder->Build();
  1350. TestDelegate d;
  1351. std::unique_ptr<URLRequest> req(context->CreateRequest(
  1352. http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  1353. EXPECT_FALSE(req->url().SchemeIsCryptographic());
  1354. req->Start();
  1355. d.RunUntilComplete();
  1356. EXPECT_EQ(d.received_redirect_count(), 0);
  1357. EXPECT_EQ(0, network_delegate.error_count());
  1358. EXPECT_EQ(200, req->GetResponseCode());
  1359. ASSERT_TRUE(req->response_headers());
  1360. EXPECT_EQ(200, req->response_headers()->response_code());
  1361. // Observe that the scheme has not been upgraded.
  1362. EXPECT_EQ(http_url, req->url());
  1363. EXPECT_FALSE(req->url().SchemeIsCryptographic());
  1364. EXPECT_TRUE(req->url().SchemeIs(url::kHttpScheme));
  1365. }
  1366. TEST_F(URLRequestTest, SkipSecureDnsDisabledByDefault) {
  1367. auto context_builder = CreateTestURLRequestContextBuilder();
  1368. auto host_resolver = std::make_unique<MockHostResolver>();
  1369. host_resolver->rules()->AddRule("example.com", "127.0.0.1");
  1370. context_builder->set_host_resolver(std::move(host_resolver));
  1371. auto context = context_builder->Build();
  1372. TestDelegate d;
  1373. std::unique_ptr<URLRequest> req(
  1374. context->CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
  1375. TRAFFIC_ANNOTATION_FOR_TESTS));
  1376. req->Start();
  1377. d.RunUntilComplete();
  1378. EXPECT_EQ(SecureDnsPolicy::kAllow,
  1379. static_cast<MockHostResolver*>(context->host_resolver())
  1380. ->last_secure_dns_policy());
  1381. }
  1382. TEST_F(URLRequestTest, SkipSecureDnsEnabled) {
  1383. auto context_builder = CreateTestURLRequestContextBuilder();
  1384. auto host_resolver = std::make_unique<MockHostResolver>();
  1385. host_resolver->rules()->AddRule("example.com", "127.0.0.1");
  1386. context_builder->set_host_resolver(std::move(host_resolver));
  1387. auto context = context_builder->Build();
  1388. TestDelegate d;
  1389. std::unique_ptr<URLRequest> req(
  1390. context->CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
  1391. TRAFFIC_ANNOTATION_FOR_TESTS));
  1392. req->SetSecureDnsPolicy(SecureDnsPolicy::kDisable);
  1393. req->Start();
  1394. d.RunUntilComplete();
  1395. EXPECT_EQ(SecureDnsPolicy::kDisable,
  1396. static_cast<MockHostResolver*>(context->host_resolver())
  1397. ->last_secure_dns_policy());
  1398. }
  1399. // Make sure that NetworkDelegate::NotifyCompleted is called if
  1400. // content is empty.
  1401. TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
  1402. HttpTestServer test_server;
  1403. ASSERT_TRUE(test_server.Start());
  1404. TestDelegate d;
  1405. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  1406. test_server.GetURL("/nocontent"), DEFAULT_PRIORITY, &d,
  1407. TRAFFIC_ANNOTATION_FOR_TESTS));
  1408. req->Start();
  1409. d.RunUntilComplete();
  1410. EXPECT_THAT(d.request_status(), IsOk());
  1411. EXPECT_EQ(204, req->GetResponseCode());
  1412. EXPECT_EQ("", d.data_received());
  1413. EXPECT_EQ(1, default_network_delegate().completed_requests());
  1414. }
  1415. // Make sure that SetPriority actually sets the URLRequest's priority
  1416. // correctly, both before and after start.
  1417. TEST_F(URLRequestTest, SetPriorityBasic) {
  1418. TestDelegate d;
  1419. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  1420. GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
  1421. TRAFFIC_ANNOTATION_FOR_TESTS));
  1422. EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
  1423. req->SetPriority(LOW);
  1424. EXPECT_EQ(LOW, req->priority());
  1425. req->Start();
  1426. EXPECT_EQ(LOW, req->priority());
  1427. req->SetPriority(MEDIUM);
  1428. EXPECT_EQ(MEDIUM, req->priority());
  1429. }
  1430. // Make sure that URLRequest calls SetPriority on a job before calling
  1431. // Start on it.
  1432. TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
  1433. TestDelegate d;
  1434. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  1435. GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
  1436. TRAFFIC_ANNOTATION_FOR_TESTS));
  1437. EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
  1438. RequestPriority job_priority;
  1439. std::unique_ptr<URLRequestJob> job =
  1440. std::make_unique<PriorityMonitoringURLRequestJob>(req.get(),
  1441. &job_priority);
  1442. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  1443. EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
  1444. req->SetPriority(LOW);
  1445. req->Start();
  1446. EXPECT_EQ(LOW, job_priority);
  1447. }
  1448. // Make sure that URLRequest passes on its priority updates to its
  1449. // job.
  1450. TEST_F(URLRequestTest, SetJobPriority) {
  1451. TestDelegate d;
  1452. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  1453. GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
  1454. TRAFFIC_ANNOTATION_FOR_TESTS));
  1455. RequestPriority job_priority;
  1456. std::unique_ptr<URLRequestJob> job =
  1457. std::make_unique<PriorityMonitoringURLRequestJob>(req.get(),
  1458. &job_priority);
  1459. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  1460. req->SetPriority(LOW);
  1461. req->Start();
  1462. EXPECT_EQ(LOW, job_priority);
  1463. req->SetPriority(MEDIUM);
  1464. EXPECT_EQ(MEDIUM, req->priority());
  1465. EXPECT_EQ(MEDIUM, job_priority);
  1466. }
  1467. // Setting the IGNORE_LIMITS load flag should be okay if the priority
  1468. // is MAXIMUM_PRIORITY.
  1469. TEST_F(URLRequestTest, PriorityIgnoreLimits) {
  1470. TestDelegate d;
  1471. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  1472. GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
  1473. TRAFFIC_ANNOTATION_FOR_TESTS));
  1474. EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
  1475. RequestPriority job_priority;
  1476. std::unique_ptr<URLRequestJob> job =
  1477. std::make_unique<PriorityMonitoringURLRequestJob>(req.get(),
  1478. &job_priority);
  1479. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  1480. req->SetLoadFlags(LOAD_IGNORE_LIMITS);
  1481. EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
  1482. req->SetPriority(MAXIMUM_PRIORITY);
  1483. EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
  1484. req->Start();
  1485. EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
  1486. EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
  1487. }
  1488. // This test verifies that URLRequest::Delegate's OnConnected() callback is
  1489. // never called if the request fails before connecting to a remote endpoint.
  1490. TEST_F(URLRequestTest, NotifyDelegateConnectedSkippedOnEarlyFailure) {
  1491. TestDelegate delegate;
  1492. // The request will never connect to anything because the URL is invalid.
  1493. auto request =
  1494. default_context().CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
  1495. &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
  1496. request->Start();
  1497. delegate.RunUntilComplete();
  1498. EXPECT_THAT(delegate.transports(), IsEmpty());
  1499. }
  1500. // This test verifies that URLRequest::Delegate's OnConnected() method
  1501. // is called once for simple redirect-less requests.
  1502. TEST_F(URLRequestTest, OnConnected) {
  1503. HttpTestServer test_server;
  1504. ASSERT_TRUE(test_server.Start());
  1505. TestDelegate delegate;
  1506. auto request = default_context().CreateRequest(test_server.GetURL("/echo"),
  1507. DEFAULT_PRIORITY, &delegate,
  1508. TRAFFIC_ANNOTATION_FOR_TESTS);
  1509. request->Start();
  1510. delegate.RunUntilComplete();
  1511. TransportInfo expected_transport;
  1512. expected_transport.endpoint =
  1513. IPEndPoint(IPAddress::IPv4Localhost(), test_server.port());
  1514. EXPECT_THAT(delegate.transports(), ElementsAre(expected_transport));
  1515. // Make sure URL_REQUEST_DELEGATE_CONNECTED is logged correctly.
  1516. auto entries = net_log_observer_.GetEntries();
  1517. size_t start_event_index = ExpectLogContainsSomewhere(
  1518. entries, /*min_offset=*/0,
  1519. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::BEGIN);
  1520. size_t end_event_index = ExpectLogContainsSomewhereAfter(
  1521. entries, /*start_offset=*/start_event_index,
  1522. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::END);
  1523. EXPECT_FALSE(LogContainsEntryWithTypeAfter(
  1524. entries, end_event_index + 1,
  1525. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED));
  1526. ASSERT_LT(end_event_index, entries.size());
  1527. EXPECT_FALSE(GetOptionalNetErrorCodeFromParams(entries[end_event_index]));
  1528. }
  1529. // This test verifies that URLRequest::Delegate's OnConnected() method is
  1530. // called after each redirect.
  1531. TEST_F(URLRequestTest, OnConnectedRedirect) {
  1532. HttpTestServer test_server;
  1533. ASSERT_TRUE(test_server.Start());
  1534. TestDelegate delegate;
  1535. // Fetch a page that redirects us once.
  1536. GURL url = test_server.GetURL("/server-redirect?" +
  1537. test_server.GetURL("/echo").spec());
  1538. auto request = default_context().CreateRequest(
  1539. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS);
  1540. request->Start();
  1541. delegate.RunUntilRedirect();
  1542. TransportInfo expected_transport;
  1543. expected_transport.endpoint =
  1544. IPEndPoint(IPAddress::IPv4Localhost(), test_server.port());
  1545. EXPECT_THAT(delegate.transports(), ElementsAre(expected_transport));
  1546. request->FollowDeferredRedirect(/*removed_headers=*/{},
  1547. /*modified_headers=*/{});
  1548. delegate.RunUntilComplete();
  1549. EXPECT_THAT(delegate.transports(),
  1550. ElementsAre(expected_transport, expected_transport));
  1551. }
  1552. // This test verifies that when the URLRequest Delegate returns an error from
  1553. // OnConnected(), the entire request fails with that error.
  1554. TEST_F(URLRequestTest, OnConnectedError) {
  1555. HttpTestServer test_server;
  1556. ASSERT_TRUE(test_server.Start());
  1557. TestDelegate delegate;
  1558. delegate.set_on_connected_result(ERR_NOT_IMPLEMENTED);
  1559. auto request = default_context().CreateRequest(test_server.GetURL("/echo"),
  1560. DEFAULT_PRIORITY, &delegate,
  1561. TRAFFIC_ANNOTATION_FOR_TESTS);
  1562. request->Start();
  1563. delegate.RunUntilComplete();
  1564. TransportInfo expected_transport;
  1565. expected_transport.endpoint =
  1566. IPEndPoint(IPAddress::IPv4Localhost(), test_server.port());
  1567. EXPECT_THAT(delegate.transports(), ElementsAre(expected_transport));
  1568. EXPECT_TRUE(delegate.request_failed());
  1569. EXPECT_THAT(delegate.request_status(), IsError(ERR_NOT_IMPLEMENTED));
  1570. // Make sure URL_REQUEST_DELEGATE_CONNECTED is logged correctly.
  1571. auto entries = net_log_observer_.GetEntries();
  1572. size_t start_event_index = ExpectLogContainsSomewhere(
  1573. entries, /*min_offset=*/0,
  1574. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::BEGIN);
  1575. size_t end_event_index = ExpectLogContainsSomewhereAfter(
  1576. entries, /*start_offset=*/start_event_index,
  1577. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::END);
  1578. EXPECT_FALSE(LogContainsEntryWithTypeAfter(
  1579. entries, end_event_index + 1,
  1580. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED));
  1581. ASSERT_LT(end_event_index, entries.size());
  1582. EXPECT_EQ(ERR_NOT_IMPLEMENTED,
  1583. GetOptionalNetErrorCodeFromParams(entries[end_event_index]));
  1584. }
  1585. TEST_F(URLRequestTest, OnConnectedAsync) {
  1586. HttpTestServer test_server;
  1587. ASSERT_TRUE(test_server.Start());
  1588. TestDelegate d;
  1589. d.set_on_connected_run_callback(true);
  1590. d.set_on_connected_result(OK);
  1591. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1592. default_context(), test_server.GetURL("/defaultresponse"), &d);
  1593. req->Start();
  1594. d.RunUntilComplete();
  1595. EXPECT_THAT(d.request_status(), IsOk());
  1596. // Make sure URL_REQUEST_DELEGATE_CONNECTED is logged correctly.
  1597. auto entries = net_log_observer_.GetEntries();
  1598. size_t start_event_index = ExpectLogContainsSomewhere(
  1599. entries, /*min_offset=*/0,
  1600. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::BEGIN);
  1601. size_t end_event_index = ExpectLogContainsSomewhereAfter(
  1602. entries, /*start_offset=*/start_event_index,
  1603. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::END);
  1604. EXPECT_FALSE(LogContainsEntryWithTypeAfter(
  1605. entries, end_event_index + 1,
  1606. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED));
  1607. ASSERT_LT(end_event_index, entries.size());
  1608. EXPECT_FALSE(GetOptionalNetErrorCodeFromParams(entries[end_event_index]));
  1609. }
  1610. TEST_F(URLRequestTest, OnConnectedAsyncError) {
  1611. HttpTestServer test_server;
  1612. ASSERT_TRUE(test_server.Start());
  1613. TestDelegate d;
  1614. d.set_on_connected_run_callback(true);
  1615. d.set_on_connected_result(ERR_NOT_IMPLEMENTED);
  1616. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1617. default_context(), test_server.GetURL("/defaultresponse"), &d);
  1618. req->Start();
  1619. d.RunUntilComplete();
  1620. EXPECT_THAT(d.request_status(), IsError(ERR_NOT_IMPLEMENTED));
  1621. // Make sure URL_REQUEST_DELEGATE_CONNECTED is logged correctly.
  1622. auto entries = net_log_observer_.GetEntries();
  1623. size_t start_event_index = ExpectLogContainsSomewhere(
  1624. entries, /*min_offset=*/0,
  1625. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::BEGIN);
  1626. size_t end_event_index = ExpectLogContainsSomewhereAfter(
  1627. entries, /*start_offset=*/start_event_index,
  1628. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED, NetLogEventPhase::END);
  1629. EXPECT_FALSE(LogContainsEntryWithTypeAfter(
  1630. entries, end_event_index + 1,
  1631. NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED));
  1632. ASSERT_LT(end_event_index, entries.size());
  1633. EXPECT_EQ(ERR_NOT_IMPLEMENTED,
  1634. GetOptionalNetErrorCodeFromParams(entries[end_event_index]));
  1635. }
  1636. TEST_F(URLRequestTest, DelayedCookieCallback) {
  1637. HttpTestServer test_server;
  1638. ASSERT_TRUE(test_server.Start());
  1639. auto context_builder = CreateTestURLRequestContextBuilder();
  1640. context_builder->SetCookieStore(std::make_unique<DelayedCookieMonster>());
  1641. auto& network_delegate = *context_builder->set_network_delegate(
  1642. std::make_unique<TestNetworkDelegate>());
  1643. auto context = context_builder->Build();
  1644. // Set up a cookie.
  1645. {
  1646. TestDelegate d;
  1647. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1648. *context, test_server.GetURL("/set-cookie?CookieToNotSend=1"), &d);
  1649. req->Start();
  1650. d.RunUntilComplete();
  1651. EXPECT_EQ(0, network_delegate.blocked_annotate_cookies_count());
  1652. EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
  1653. EXPECT_EQ(1, network_delegate.set_cookie_count());
  1654. }
  1655. // Verify that the cookie is set.
  1656. {
  1657. TestDelegate d;
  1658. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1659. *context, test_server.GetURL("/echoheader?Cookie"), &d);
  1660. req->Start();
  1661. d.RunUntilComplete();
  1662. EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") !=
  1663. std::string::npos);
  1664. EXPECT_EQ(0, network_delegate.blocked_annotate_cookies_count());
  1665. EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
  1666. }
  1667. }
  1668. TEST_F(URLRequestTest, DelayedCookieCallbackAsync) {
  1669. HttpTestServer test_server;
  1670. ASSERT_TRUE(test_server.Start());
  1671. // Add a secure cookie so we can try to set an insecure cookie and have
  1672. // SetCanonicalCookie fail.
  1673. GURL::Replacements replace_scheme;
  1674. replace_scheme.SetSchemeStr("https");
  1675. GURL url = test_server.base_url().ReplaceComponents(replace_scheme);
  1676. auto cookie1 = CanonicalCookie::Create(
  1677. url, "AlreadySetCookie=1;Secure", base::Time::Now(),
  1678. absl::nullopt /* server_time */,
  1679. absl::nullopt /* cookie_partition_key */);
  1680. auto delayed_cm = std::make_unique<DelayedCookieMonster>();
  1681. delayed_cm->SetCanonicalCookieAsync(std::move(cookie1), url,
  1682. net::CookieOptions::MakeAllInclusive(),
  1683. CookieStore::SetCookiesCallback());
  1684. auto cookie2 = CanonicalCookie::Create(
  1685. url, "AlreadySetCookie=1;Secure", base::Time::Now(),
  1686. absl::nullopt /* server_time */,
  1687. absl::nullopt /* cookie_partition_key */);
  1688. auto cm = std::make_unique<CookieMonster>(nullptr, nullptr,
  1689. /*first_party_sets_enabled=*/false);
  1690. cm->SetCanonicalCookieAsync(std::move(cookie2), url,
  1691. net::CookieOptions::MakeAllInclusive(),
  1692. CookieStore::SetCookiesCallback());
  1693. auto async_context_builder = CreateTestURLRequestContextBuilder();
  1694. async_context_builder->SetCookieStore(std::move(delayed_cm));
  1695. auto& async_filter_network_delegate =
  1696. *async_context_builder->set_network_delegate(
  1697. std::make_unique<FilteringTestNetworkDelegate>());
  1698. auto async_context = async_context_builder->Build();
  1699. async_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
  1700. TestDelegate async_delegate;
  1701. auto sync_context_builder = CreateTestURLRequestContextBuilder();
  1702. sync_context_builder->SetCookieStore(std::move(cm));
  1703. auto& sync_filter_network_delegate =
  1704. *sync_context_builder->set_network_delegate(
  1705. std::make_unique<FilteringTestNetworkDelegate>());
  1706. auto sync_context = sync_context_builder->Build();
  1707. sync_filter_network_delegate.SetCookieFilter("CookieBlockedOnCanGetCookie");
  1708. TestDelegate sync_delegate;
  1709. std::vector<std::string> cookie_lines(
  1710. {// Fails in SetCanonicalCookie for trying to set a secure cookie
  1711. // on an insecure host.
  1712. "CookieNotSet=1;Secure",
  1713. // Fail in FilteringTestNetworkDelegate::CanGetCookie.
  1714. "CookieBlockedOnCanGetCookie=1",
  1715. // Fails in SetCanonicalCookie for trying to overwrite a secure cookie
  1716. // with an insecure cookie.
  1717. "AlreadySetCookie=1",
  1718. // Succeeds and added cookie to store. Delayed (which makes the callback
  1719. // run asynchronously) in DelayedCookieMonster.
  1720. "CookieSet=1"});
  1721. for (auto first_cookie_line : cookie_lines) {
  1722. for (auto second_cookie_line : cookie_lines) {
  1723. // Run with the delayed cookie monster.
  1724. std::unique_ptr<URLRequest> request = CreateFirstPartyRequest(
  1725. *async_context,
  1726. test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
  1727. second_cookie_line),
  1728. &async_delegate);
  1729. request->Start();
  1730. async_delegate.RunUntilComplete();
  1731. EXPECT_THAT(async_delegate.request_status(), IsOk());
  1732. // Run with the regular cookie monster.
  1733. request = CreateFirstPartyRequest(
  1734. *sync_context,
  1735. test_server.GetURL("/set-cookie?" + first_cookie_line + "&" +
  1736. second_cookie_line),
  1737. &sync_delegate);
  1738. request->Start();
  1739. sync_delegate.RunUntilComplete();
  1740. EXPECT_THAT(sync_delegate.request_status(), IsOk());
  1741. int expected_set_cookie_count = 0;
  1742. int expected_blocked_cookie_count = 0;
  1743. // 2 calls to the delegate's OnCanSetCookie method are expected, even if
  1744. // the cookies don't end up getting set.
  1745. expected_set_cookie_count += 2;
  1746. if (first_cookie_line == "CookieBlockedOnCanGetCookie=1")
  1747. ++expected_blocked_cookie_count;
  1748. if (second_cookie_line == "CookieBlockedOnCanGetCookie=1")
  1749. ++expected_blocked_cookie_count;
  1750. EXPECT_EQ(expected_set_cookie_count,
  1751. async_filter_network_delegate.set_cookie_called_count());
  1752. EXPECT_EQ(expected_blocked_cookie_count,
  1753. async_filter_network_delegate.blocked_set_cookie_count());
  1754. EXPECT_EQ(expected_set_cookie_count,
  1755. sync_filter_network_delegate.set_cookie_called_count());
  1756. EXPECT_EQ(expected_blocked_cookie_count,
  1757. sync_filter_network_delegate.blocked_set_cookie_count());
  1758. async_filter_network_delegate.ResetSetCookieCalledCount();
  1759. async_filter_network_delegate.ResetBlockedSetCookieCount();
  1760. sync_filter_network_delegate.ResetSetCookieCalledCount();
  1761. sync_filter_network_delegate.ResetBlockedSetCookieCount();
  1762. }
  1763. }
  1764. }
  1765. TEST_F(URLRequestTest, DoNotSendCookies) {
  1766. HttpTestServer test_server;
  1767. ASSERT_TRUE(test_server.Start());
  1768. // Set up a cookie.
  1769. {
  1770. TestDelegate d;
  1771. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1772. default_context(), test_server.GetURL("/set-cookie?CookieToNotSend=1"),
  1773. &d);
  1774. req->Start();
  1775. d.RunUntilComplete();
  1776. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1777. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1778. }
  1779. // Verify that the cookie is set.
  1780. {
  1781. TestDelegate d;
  1782. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1783. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1784. req->Start();
  1785. d.RunUntilComplete();
  1786. EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") !=
  1787. std::string::npos);
  1788. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1789. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1790. }
  1791. // Verify that the cookie isn't sent when credentials are not allowed.
  1792. {
  1793. TestDelegate d;
  1794. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1795. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1796. req->set_allow_credentials(false);
  1797. req->Start();
  1798. d.RunUntilComplete();
  1799. EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") ==
  1800. std::string::npos);
  1801. // When credentials are blocked, OnAnnotateAndMoveUserBlockedCookies() is
  1802. // not invoked.
  1803. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1804. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1805. }
  1806. }
  1807. TEST_F(URLRequestTest, DoNotSaveCookies) {
  1808. HttpTestServer test_server;
  1809. ASSERT_TRUE(test_server.Start());
  1810. // Set up a cookie.
  1811. {
  1812. TestDelegate d;
  1813. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1814. default_context(),
  1815. test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), &d);
  1816. req->Start();
  1817. d.RunUntilComplete();
  1818. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1819. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1820. EXPECT_EQ(1, default_network_delegate().set_cookie_count());
  1821. }
  1822. // Try to set-up another cookie and update the previous cookie.
  1823. {
  1824. TestDelegate d;
  1825. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1826. default_context(),
  1827. test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
  1828. &d);
  1829. req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
  1830. req->Start();
  1831. d.RunUntilComplete();
  1832. // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
  1833. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1834. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1835. EXPECT_EQ(1, default_network_delegate().set_cookie_count());
  1836. }
  1837. // Verify the cookies weren't saved or updated.
  1838. {
  1839. TestDelegate d;
  1840. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1841. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1842. req->Start();
  1843. d.RunUntilComplete();
  1844. EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") ==
  1845. std::string::npos);
  1846. EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") !=
  1847. std::string::npos);
  1848. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1849. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1850. EXPECT_EQ(1, default_network_delegate().set_cookie_count());
  1851. }
  1852. }
  1853. TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
  1854. HttpTestServer test_server;
  1855. ASSERT_TRUE(test_server.Start());
  1856. // Set up a cookie.
  1857. {
  1858. TestDelegate d;
  1859. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1860. default_context(), test_server.GetURL("/set-cookie?CookieToNotSend=1"),
  1861. &d);
  1862. req->Start();
  1863. d.RunUntilComplete();
  1864. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1865. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1866. }
  1867. // Verify that the cookie is set.
  1868. {
  1869. TestDelegate d;
  1870. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1871. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1872. req->Start();
  1873. d.RunUntilComplete();
  1874. EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") !=
  1875. std::string::npos);
  1876. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1877. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1878. auto entries = net_log_observer_.GetEntries();
  1879. for (const auto& entry : entries) {
  1880. EXPECT_NE(entry.type,
  1881. NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE);
  1882. }
  1883. }
  1884. // Verify that the cookie isn't sent.
  1885. {
  1886. TestDelegate d;
  1887. default_network_delegate().set_cookie_options(
  1888. TestNetworkDelegate::NO_GET_COOKIES);
  1889. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1890. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1891. req->Start();
  1892. d.RunUntilComplete();
  1893. EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") ==
  1894. std::string::npos);
  1895. EXPECT_EQ(1, default_network_delegate().blocked_annotate_cookies_count());
  1896. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1897. auto entries = net_log_observer_.GetEntries();
  1898. ExpectLogContainsSomewhereAfter(
  1899. entries, 0, NetLogEventType::COOKIE_GET_BLOCKED_BY_NETWORK_DELEGATE,
  1900. NetLogEventPhase::NONE);
  1901. }
  1902. }
  1903. // TODO(crbug.com/564656) This test is flaky on iOS.
  1904. #if BUILDFLAG(IS_IOS)
  1905. #define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
  1906. #else
  1907. #define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
  1908. #endif
  1909. TEST_F(URLRequestTest, MAYBE_DoNotSaveCookies_ViaPolicy) {
  1910. HttpTestServer test_server;
  1911. ASSERT_TRUE(test_server.Start());
  1912. // Set up a cookie.
  1913. {
  1914. TestDelegate d;
  1915. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1916. default_context(),
  1917. test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), &d);
  1918. req->Start();
  1919. d.RunUntilComplete();
  1920. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1921. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1922. auto entries = net_log_observer_.GetEntries();
  1923. for (const auto& entry : entries) {
  1924. EXPECT_NE(entry.type,
  1925. NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
  1926. }
  1927. }
  1928. // Try to set-up another cookie and update the previous cookie.
  1929. {
  1930. TestDelegate d;
  1931. default_network_delegate().set_cookie_options(
  1932. TestNetworkDelegate::NO_SET_COOKIE);
  1933. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1934. default_context(),
  1935. test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
  1936. &d);
  1937. req->Start();
  1938. d.RunUntilComplete();
  1939. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1940. EXPECT_EQ(2, default_network_delegate().blocked_set_cookie_count());
  1941. auto entries = net_log_observer_.GetEntries();
  1942. ExpectLogContainsSomewhereAfter(
  1943. entries, 0, NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE,
  1944. NetLogEventPhase::NONE);
  1945. }
  1946. // Verify the cookies weren't saved or updated.
  1947. {
  1948. TestDelegate d;
  1949. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1950. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1951. req->Start();
  1952. d.RunUntilComplete();
  1953. EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") ==
  1954. std::string::npos);
  1955. EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") !=
  1956. std::string::npos);
  1957. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1958. EXPECT_EQ(2, default_network_delegate().blocked_set_cookie_count());
  1959. }
  1960. }
  1961. TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
  1962. HttpTestServer test_server;
  1963. ASSERT_TRUE(test_server.Start());
  1964. // Set up an empty cookie.
  1965. {
  1966. TestDelegate d;
  1967. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1968. default_context(), test_server.GetURL("/set-cookie"), &d);
  1969. req->Start();
  1970. d.RunUntilComplete();
  1971. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1972. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1973. EXPECT_EQ(0, default_network_delegate().set_cookie_count());
  1974. }
  1975. }
  1976. TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
  1977. HttpTestServer test_server;
  1978. ASSERT_TRUE(test_server.Start());
  1979. // Set up a cookie.
  1980. {
  1981. TestDelegate d;
  1982. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1983. default_context(), test_server.GetURL("/set-cookie?CookieToNotSend=1"),
  1984. &d);
  1985. req->Start();
  1986. d.RunUntilComplete();
  1987. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  1988. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  1989. }
  1990. // Verify that the cookie is set.
  1991. {
  1992. TestDelegate d;
  1993. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  1994. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  1995. req->Start();
  1996. d.RunUntilComplete();
  1997. EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") !=
  1998. std::string::npos);
  1999. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2000. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2001. }
  2002. // Verify that the cookie isn't sent.
  2003. {
  2004. TestDelegate d;
  2005. default_network_delegate().set_cookie_options(
  2006. TestNetworkDelegate::NO_GET_COOKIES);
  2007. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2008. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  2009. req->Start();
  2010. d.RunUntilComplete();
  2011. EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") ==
  2012. std::string::npos);
  2013. EXPECT_EQ(1, default_network_delegate().blocked_annotate_cookies_count());
  2014. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2015. }
  2016. }
  2017. TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
  2018. HttpTestServer test_server;
  2019. ASSERT_TRUE(test_server.Start());
  2020. // Set up a cookie.
  2021. {
  2022. TestDelegate d;
  2023. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2024. default_context(),
  2025. test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), &d);
  2026. req->Start();
  2027. d.RunUntilComplete();
  2028. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2029. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2030. }
  2031. // Try to set-up another cookie and update the previous cookie.
  2032. {
  2033. TestDelegate d;
  2034. default_network_delegate().set_cookie_options(
  2035. TestNetworkDelegate::NO_SET_COOKIE);
  2036. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2037. default_context(),
  2038. test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
  2039. &d);
  2040. req->Start();
  2041. d.RunUntilComplete();
  2042. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2043. EXPECT_EQ(2, default_network_delegate().blocked_set_cookie_count());
  2044. }
  2045. // Verify the cookies weren't saved or updated.
  2046. {
  2047. TestDelegate d;
  2048. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2049. default_context(), test_server.GetURL("/echoheader?Cookie"), &d);
  2050. req->Start();
  2051. d.RunUntilComplete();
  2052. EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") ==
  2053. std::string::npos);
  2054. EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") !=
  2055. std::string::npos);
  2056. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2057. EXPECT_EQ(2, default_network_delegate().blocked_set_cookie_count());
  2058. }
  2059. }
  2060. // Tests for SameSite cookies. The test param indicates whether the same-site
  2061. // calculation considers redirect chains.
  2062. class URLRequestSameSiteCookiesTest
  2063. : public URLRequestTest,
  2064. public ::testing::WithParamInterface<bool> {
  2065. public:
  2066. URLRequestSameSiteCookiesTest() {
  2067. if (DoesCookieSameSiteConsiderRedirectChain()) {
  2068. feature_list_.InitAndEnableFeature(
  2069. features::kCookieSameSiteConsidersRedirectChain);
  2070. }
  2071. }
  2072. bool DoesCookieSameSiteConsiderRedirectChain() { return GetParam(); }
  2073. private:
  2074. base::test::ScopedFeatureList feature_list_;
  2075. };
  2076. TEST_P(URLRequestSameSiteCookiesTest, SameSiteCookies) {
  2077. HttpTestServer test_server;
  2078. ASSERT_TRUE(test_server.Start());
  2079. const std::string kHost = "example.test";
  2080. const std::string kSubHost = "subdomain.example.test";
  2081. const std::string kCrossHost = "cross-origin.test";
  2082. const url::Origin kOrigin =
  2083. url::Origin::Create(test_server.GetURL(kHost, "/"));
  2084. const url::Origin kSubOrigin =
  2085. url::Origin::Create(test_server.GetURL(kSubHost, "/"));
  2086. const url::Origin kCrossOrigin =
  2087. url::Origin::Create(test_server.GetURL(kCrossHost, "/"));
  2088. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  2089. const SiteForCookies kCrossSiteForCookies =
  2090. SiteForCookies::FromOrigin(kCrossOrigin);
  2091. // Set up two 'SameSite' cookies on 'example.test'
  2092. {
  2093. TestDelegate d;
  2094. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2095. default_context(),
  2096. test_server.GetURL(kHost,
  2097. "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
  2098. "LaxSameSiteCookie=1;SameSite=Lax"),
  2099. &d);
  2100. req->set_site_for_cookies(kSiteForCookies);
  2101. req->set_initiator(kOrigin);
  2102. req->Start();
  2103. d.RunUntilComplete();
  2104. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2105. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2106. EXPECT_EQ(2, default_network_delegate().set_cookie_count());
  2107. }
  2108. // Verify that both cookies are sent for same-site requests, whether they are
  2109. // subresource requests, subframe navigations, or main frame navigations.
  2110. for (IsolationInfo::RequestType request_type :
  2111. {IsolationInfo::RequestType::kMainFrame,
  2112. IsolationInfo::RequestType::kSubFrame,
  2113. IsolationInfo::RequestType::kOther}) {
  2114. TestDelegate d;
  2115. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2116. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2117. TRAFFIC_ANNOTATION_FOR_TESTS));
  2118. req->set_isolation_info(IsolationInfo::Create(request_type, kOrigin,
  2119. kOrigin, kSiteForCookies,
  2120. {} /* party_context */));
  2121. req->set_site_for_cookies(kSiteForCookies);
  2122. req->set_initiator(kOrigin);
  2123. req->Start();
  2124. d.RunUntilComplete();
  2125. EXPECT_NE(std::string::npos,
  2126. d.data_received().find("StrictSameSiteCookie=1"));
  2127. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2128. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2129. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2130. }
  2131. // Verify that both cookies are sent when the request has no initiator (can
  2132. // happen for main frame browser-initiated navigations).
  2133. {
  2134. TestDelegate d;
  2135. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2136. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2137. TRAFFIC_ANNOTATION_FOR_TESTS));
  2138. req->set_site_for_cookies(kSiteForCookies);
  2139. req->Start();
  2140. d.RunUntilComplete();
  2141. EXPECT_NE(std::string::npos,
  2142. d.data_received().find("StrictSameSiteCookie=1"));
  2143. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2144. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2145. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2146. }
  2147. // Verify that both cookies are sent for same-registrable-domain requests.
  2148. {
  2149. TestDelegate d;
  2150. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2151. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2152. TRAFFIC_ANNOTATION_FOR_TESTS));
  2153. req->set_site_for_cookies(
  2154. SiteForCookies::FromUrl(test_server.GetURL(kSubHost, "/")));
  2155. req->set_initiator(kSubOrigin);
  2156. req->Start();
  2157. d.RunUntilComplete();
  2158. EXPECT_NE(std::string::npos,
  2159. d.data_received().find("StrictSameSiteCookie=1"));
  2160. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2161. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2162. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2163. }
  2164. // Verify that neither cookie is not sent for cross-site requests.
  2165. {
  2166. TestDelegate d;
  2167. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2168. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2169. TRAFFIC_ANNOTATION_FOR_TESTS));
  2170. req->set_site_for_cookies(kCrossSiteForCookies);
  2171. req->set_initiator(kCrossOrigin);
  2172. req->Start();
  2173. d.RunUntilComplete();
  2174. EXPECT_EQ(std::string::npos,
  2175. d.data_received().find("StrictSameSiteCookie=1"));
  2176. EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2177. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2178. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2179. }
  2180. // Verify that the lax cookie is sent for cross-site initiators when the
  2181. // method is "safe" and the request is a main frame navigation.
  2182. {
  2183. TestDelegate d;
  2184. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2185. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2186. TRAFFIC_ANNOTATION_FOR_TESTS));
  2187. req->set_isolation_info(IsolationInfo::Create(
  2188. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2189. kSiteForCookies, {} /* party_context */));
  2190. req->set_site_for_cookies(kSiteForCookies);
  2191. req->set_initiator(kCrossOrigin);
  2192. req->set_method("GET");
  2193. req->Start();
  2194. d.RunUntilComplete();
  2195. EXPECT_EQ(std::string::npos,
  2196. d.data_received().find("StrictSameSiteCookie=1"));
  2197. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2198. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2199. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2200. }
  2201. // Verify that the lax cookie is sent for cross-site initiators when the
  2202. // method is "safe" and the request is being forced to be considered as a
  2203. // main frame navigation.
  2204. {
  2205. TestDelegate d;
  2206. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2207. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2208. TRAFFIC_ANNOTATION_FOR_TESTS));
  2209. req->set_isolation_info(IsolationInfo::Create(
  2210. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2211. {} /* party_context */));
  2212. req->set_site_for_cookies(kSiteForCookies);
  2213. req->set_initiator(kCrossOrigin);
  2214. req->set_method("GET");
  2215. req->set_force_main_frame_for_same_site_cookies(true);
  2216. req->Start();
  2217. d.RunUntilComplete();
  2218. EXPECT_EQ(std::string::npos,
  2219. d.data_received().find("StrictSameSiteCookie=1"));
  2220. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2221. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2222. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2223. }
  2224. // Verify that neither cookie is sent for cross-site initiators when the
  2225. // method is unsafe (e.g. POST), even if the request is a main frame
  2226. // navigation.
  2227. {
  2228. TestDelegate d;
  2229. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2230. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2231. TRAFFIC_ANNOTATION_FOR_TESTS));
  2232. req->set_isolation_info(IsolationInfo::Create(
  2233. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2234. kSiteForCookies, {} /* party_context */));
  2235. req->set_site_for_cookies(kSiteForCookies);
  2236. req->set_initiator(kCrossOrigin);
  2237. req->set_method("POST");
  2238. req->Start();
  2239. d.RunUntilComplete();
  2240. EXPECT_EQ(std::string::npos,
  2241. d.data_received().find("StrictSameSiteCookie=1"));
  2242. EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2243. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2244. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2245. }
  2246. // Verify that neither cookie is sent for cross-site initiators when the
  2247. // method is safe and the site-for-cookies is same-site, but the request is
  2248. // not a main frame navigation.
  2249. {
  2250. TestDelegate d;
  2251. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2252. test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2253. TRAFFIC_ANNOTATION_FOR_TESTS));
  2254. req->set_isolation_info(IsolationInfo::Create(
  2255. IsolationInfo::RequestType::kSubFrame, kOrigin, kOrigin,
  2256. kSiteForCookies, {} /* party_context */));
  2257. req->set_site_for_cookies(kSiteForCookies);
  2258. req->set_initiator(kCrossOrigin);
  2259. req->set_method("GET");
  2260. req->Start();
  2261. d.RunUntilComplete();
  2262. EXPECT_EQ(std::string::npos,
  2263. d.data_received().find("StrictSameSiteCookie=1"));
  2264. EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2265. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  2266. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  2267. // Check that the appropriate cookie inclusion status is set.
  2268. ASSERT_EQ(2u, req->maybe_sent_cookies().size());
  2269. CookieInclusionStatus expected_strict_status =
  2270. CookieInclusionStatus::MakeFromReasonsForTesting(
  2271. {CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT},
  2272. {} /* warning_reasons */);
  2273. CookieInclusionStatus expected_lax_status =
  2274. CookieInclusionStatus::MakeFromReasonsForTesting(
  2275. {CookieInclusionStatus::EXCLUDE_SAMESITE_LAX},
  2276. {} /* warning_reasons */);
  2277. EXPECT_EQ(expected_strict_status,
  2278. req->maybe_sent_cookies()[0].access_result.status);
  2279. EXPECT_EQ(expected_lax_status,
  2280. req->maybe_sent_cookies()[1].access_result.status);
  2281. }
  2282. }
  2283. TEST_P(URLRequestSameSiteCookiesTest, SameSiteCookies_Redirect) {
  2284. EmbeddedTestServer http_server;
  2285. RegisterDefaultHandlers(&http_server);
  2286. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  2287. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  2288. RegisterDefaultHandlers(&https_server);
  2289. ASSERT_TRUE(http_server.Start());
  2290. ASSERT_TRUE(https_server.Start());
  2291. const std::string kHost = "foo.a.test";
  2292. const std::string kSameSiteHost = "bar.a.test";
  2293. const std::string kCrossSiteHost = "b.test";
  2294. const url::Origin kOrigin =
  2295. url::Origin::Create(https_server.GetURL(kHost, "/"));
  2296. const url::Origin kHttpOrigin =
  2297. url::Origin::Create(http_server.GetURL(kHost, "/"));
  2298. const url::Origin kSameSiteOrigin =
  2299. url::Origin::Create(https_server.GetURL(kSameSiteHost, "/"));
  2300. const url::Origin kCrossSiteOrigin =
  2301. url::Origin::Create(https_server.GetURL(kCrossSiteHost, "/"));
  2302. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  2303. const SiteForCookies kHttpSiteForCookies =
  2304. SiteForCookies::FromOrigin(kHttpOrigin);
  2305. const SiteForCookies kCrossSiteForCookies =
  2306. SiteForCookies::FromOrigin(kCrossSiteOrigin);
  2307. // Set up two 'SameSite' cookies on foo.a.test
  2308. {
  2309. TestDelegate d;
  2310. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  2311. default_context(),
  2312. https_server.GetURL(
  2313. kHost,
  2314. "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
  2315. "LaxSameSiteCookie=1;SameSite=Lax"),
  2316. &d);
  2317. req->set_site_for_cookies(kSiteForCookies);
  2318. req->set_initiator(kOrigin);
  2319. req->Start();
  2320. d.RunUntilComplete();
  2321. ASSERT_EQ(2u, GetAllCookies(&default_context()).size());
  2322. }
  2323. // Verify that both cookies are sent for same-site, unredirected requests.
  2324. {
  2325. TestDelegate d;
  2326. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2327. https_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2328. TRAFFIC_ANNOTATION_FOR_TESTS));
  2329. req->set_site_for_cookies(kSiteForCookies);
  2330. req->set_initiator(kOrigin);
  2331. req->Start();
  2332. d.RunUntilComplete();
  2333. EXPECT_EQ(1u, req->url_chain().size());
  2334. EXPECT_NE(std::string::npos,
  2335. d.data_received().find("StrictSameSiteCookie=1"));
  2336. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2337. }
  2338. // Verify that both cookies are sent for a same-origin redirected top level
  2339. // navigation.
  2340. {
  2341. TestDelegate d;
  2342. GURL url = https_server.GetURL(
  2343. kHost, "/server-redirect?" +
  2344. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2345. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2346. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2347. req->set_isolation_info(IsolationInfo::Create(
  2348. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2349. kSiteForCookies, {} /* party_context */));
  2350. req->set_first_party_url_policy(
  2351. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2352. req->set_site_for_cookies(kSiteForCookies);
  2353. req->set_initiator(kOrigin);
  2354. req->Start();
  2355. d.RunUntilComplete();
  2356. EXPECT_EQ(2u, req->url_chain().size());
  2357. EXPECT_NE(std::string::npos,
  2358. d.data_received().find("StrictSameSiteCookie=1"));
  2359. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2360. }
  2361. // Verify that both cookies are sent for a same-site redirected top level
  2362. // navigation.
  2363. {
  2364. TestDelegate d;
  2365. GURL url = https_server.GetURL(
  2366. kSameSiteHost,
  2367. "/server-redirect?" +
  2368. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2369. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2370. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2371. req->set_isolation_info(IsolationInfo::Create(
  2372. IsolationInfo::RequestType::kMainFrame, kSameSiteOrigin,
  2373. kSameSiteOrigin, kSiteForCookies, {} /* party_context */));
  2374. req->set_first_party_url_policy(
  2375. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2376. req->set_site_for_cookies(kSiteForCookies);
  2377. req->set_initiator(kOrigin);
  2378. req->Start();
  2379. d.RunUntilComplete();
  2380. EXPECT_EQ(2u, req->url_chain().size());
  2381. EXPECT_NE(std::string::npos,
  2382. d.data_received().find("StrictSameSiteCookie=1"));
  2383. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2384. }
  2385. // If redirect chains are considered:
  2386. // Verify that the Strict cookie may or may not be sent for a cross-scheme
  2387. // (same-registrable-domain) redirected top level navigation, depending on the
  2388. // status of Schemeful Same-Site. The Lax cookie is sent regardless, because
  2389. // this is a top-level navigation.
  2390. //
  2391. // If redirect chains are not considered:
  2392. // Verify that both cookies are sent, because this is a top-level navigation.
  2393. {
  2394. base::test::ScopedFeatureList feature_list;
  2395. feature_list.InitAndDisableFeature(features::kSchemefulSameSite);
  2396. TestDelegate d;
  2397. GURL url = http_server.GetURL(
  2398. kHost, "/server-redirect?" +
  2399. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2400. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2401. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2402. req->set_isolation_info(IsolationInfo::Create(
  2403. IsolationInfo::RequestType::kMainFrame, kHttpOrigin, kHttpOrigin,
  2404. kHttpSiteForCookies, {} /* party_context */));
  2405. req->set_first_party_url_policy(
  2406. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2407. req->set_site_for_cookies(kHttpSiteForCookies);
  2408. req->set_initiator(kOrigin);
  2409. req->Start();
  2410. d.RunUntilComplete();
  2411. EXPECT_EQ(2u, req->url_chain().size());
  2412. EXPECT_NE(std::string::npos,
  2413. d.data_received().find("StrictSameSiteCookie=1"));
  2414. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2415. }
  2416. {
  2417. base::test::ScopedFeatureList feature_list;
  2418. feature_list.InitAndEnableFeature(features::kSchemefulSameSite);
  2419. TestDelegate d;
  2420. GURL url = http_server.GetURL(
  2421. kHost, "/server-redirect?" +
  2422. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2423. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2424. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2425. req->set_isolation_info(IsolationInfo::Create(
  2426. IsolationInfo::RequestType::kMainFrame, kHttpOrigin, kHttpOrigin,
  2427. kHttpSiteForCookies, {} /* party_context */));
  2428. req->set_first_party_url_policy(
  2429. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2430. req->set_site_for_cookies(kHttpSiteForCookies);
  2431. req->set_initiator(kOrigin);
  2432. req->Start();
  2433. d.RunUntilComplete();
  2434. EXPECT_EQ(2u, req->url_chain().size());
  2435. EXPECT_EQ(
  2436. DoesCookieSameSiteConsiderRedirectChain(),
  2437. std::string::npos == d.data_received().find("StrictSameSiteCookie=1"));
  2438. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2439. }
  2440. // Verify that (depending on whether redirect chains are considered), the
  2441. // Strict cookie is (not) sent for a cross-site redirected top level
  2442. // navigation...
  2443. {
  2444. TestDelegate d;
  2445. GURL url = https_server.GetURL(
  2446. kCrossSiteHost,
  2447. "/server-redirect?" +
  2448. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2449. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2450. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2451. req->set_isolation_info(IsolationInfo::Create(
  2452. IsolationInfo::RequestType::kMainFrame, kCrossSiteOrigin,
  2453. kCrossSiteOrigin, kCrossSiteForCookies, {} /* party_context */));
  2454. req->set_first_party_url_policy(
  2455. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2456. req->set_site_for_cookies(kCrossSiteForCookies);
  2457. req->set_initiator(kOrigin);
  2458. req->Start();
  2459. d.RunUntilComplete();
  2460. EXPECT_EQ(2u, req->url_chain().size());
  2461. EXPECT_EQ(
  2462. DoesCookieSameSiteConsiderRedirectChain(),
  2463. std::string::npos == d.data_received().find("StrictSameSiteCookie=1"));
  2464. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2465. }
  2466. // ... even if the initial URL is same-site.
  2467. {
  2468. TestDelegate d;
  2469. GURL middle_url = https_server.GetURL(
  2470. kCrossSiteHost,
  2471. "/server-redirect?" +
  2472. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2473. GURL url =
  2474. https_server.GetURL(kHost, "/server-redirect?" + middle_url.spec());
  2475. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2476. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2477. req->set_isolation_info(IsolationInfo::Create(
  2478. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2479. kSiteForCookies, {} /* party_context */));
  2480. req->set_first_party_url_policy(
  2481. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2482. req->set_site_for_cookies(kSiteForCookies);
  2483. req->set_initiator(kOrigin);
  2484. req->Start();
  2485. d.RunUntilComplete();
  2486. EXPECT_EQ(3u, req->url_chain().size());
  2487. EXPECT_EQ(
  2488. DoesCookieSameSiteConsiderRedirectChain(),
  2489. std::string::npos == d.data_received().find("StrictSameSiteCookie=1"));
  2490. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2491. }
  2492. // Verify that (depending on whether redirect chains are considered), neither
  2493. // (or both) SameSite cookie is sent for a cross-site redirected subresource
  2494. // request...
  2495. {
  2496. TestDelegate d;
  2497. GURL url = https_server.GetURL(
  2498. kCrossSiteHost,
  2499. "/server-redirect?" +
  2500. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2501. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2502. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2503. req->set_isolation_info(IsolationInfo::Create(
  2504. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2505. {} /* party_context */));
  2506. req->set_site_for_cookies(kSiteForCookies);
  2507. req->set_initiator(kOrigin);
  2508. req->Start();
  2509. d.RunUntilComplete();
  2510. EXPECT_EQ(2u, req->url_chain().size());
  2511. EXPECT_EQ(
  2512. DoesCookieSameSiteConsiderRedirectChain(),
  2513. std::string::npos == d.data_received().find("StrictSameSiteCookie=1"));
  2514. EXPECT_EQ(
  2515. DoesCookieSameSiteConsiderRedirectChain(),
  2516. std::string::npos == d.data_received().find("LaxSameSiteCookie=1"));
  2517. }
  2518. // ... even if the initial URL is same-site.
  2519. {
  2520. TestDelegate d;
  2521. GURL middle_url = https_server.GetURL(
  2522. kCrossSiteHost,
  2523. "/server-redirect?" +
  2524. https_server.GetURL(kHost, "/echoheader?Cookie").spec());
  2525. GURL url =
  2526. https_server.GetURL(kHost, "/server-redirect?" + middle_url.spec());
  2527. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2528. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2529. req->set_isolation_info(IsolationInfo::Create(
  2530. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2531. {} /* party_context */));
  2532. req->set_site_for_cookies(kSiteForCookies);
  2533. req->set_initiator(kOrigin);
  2534. req->Start();
  2535. d.RunUntilComplete();
  2536. EXPECT_EQ(3u, req->url_chain().size());
  2537. EXPECT_EQ(
  2538. DoesCookieSameSiteConsiderRedirectChain(),
  2539. std::string::npos == d.data_received().find("StrictSameSiteCookie=1"));
  2540. EXPECT_EQ(
  2541. DoesCookieSameSiteConsiderRedirectChain(),
  2542. std::string::npos == d.data_received().find("LaxSameSiteCookie=1"));
  2543. }
  2544. }
  2545. TEST_P(URLRequestSameSiteCookiesTest, SettingSameSiteCookies) {
  2546. HttpTestServer test_server;
  2547. ASSERT_TRUE(test_server.Start());
  2548. const std::string kHost = "example.test";
  2549. const std::string kSubHost = "subdomain.example.test";
  2550. const std::string kCrossHost = "cross-origin.test";
  2551. const url::Origin kOrigin =
  2552. url::Origin::Create(test_server.GetURL(kHost, "/"));
  2553. const url::Origin kSubOrigin =
  2554. url::Origin::Create(test_server.GetURL(kSubHost, "/"));
  2555. const url::Origin kCrossOrigin =
  2556. url::Origin::Create(test_server.GetURL(kCrossHost, "/"));
  2557. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  2558. const SiteForCookies kCrossSiteForCookies =
  2559. SiteForCookies::FromOrigin(kCrossOrigin);
  2560. int expected_cookies = 0;
  2561. {
  2562. TestDelegate d;
  2563. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2564. test_server.GetURL(kHost,
  2565. "/set-cookie?Strict1=1;SameSite=Strict&"
  2566. "Lax1=1;SameSite=Lax"),
  2567. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2568. req->set_site_for_cookies(kSiteForCookies);
  2569. req->set_initiator(kOrigin);
  2570. // 'SameSite' cookies are settable from strict same-site contexts
  2571. // (same-origin site_for_cookies, same-origin initiator), so this request
  2572. // should result in two cookies being set.
  2573. expected_cookies += 2;
  2574. req->Start();
  2575. d.RunUntilComplete();
  2576. EXPECT_EQ(expected_cookies,
  2577. static_cast<int>(GetAllCookies(&default_context()).size()));
  2578. EXPECT_EQ(expected_cookies, default_network_delegate().set_cookie_count());
  2579. }
  2580. {
  2581. TestDelegate d;
  2582. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2583. test_server.GetURL(kHost,
  2584. "/set-cookie?Strict2=1;SameSite=Strict&"
  2585. "Lax2=1;SameSite=Lax"),
  2586. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2587. req->set_isolation_info(IsolationInfo::Create(
  2588. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2589. kSiteForCookies, {} /* party_context */));
  2590. req->set_site_for_cookies(kSiteForCookies);
  2591. req->set_initiator(kCrossOrigin);
  2592. // 'SameSite' cookies are settable from lax same-site contexts (same-origin
  2593. // site_for_cookies, cross-site initiator, main frame navigation), so this
  2594. // request should result in two cookies being set.
  2595. expected_cookies += 2;
  2596. req->Start();
  2597. d.RunUntilComplete();
  2598. EXPECT_EQ(expected_cookies,
  2599. static_cast<int>(GetAllCookies(&default_context()).size()));
  2600. EXPECT_EQ(expected_cookies, default_network_delegate().set_cookie_count());
  2601. }
  2602. {
  2603. TestDelegate d;
  2604. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2605. test_server.GetURL(kHost,
  2606. "/set-cookie?Strict3=1;SameSite=Strict&"
  2607. "Lax3=1;SameSite=Lax"),
  2608. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2609. req->set_isolation_info(IsolationInfo::Create(
  2610. IsolationInfo::RequestType::kMainFrame, kSubOrigin, kSubOrigin,
  2611. kSiteForCookies, {} /* party_context */));
  2612. req->set_site_for_cookies(
  2613. SiteForCookies::FromUrl(test_server.GetURL(kSubHost, "/")));
  2614. req->set_initiator(kCrossOrigin);
  2615. // 'SameSite' cookies are settable from lax same-site contexts (same-site
  2616. // site_for_cookies, cross-site initiator, main frame navigation), so this
  2617. // request should result in two cookies being set.
  2618. expected_cookies += 2;
  2619. req->Start();
  2620. d.RunUntilComplete();
  2621. EXPECT_EQ(expected_cookies,
  2622. static_cast<int>(GetAllCookies(&default_context()).size()));
  2623. EXPECT_EQ(expected_cookies, default_network_delegate().set_cookie_count());
  2624. }
  2625. {
  2626. TestDelegate d;
  2627. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2628. test_server.GetURL(kHost,
  2629. "/set-cookie?Strict4=1;SameSite=Strict&"
  2630. "Lax4=1;SameSite=Lax"),
  2631. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2632. req->set_site_for_cookies(
  2633. SiteForCookies::FromUrl(test_server.GetURL(kSubHost, "/")));
  2634. // 'SameSite' cookies are settable from strict same-site contexts (same-site
  2635. // site_for_cookies, no initiator), so this request should result in two
  2636. // cookies being set.
  2637. expected_cookies += 2;
  2638. req->Start();
  2639. d.RunUntilComplete();
  2640. EXPECT_EQ(expected_cookies,
  2641. static_cast<int>(GetAllCookies(&default_context()).size()));
  2642. EXPECT_EQ(expected_cookies, default_network_delegate().set_cookie_count());
  2643. }
  2644. int expected_network_delegate_set_cookie_count;
  2645. {
  2646. TestDelegate d;
  2647. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2648. test_server.GetURL(kHost,
  2649. "/set-cookie?Strict5=1;SameSite=Strict&"
  2650. "Lax5=1;SameSite=Lax"),
  2651. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2652. req->set_site_for_cookies(kCrossSiteForCookies);
  2653. req->set_initiator(kCrossOrigin);
  2654. // 'SameSite' cookies are not settable from cross-site contexts, so this
  2655. // should not result in any new cookies being set.
  2656. expected_cookies += 0;
  2657. // This counts the number of successful calls to CanSetCookie() when
  2658. // attempting to set a cookie. The two cookies above were created and
  2659. // attempted to be set, and were not rejected by the NetworkDelegate, so the
  2660. // count here is 2 more than the number of cookies actually set.
  2661. expected_network_delegate_set_cookie_count = expected_cookies + 2;
  2662. req->Start();
  2663. d.RunUntilComplete();
  2664. // This counts the number of cookies actually set.
  2665. EXPECT_EQ(expected_cookies,
  2666. static_cast<int>(GetAllCookies(&default_context()).size()));
  2667. EXPECT_EQ(expected_network_delegate_set_cookie_count,
  2668. default_network_delegate().set_cookie_count());
  2669. }
  2670. {
  2671. TestDelegate d;
  2672. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2673. test_server.GetURL(kHost,
  2674. "/set-cookie?Strict6=1;SameSite=Strict&"
  2675. "Lax6=1;SameSite=Lax"),
  2676. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2677. req->set_isolation_info(IsolationInfo::Create(
  2678. IsolationInfo::RequestType::kSubFrame, kOrigin, kOrigin,
  2679. kSiteForCookies, {} /* party_context */));
  2680. req->set_site_for_cookies(kSiteForCookies);
  2681. req->set_initiator(kCrossOrigin);
  2682. // Same-site site-for-cookies, cross-site initiator, non main frame
  2683. // navigation -> context is considered cross-site so no SameSite cookies are
  2684. // set.
  2685. expected_cookies += 0;
  2686. // This counts the number of successful calls to CanSetCookie() when
  2687. // attempting to set a cookie. The two cookies above were created and
  2688. // attempted to be set, and were not rejected by the NetworkDelegate, so the
  2689. // count here is 2 more than the number of cookies actually set.
  2690. expected_network_delegate_set_cookie_count += 2;
  2691. req->Start();
  2692. d.RunUntilComplete();
  2693. EXPECT_EQ(expected_cookies,
  2694. static_cast<int>(GetAllCookies(&default_context()).size()));
  2695. EXPECT_EQ(expected_network_delegate_set_cookie_count,
  2696. default_network_delegate().set_cookie_count());
  2697. // Check that the appropriate cookie inclusion status is set.
  2698. ASSERT_EQ(2u, req->maybe_stored_cookies().size());
  2699. CookieInclusionStatus expected_strict_status =
  2700. CookieInclusionStatus::MakeFromReasonsForTesting(
  2701. {CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT},
  2702. {} /* warning_reasons */);
  2703. CookieInclusionStatus expected_lax_status =
  2704. CookieInclusionStatus::MakeFromReasonsForTesting(
  2705. {CookieInclusionStatus::EXCLUDE_SAMESITE_LAX},
  2706. {} /* warning_reasons */);
  2707. EXPECT_EQ(expected_strict_status,
  2708. req->maybe_stored_cookies()[0].access_result.status);
  2709. EXPECT_EQ(expected_lax_status,
  2710. req->maybe_stored_cookies()[1].access_result.status);
  2711. }
  2712. {
  2713. TestDelegate d;
  2714. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2715. test_server.GetURL(kHost,
  2716. "/set-cookie?Strict7=1;SameSite=Strict&"
  2717. "Lax7=1;SameSite=Lax"),
  2718. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2719. req->set_isolation_info(IsolationInfo::Create(
  2720. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2721. {} /* party_context */));
  2722. req->set_site_for_cookies(kSiteForCookies);
  2723. req->set_initiator(kCrossOrigin);
  2724. req->set_force_main_frame_for_same_site_cookies(true);
  2725. // 'SameSite' cookies are settable from lax same-site contexts (same-origin
  2726. // site_for_cookies, cross-site initiator, main frame navigation), so this
  2727. // request should result in two cookies being set.
  2728. expected_cookies += 2;
  2729. expected_network_delegate_set_cookie_count += 2;
  2730. req->Start();
  2731. d.RunUntilComplete();
  2732. EXPECT_EQ(expected_cookies,
  2733. static_cast<int>(GetAllCookies(&default_context()).size()));
  2734. EXPECT_EQ(expected_network_delegate_set_cookie_count,
  2735. default_network_delegate().set_cookie_count());
  2736. }
  2737. }
  2738. // Tests special chrome:// scheme that is supposed to always attach SameSite
  2739. // cookies if the requested site is secure.
  2740. TEST_P(URLRequestSameSiteCookiesTest, SameSiteCookiesSpecialScheme) {
  2741. url::ScopedSchemeRegistryForTests scoped_registry;
  2742. url::AddStandardScheme("chrome", url::SchemeType::SCHEME_WITH_HOST);
  2743. EmbeddedTestServer https_test_server(EmbeddedTestServer::TYPE_HTTPS);
  2744. RegisterDefaultHandlers(&https_test_server);
  2745. ASSERT_TRUE(https_test_server.Start());
  2746. EmbeddedTestServer http_test_server(EmbeddedTestServer::TYPE_HTTP);
  2747. RegisterDefaultHandlers(&http_test_server);
  2748. ASSERT_TRUE(http_test_server.Start());
  2749. ASSERT_NE(https_test_server.port(), http_test_server.port());
  2750. // Both hostnames should be 127.0.0.1 (so that we can use the same set of
  2751. // cookies on both, for convenience).
  2752. ASSERT_EQ(https_test_server.host_port_pair().host(),
  2753. http_test_server.host_port_pair().host());
  2754. // Set up special schemes
  2755. auto cad = std::make_unique<TestCookieAccessDelegate>();
  2756. cad->SetIgnoreSameSiteRestrictionsScheme("chrome", true);
  2757. auto cm = std::make_unique<CookieMonster>(nullptr, nullptr,
  2758. /*first_party_sets_enabled=*/false);
  2759. cm->SetCookieAccessDelegate(std::move(cad));
  2760. auto context_builder = CreateTestURLRequestContextBuilder();
  2761. context_builder->SetCookieStore(std::move(cm));
  2762. auto context = context_builder->Build();
  2763. // SameSite cookies are not set for 'chrome' scheme if requested origin is not
  2764. // secure.
  2765. {
  2766. TestDelegate d;
  2767. std::unique_ptr<URLRequest> req(context->CreateRequest(
  2768. http_test_server.GetURL(
  2769. "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
  2770. "LaxSameSiteCookie=1;SameSite=Lax"),
  2771. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2772. req->set_site_for_cookies(
  2773. SiteForCookies::FromUrl(GURL("chrome://whatever/")));
  2774. req->Start();
  2775. d.RunUntilComplete();
  2776. EXPECT_EQ(0u, GetAllCookies(context.get()).size());
  2777. }
  2778. // But they are set for 'chrome' scheme if the requested origin is secure.
  2779. {
  2780. TestDelegate d;
  2781. std::unique_ptr<URLRequest> req(context->CreateRequest(
  2782. https_test_server.GetURL(
  2783. "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
  2784. "LaxSameSiteCookie=1;SameSite=Lax"),
  2785. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2786. req->set_site_for_cookies(
  2787. SiteForCookies::FromUrl(GURL("chrome://whatever/")));
  2788. req->Start();
  2789. d.RunUntilComplete();
  2790. CookieList cookies = GetAllCookies(context.get());
  2791. EXPECT_EQ(2u, cookies.size());
  2792. }
  2793. // Verify that they are both sent when the site_for_cookies scheme is
  2794. // 'chrome' and the requested origin is secure.
  2795. {
  2796. TestDelegate d;
  2797. std::unique_ptr<URLRequest> req(context->CreateRequest(
  2798. https_test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2799. TRAFFIC_ANNOTATION_FOR_TESTS));
  2800. req->set_site_for_cookies(
  2801. SiteForCookies::FromUrl(GURL("chrome://whatever/")));
  2802. req->Start();
  2803. d.RunUntilComplete();
  2804. EXPECT_NE(std::string::npos,
  2805. d.data_received().find("StrictSameSiteCookie=1"));
  2806. EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
  2807. }
  2808. // Verify that they are not sent when the site_for_cookies scheme is
  2809. // 'chrome' and the requested origin is not secure.
  2810. {
  2811. TestDelegate d;
  2812. std::unique_ptr<URLRequest> req(context->CreateRequest(
  2813. http_test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
  2814. TRAFFIC_ANNOTATION_FOR_TESTS));
  2815. req->set_site_for_cookies(
  2816. SiteForCookies::FromUrl(GURL("chrome://whatever/")));
  2817. req->Start();
  2818. d.RunUntilComplete();
  2819. EXPECT_EQ(std::string::npos,
  2820. d.data_received().find("StrictSameSiteCookie"));
  2821. EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie"));
  2822. }
  2823. }
  2824. TEST_P(URLRequestSameSiteCookiesTest, SettingSameSiteCookies_Redirect) {
  2825. EmbeddedTestServer http_server;
  2826. RegisterDefaultHandlers(&http_server);
  2827. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  2828. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  2829. RegisterDefaultHandlers(&https_server);
  2830. ASSERT_TRUE(http_server.Start());
  2831. ASSERT_TRUE(https_server.Start());
  2832. auto& network_delegate = default_network_delegate();
  2833. const std::string kHost = "foo.a.test";
  2834. const std::string kSameSiteHost = "bar.a.test";
  2835. const std::string kCrossSiteHost = "b.test";
  2836. const url::Origin kOrigin =
  2837. url::Origin::Create(https_server.GetURL(kHost, "/"));
  2838. const url::Origin kHttpOrigin =
  2839. url::Origin::Create(http_server.GetURL(kHost, "/"));
  2840. const url::Origin kSameSiteOrigin =
  2841. url::Origin::Create(https_server.GetURL(kSameSiteHost, "/"));
  2842. const url::Origin kCrossSiteOrigin =
  2843. url::Origin::Create(https_server.GetURL(kCrossSiteHost, "/"));
  2844. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  2845. const SiteForCookies kHttpSiteForCookies =
  2846. SiteForCookies::FromOrigin(kHttpOrigin);
  2847. const SiteForCookies kCrossSiteForCookies =
  2848. SiteForCookies::FromOrigin(kCrossSiteOrigin);
  2849. int expected_cookies = 0;
  2850. int expected_set_cookie_count = 0;
  2851. // Verify that SameSite cookies can be set for a same-origin redirected
  2852. // top-level navigation request.
  2853. {
  2854. TestDelegate d;
  2855. GURL set_cookie_url = https_server.GetURL(
  2856. kHost, "/set-cookie?Strict1=1;SameSite=Strict&Lax1=1;SameSite=Lax");
  2857. GURL url =
  2858. https_server.GetURL(kHost, "/server-redirect?" + set_cookie_url.spec());
  2859. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2860. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2861. req->set_isolation_info(IsolationInfo::Create(
  2862. IsolationInfo::RequestType::kMainFrame, kOrigin, kOrigin,
  2863. kSiteForCookies, {} /* party_context */));
  2864. req->set_first_party_url_policy(
  2865. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2866. req->set_site_for_cookies(kSiteForCookies);
  2867. req->set_initiator(kOrigin);
  2868. expected_cookies += 2;
  2869. expected_set_cookie_count += 2;
  2870. req->Start();
  2871. d.RunUntilComplete();
  2872. EXPECT_EQ(expected_cookies,
  2873. static_cast<int>(GetAllCookies(&default_context()).size()));
  2874. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2875. }
  2876. // Verify that SameSite cookies can be set for a same-site redirected
  2877. // top-level navigation request.
  2878. {
  2879. TestDelegate d;
  2880. GURL set_cookie_url = https_server.GetURL(
  2881. kHost, "/set-cookie?Strict2=1;SameSite=Strict&Lax2=1;SameSite=Lax");
  2882. GURL url = https_server.GetURL(kSameSiteHost,
  2883. "/server-redirect?" + set_cookie_url.spec());
  2884. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2885. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2886. req->set_isolation_info(IsolationInfo::Create(
  2887. IsolationInfo::RequestType::kMainFrame, kSameSiteOrigin,
  2888. kSameSiteOrigin, kSiteForCookies, {} /* party_context */));
  2889. req->set_first_party_url_policy(
  2890. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2891. req->set_site_for_cookies(kSiteForCookies);
  2892. req->set_initiator(kSameSiteOrigin);
  2893. expected_cookies += 2;
  2894. expected_set_cookie_count += 2;
  2895. req->Start();
  2896. d.RunUntilComplete();
  2897. EXPECT_EQ(expected_cookies,
  2898. static_cast<int>(GetAllCookies(&default_context()).size()));
  2899. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2900. }
  2901. // Verify that SameSite cookies can be set for a cross-site redirected
  2902. // top-level navigation request.
  2903. {
  2904. TestDelegate d;
  2905. GURL set_cookie_url = https_server.GetURL(
  2906. kHost, "/set-cookie?Strict3=1;SameSite=Strict&Lax3=1;SameSite=Lax");
  2907. GURL url = https_server.GetURL(kCrossSiteHost,
  2908. "/server-redirect?" + set_cookie_url.spec());
  2909. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2910. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2911. req->set_isolation_info(IsolationInfo::Create(
  2912. IsolationInfo::RequestType::kMainFrame, kCrossSiteOrigin,
  2913. kCrossSiteOrigin, kCrossSiteForCookies, {} /* party_context */));
  2914. req->set_first_party_url_policy(
  2915. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  2916. req->set_site_for_cookies(kCrossSiteForCookies);
  2917. req->set_initiator(kCrossSiteOrigin);
  2918. expected_cookies += 2;
  2919. expected_set_cookie_count += 2;
  2920. req->Start();
  2921. d.RunUntilComplete();
  2922. EXPECT_EQ(expected_cookies,
  2923. static_cast<int>(GetAllCookies(&default_context()).size()));
  2924. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2925. }
  2926. // Verify that SameSite cookies can be set for a same-origin redirected
  2927. // subresource request.
  2928. {
  2929. TestDelegate d;
  2930. GURL set_cookie_url = https_server.GetURL(
  2931. kHost, "/set-cookie?Strict4=1;SameSite=Strict&Lax4=1;SameSite=Lax");
  2932. GURL url =
  2933. https_server.GetURL(kHost, "/server-redirect?" + set_cookie_url.spec());
  2934. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2935. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2936. req->set_isolation_info(IsolationInfo::Create(
  2937. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2938. {} /* party_context */));
  2939. req->set_site_for_cookies(kSiteForCookies);
  2940. req->set_initiator(kOrigin);
  2941. expected_cookies += 2;
  2942. expected_set_cookie_count += 2;
  2943. req->Start();
  2944. d.RunUntilComplete();
  2945. EXPECT_EQ(expected_cookies,
  2946. static_cast<int>(GetAllCookies(&default_context()).size()));
  2947. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2948. }
  2949. // Verify that SameSite cookies can be set for a same-site redirected
  2950. // subresource request.
  2951. {
  2952. TestDelegate d;
  2953. GURL set_cookie_url = https_server.GetURL(
  2954. kHost, "/set-cookie?Strict5=1;SameSite=Strict&Lax5=1;SameSite=Lax");
  2955. GURL url = https_server.GetURL(kSameSiteHost,
  2956. "/server-redirect?" + set_cookie_url.spec());
  2957. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2958. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2959. req->set_isolation_info(IsolationInfo::Create(
  2960. IsolationInfo::RequestType::kOther, kSameSiteOrigin, kSameSiteOrigin,
  2961. kSiteForCookies, {} /* party_context */));
  2962. req->set_site_for_cookies(kSiteForCookies);
  2963. req->set_initiator(kSameSiteOrigin);
  2964. expected_cookies += 2;
  2965. expected_set_cookie_count += 2;
  2966. req->Start();
  2967. d.RunUntilComplete();
  2968. EXPECT_EQ(expected_cookies,
  2969. static_cast<int>(GetAllCookies(&default_context()).size()));
  2970. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2971. }
  2972. // Verify that (depending on whether redirect chains are considered) SameSite
  2973. // cookies can/cannot be set for a cross-site redirected subresource request,
  2974. // even if the site-for-cookies and initiator are same-site, ...
  2975. {
  2976. TestDelegate d;
  2977. GURL set_cookie_url = https_server.GetURL(
  2978. kHost, "/set-cookie?Strict6=1;SameSite=Strict&Lax6=1;SameSite=Lax");
  2979. GURL url = https_server.GetURL(kCrossSiteHost,
  2980. "/server-redirect?" + set_cookie_url.spec());
  2981. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  2982. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  2983. req->set_isolation_info(IsolationInfo::Create(
  2984. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  2985. {} /* party_context */));
  2986. req->set_site_for_cookies(kSiteForCookies);
  2987. req->set_initiator(kOrigin);
  2988. expected_cookies += DoesCookieSameSiteConsiderRedirectChain() ? 0 : 2;
  2989. expected_set_cookie_count += 2;
  2990. req->Start();
  2991. d.RunUntilComplete();
  2992. EXPECT_EQ(expected_cookies,
  2993. static_cast<int>(GetAllCookies(&default_context()).size()));
  2994. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  2995. }
  2996. // ... even if the initial URL is same-site.
  2997. {
  2998. TestDelegate d;
  2999. GURL set_cookie_url = https_server.GetURL(
  3000. kHost, "/set-cookie?Strict7=1;SameSite=Strict&Lax7=1;SameSite=Lax");
  3001. GURL middle_url = https_server.GetURL(
  3002. kCrossSiteHost, "/server-redirect?" + set_cookie_url.spec());
  3003. GURL url =
  3004. https_server.GetURL(kHost, "/server-redirect?" + middle_url.spec());
  3005. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  3006. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3007. req->set_isolation_info(IsolationInfo::Create(
  3008. IsolationInfo::RequestType::kOther, kOrigin, kOrigin, kSiteForCookies,
  3009. {} /* party_context */));
  3010. req->set_site_for_cookies(kSiteForCookies);
  3011. req->set_initiator(kOrigin);
  3012. expected_cookies += DoesCookieSameSiteConsiderRedirectChain() ? 0 : 2;
  3013. expected_set_cookie_count += 2;
  3014. req->Start();
  3015. d.RunUntilComplete();
  3016. EXPECT_EQ(expected_cookies,
  3017. static_cast<int>(GetAllCookies(&default_context()).size()));
  3018. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  3019. }
  3020. // Verify that SameSite cookies may or may not be set for a cross-scheme
  3021. // (same-registrable-domain) redirected subresource request, depending on the
  3022. // status of Schemeful Same-Site and whether redirect chains are considered.
  3023. {
  3024. base::test::ScopedFeatureList feature_list;
  3025. feature_list.InitAndDisableFeature(features::kSchemefulSameSite);
  3026. TestDelegate d;
  3027. GURL set_cookie_url = https_server.GetURL(
  3028. kHost, "/set-cookie?Strict8=1;SameSite=Strict&Lax8=1;SameSite=Lax");
  3029. GURL url =
  3030. http_server.GetURL(kHost, "/server-redirect?" + set_cookie_url.spec());
  3031. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  3032. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3033. req->set_isolation_info(IsolationInfo::Create(
  3034. IsolationInfo::RequestType::kOther, kHttpOrigin, kHttpOrigin,
  3035. kHttpSiteForCookies, {} /* party_context */));
  3036. req->set_first_party_url_policy(
  3037. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  3038. req->set_site_for_cookies(kHttpSiteForCookies);
  3039. req->set_initiator(kOrigin);
  3040. expected_cookies += 2;
  3041. expected_set_cookie_count += 2;
  3042. req->Start();
  3043. d.RunUntilComplete();
  3044. EXPECT_EQ(expected_cookies,
  3045. static_cast<int>(GetAllCookies(&default_context()).size()));
  3046. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  3047. }
  3048. {
  3049. base::test::ScopedFeatureList feature_list;
  3050. feature_list.InitAndEnableFeature(features::kSchemefulSameSite);
  3051. TestDelegate d;
  3052. GURL set_cookie_url = https_server.GetURL(
  3053. kHost, "/set-cookie?Strict9=1;SameSite=Strict&Lax9=1;SameSite=Lax");
  3054. GURL url =
  3055. http_server.GetURL(kHost, "/server-redirect?" + set_cookie_url.spec());
  3056. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  3057. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3058. req->set_isolation_info(IsolationInfo::Create(
  3059. IsolationInfo::RequestType::kOther, kHttpOrigin, kHttpOrigin,
  3060. kHttpSiteForCookies, {} /* party_context */));
  3061. req->set_first_party_url_policy(
  3062. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  3063. req->set_site_for_cookies(kHttpSiteForCookies);
  3064. req->set_initiator(kOrigin);
  3065. expected_cookies += DoesCookieSameSiteConsiderRedirectChain() ? 0 : 2;
  3066. expected_set_cookie_count += 2;
  3067. req->Start();
  3068. d.RunUntilComplete();
  3069. EXPECT_EQ(expected_cookies,
  3070. static_cast<int>(GetAllCookies(&default_context()).size()));
  3071. EXPECT_EQ(expected_set_cookie_count, network_delegate.set_cookie_count());
  3072. }
  3073. }
  3074. INSTANTIATE_TEST_SUITE_P(/* no label */,
  3075. URLRequestSameSiteCookiesTest,
  3076. ::testing::Bool());
  3077. // Tests that __Secure- cookies can't be set on non-secure origins.
  3078. TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
  3079. EmbeddedTestServer http_server;
  3080. RegisterDefaultHandlers(&http_server);
  3081. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  3082. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  3083. RegisterDefaultHandlers(&https_server);
  3084. ASSERT_TRUE(http_server.Start());
  3085. ASSERT_TRUE(https_server.Start());
  3086. // Try to set a Secure __Secure- cookie on http://a.test (non-secure origin).
  3087. {
  3088. TestDelegate d;
  3089. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3090. default_context(),
  3091. http_server.GetURL("a.test",
  3092. "/set-cookie?__Secure-nonsecure-origin=1;Secure&"
  3093. "cookienotsecure=1"),
  3094. &d);
  3095. req->Start();
  3096. d.RunUntilComplete();
  3097. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3098. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3099. }
  3100. // Verify that the __Secure- cookie was not set by checking cookies for
  3101. // https://a.test (secure origin).
  3102. {
  3103. TestDelegate d;
  3104. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3105. default_context(), https_server.GetURL("a.test", "/echoheader?Cookie"),
  3106. &d);
  3107. req->Start();
  3108. d.RunUntilComplete();
  3109. EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
  3110. std::string::npos);
  3111. EXPECT_NE(d.data_received().find("cookienotsecure=1"), std::string::npos);
  3112. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3113. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3114. }
  3115. }
  3116. TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
  3117. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  3118. RegisterDefaultHandlers(&https_server);
  3119. ASSERT_TRUE(https_server.Start());
  3120. // Try to set a non-Secure __Secure- cookie.
  3121. {
  3122. TestDelegate d;
  3123. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3124. default_context(), https_server.GetURL("/set-cookie?__Secure-foo=1"),
  3125. &d);
  3126. req->Start();
  3127. d.RunUntilComplete();
  3128. EXPECT_EQ(0, default_network_delegate().set_cookie_count());
  3129. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3130. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3131. }
  3132. // Verify that the cookie is not set.
  3133. {
  3134. TestDelegate d;
  3135. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3136. default_context(), https_server.GetURL("/echoheader?Cookie"), &d);
  3137. req->Start();
  3138. d.RunUntilComplete();
  3139. EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
  3140. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3141. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3142. }
  3143. }
  3144. TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
  3145. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  3146. RegisterDefaultHandlers(&https_server);
  3147. ASSERT_TRUE(https_server.Start());
  3148. // Try to set a Secure __Secure- cookie.
  3149. {
  3150. TestDelegate d;
  3151. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3152. default_context(),
  3153. https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"), &d);
  3154. req->Start();
  3155. d.RunUntilComplete();
  3156. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3157. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3158. }
  3159. // Verify that the cookie is set.
  3160. {
  3161. TestDelegate d;
  3162. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3163. default_context(), https_server.GetURL("/echoheader?Cookie"), &d);
  3164. req->Start();
  3165. d.RunUntilComplete();
  3166. EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
  3167. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3168. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3169. }
  3170. }
  3171. // Tests that secure cookies can't be set on non-secure origins if strict secure
  3172. // cookies are enabled.
  3173. TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
  3174. EmbeddedTestServer http_server;
  3175. RegisterDefaultHandlers(&http_server);
  3176. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  3177. https_server.SetSSLConfig(EmbeddedTestServer::CERT_TEST_NAMES);
  3178. RegisterDefaultHandlers(&https_server);
  3179. ASSERT_TRUE(http_server.Start());
  3180. ASSERT_TRUE(https_server.Start());
  3181. // Try to set a Secure cookie and a non-Secure cookie from a nonsecure origin.
  3182. {
  3183. TestDelegate d;
  3184. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3185. default_context(),
  3186. http_server.GetURL("a.test",
  3187. "/set-cookie?nonsecure-origin=1;Secure&"
  3188. "cookienotsecure=1"),
  3189. &d);
  3190. req->Start();
  3191. d.RunUntilComplete();
  3192. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3193. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3194. }
  3195. // Verify that the Secure cookie was not set.
  3196. {
  3197. TestDelegate d;
  3198. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3199. default_context(), https_server.GetURL("a.test", "/echoheader?Cookie"),
  3200. &d);
  3201. req->Start();
  3202. d.RunUntilComplete();
  3203. EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
  3204. EXPECT_NE(d.data_received().find("cookienotsecure=1"), std::string::npos);
  3205. EXPECT_EQ(0, default_network_delegate().blocked_annotate_cookies_count());
  3206. EXPECT_EQ(0, default_network_delegate().blocked_set_cookie_count());
  3207. }
  3208. }
  3209. // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
  3210. // value for the `fixed_date_` member.
  3211. class FixedDateNetworkDelegate : public TestNetworkDelegate {
  3212. public:
  3213. explicit FixedDateNetworkDelegate(base::StringPiece fixed_date)
  3214. : fixed_date_(fixed_date) {}
  3215. FixedDateNetworkDelegate(const FixedDateNetworkDelegate&) = delete;
  3216. FixedDateNetworkDelegate& operator=(const FixedDateNetworkDelegate&) = delete;
  3217. ~FixedDateNetworkDelegate() override = default;
  3218. void set_fixed_date(base::StringPiece fixed_date) {
  3219. fixed_date_ = static_cast<std::string>(fixed_date);
  3220. }
  3221. // NetworkDelegate implementation
  3222. int OnHeadersReceived(
  3223. URLRequest* request,
  3224. CompletionOnceCallback callback,
  3225. const HttpResponseHeaders* original_response_headers,
  3226. scoped_refptr<HttpResponseHeaders>* override_response_headers,
  3227. const IPEndPoint& endpoint,
  3228. absl::optional<GURL>* preserve_fragment_on_redirect_url) override;
  3229. private:
  3230. std::string fixed_date_;
  3231. };
  3232. int FixedDateNetworkDelegate::OnHeadersReceived(
  3233. URLRequest* request,
  3234. CompletionOnceCallback callback,
  3235. const HttpResponseHeaders* original_response_headers,
  3236. scoped_refptr<HttpResponseHeaders>* override_response_headers,
  3237. const IPEndPoint& endpoint,
  3238. absl::optional<GURL>* preserve_fragment_on_redirect_url) {
  3239. *override_response_headers = base::MakeRefCounted<HttpResponseHeaders>(
  3240. original_response_headers->raw_headers());
  3241. (*override_response_headers)->SetHeader("Date", fixed_date_);
  3242. return TestNetworkDelegate::OnHeadersReceived(
  3243. request, std::move(callback), original_response_headers,
  3244. override_response_headers, endpoint, preserve_fragment_on_redirect_url);
  3245. }
  3246. // Test that cookie expiration times are adjusted for server/client clock
  3247. // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
  3248. // headers by defaulting to GMT. (crbug.com/135131)
  3249. TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
  3250. HttpTestServer test_server;
  3251. ASSERT_TRUE(test_server.Start());
  3252. auto context_builder = CreateTestURLRequestContextBuilder();
  3253. auto& network_delegate = *context_builder->set_network_delegate(
  3254. std::make_unique<FixedDateNetworkDelegate>("04-Jan-2004 04:09:25 UTC"));
  3255. auto context = context_builder->Build();
  3256. // Set up an expired cookie.
  3257. {
  3258. TestDelegate d;
  3259. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3260. *context,
  3261. test_server.GetURL(
  3262. "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
  3263. &d);
  3264. req->Start();
  3265. d.RunUntilComplete();
  3266. }
  3267. // Verify that the cookie is not set.
  3268. {
  3269. TestDelegate d;
  3270. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3271. *context, test_server.GetURL("/echoheader?Cookie"), &d);
  3272. req->Start();
  3273. d.RunUntilComplete();
  3274. EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
  3275. }
  3276. // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
  3277. {
  3278. TestDelegate d;
  3279. network_delegate.set_fixed_date("18-Apr-1977 22:49:13 UTC");
  3280. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3281. *context,
  3282. test_server.GetURL(
  3283. "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
  3284. &d);
  3285. req->Start();
  3286. d.RunUntilComplete();
  3287. }
  3288. // Verify that the cookie is set.
  3289. {
  3290. TestDelegate d;
  3291. std::unique_ptr<URLRequest> req = CreateFirstPartyRequest(
  3292. *context, test_server.GetURL("/echoheader?Cookie"), &d);
  3293. req->Start();
  3294. d.RunUntilComplete();
  3295. EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
  3296. }
  3297. }
  3298. // Check that it is impossible to change the referrer in the extra headers of
  3299. // an URLRequest.
  3300. TEST_F(URLRequestTest, DoNotOverrideReferrer) {
  3301. HttpTestServer test_server;
  3302. ASSERT_TRUE(test_server.Start());
  3303. // If extra headers contain referer and the request contains a referer,
  3304. // only the latter shall be respected.
  3305. {
  3306. TestDelegate d;
  3307. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  3308. test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  3309. TRAFFIC_ANNOTATION_FOR_TESTS));
  3310. req->SetReferrer("http://foo.com/");
  3311. HttpRequestHeaders headers;
  3312. headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
  3313. req->SetExtraRequestHeaders(headers);
  3314. req->Start();
  3315. d.RunUntilComplete();
  3316. EXPECT_EQ("http://foo.com/", d.data_received());
  3317. }
  3318. // If extra headers contain a referer but the request does not, no referer
  3319. // shall be sent in the header.
  3320. {
  3321. TestDelegate d;
  3322. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  3323. test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  3324. TRAFFIC_ANNOTATION_FOR_TESTS));
  3325. HttpRequestHeaders headers;
  3326. headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
  3327. req->SetExtraRequestHeaders(headers);
  3328. req->SetLoadFlags(LOAD_VALIDATE_CACHE);
  3329. req->Start();
  3330. d.RunUntilComplete();
  3331. EXPECT_EQ("None", d.data_received());
  3332. }
  3333. }
  3334. class URLRequestTestHTTP : public URLRequestTest {
  3335. public:
  3336. const url::Origin origin1_;
  3337. const url::Origin origin2_;
  3338. const IsolationInfo isolation_info1_;
  3339. const IsolationInfo isolation_info2_;
  3340. URLRequestTestHTTP()
  3341. : origin1_(url::Origin::Create(GURL("https://foo.test/"))),
  3342. origin2_(url::Origin::Create(GURL("https://bar.test/"))),
  3343. isolation_info1_(IsolationInfo::CreateForInternalRequest(origin1_)),
  3344. isolation_info2_(IsolationInfo::CreateForInternalRequest(origin2_)),
  3345. test_server_(base::FilePath(kTestFilePath)) {
  3346. // Needed for NetworkIsolationKey to make it down to the socket layer, for
  3347. // the PKP violation report test.
  3348. feature_list_.InitAndEnableFeature(
  3349. net::features::kPartitionConnectionsByNetworkIsolationKey);
  3350. }
  3351. protected:
  3352. // ProtocolHandler for the scheme that's unsafe to redirect to.
  3353. class NET_EXPORT UnsafeRedirectProtocolHandler
  3354. : public URLRequestJobFactory::ProtocolHandler {
  3355. public:
  3356. UnsafeRedirectProtocolHandler() = default;
  3357. UnsafeRedirectProtocolHandler(const UnsafeRedirectProtocolHandler&) =
  3358. delete;
  3359. UnsafeRedirectProtocolHandler& operator=(
  3360. const UnsafeRedirectProtocolHandler&) = delete;
  3361. ~UnsafeRedirectProtocolHandler() override = default;
  3362. // URLRequestJobFactory::ProtocolHandler implementation:
  3363. std::unique_ptr<URLRequestJob> CreateJob(
  3364. URLRequest* request) const override {
  3365. NOTREACHED();
  3366. return nullptr;
  3367. }
  3368. bool IsSafeRedirectTarget(const GURL& location) const override {
  3369. return false;
  3370. }
  3371. };
  3372. // URLRequestTest interface:
  3373. void SetUpContextBuilder(URLRequestContextBuilder& builder) override {
  3374. // Add support for an unsafe scheme to the default URLRequestContext.
  3375. builder.SetProtocolHandler(
  3376. "unsafe", std::make_unique<UnsafeRedirectProtocolHandler>());
  3377. }
  3378. // Requests |redirect_url|, which must return a HTTP 3xx redirect.
  3379. // |request_method| is the method to use for the initial request.
  3380. // |redirect_method| is the method that is expected to be used for the second
  3381. // request, after redirection.
  3382. // If |include_data| is true, data is uploaded with the request. The
  3383. // response body is expected to match it exactly, if and only if
  3384. // |request_method| == |redirect_method|.
  3385. void HTTPRedirectMethodTest(const GURL& redirect_url,
  3386. const std::string& request_method,
  3387. const std::string& redirect_method,
  3388. bool include_data) {
  3389. static const char kData[] = "hello world";
  3390. TestDelegate d;
  3391. std::unique_ptr<URLRequest> req =
  3392. CreateFirstPartyRequest(default_context(), redirect_url, &d);
  3393. req->set_method(request_method);
  3394. if (include_data) {
  3395. req->set_upload(CreateSimpleUploadData(kData));
  3396. HttpRequestHeaders headers;
  3397. headers.SetHeader(HttpRequestHeaders::kContentLength,
  3398. base::NumberToString(std::size(kData) - 1));
  3399. headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
  3400. req->SetExtraRequestHeaders(headers);
  3401. }
  3402. req->Start();
  3403. d.RunUntilComplete();
  3404. EXPECT_EQ(redirect_method, req->method());
  3405. EXPECT_EQ(OK, d.request_status());
  3406. if (include_data) {
  3407. if (request_method == redirect_method) {
  3408. EXPECT_TRUE(req->extra_request_headers().HasHeader(
  3409. HttpRequestHeaders::kContentLength));
  3410. EXPECT_TRUE(req->extra_request_headers().HasHeader(
  3411. HttpRequestHeaders::kContentType));
  3412. EXPECT_EQ(kData, d.data_received());
  3413. } else {
  3414. EXPECT_FALSE(req->extra_request_headers().HasHeader(
  3415. HttpRequestHeaders::kContentLength));
  3416. EXPECT_FALSE(req->extra_request_headers().HasHeader(
  3417. HttpRequestHeaders::kContentType));
  3418. EXPECT_NE(kData, d.data_received());
  3419. }
  3420. }
  3421. if (HasFailure())
  3422. LOG(WARNING) << "Request method was: " << request_method;
  3423. }
  3424. // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
  3425. // used as the initial origin.
  3426. // |request_method| is the method to use for the initial request.
  3427. // |redirect_method| is the method that is expected to be used for the second
  3428. // request, after redirection.
  3429. // |expected_origin_value| is the expected value for the Origin header after
  3430. // redirection. If empty, expects that there will be no Origin header.
  3431. void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
  3432. const std::string& request_method,
  3433. const std::string& redirect_method,
  3434. const std::string& expected_origin_value) {
  3435. TestDelegate d;
  3436. std::unique_ptr<URLRequest> req =
  3437. CreateFirstPartyRequest(default_context(), redirect_url, &d);
  3438. req->set_method(request_method);
  3439. req->SetExtraRequestHeaderByName(
  3440. HttpRequestHeaders::kOrigin,
  3441. redirect_url.DeprecatedGetOriginAsURL().spec(), false);
  3442. req->Start();
  3443. d.RunUntilComplete();
  3444. EXPECT_EQ(redirect_method, req->method());
  3445. // Note that there is no check for request success here because, for
  3446. // purposes of testing, the request very well may fail. For example, if the
  3447. // test redirects to an HTTPS server from an HTTP origin, thus it is cross
  3448. // origin, there is not an HTTPS server in this unit test framework, so the
  3449. // request would fail. However, that's fine, as long as the request headers
  3450. // are in order and pass the checks below.
  3451. if (expected_origin_value.empty()) {
  3452. EXPECT_FALSE(
  3453. req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
  3454. } else {
  3455. std::string origin_header;
  3456. EXPECT_TRUE(req->extra_request_headers().GetHeader(
  3457. HttpRequestHeaders::kOrigin, &origin_header));
  3458. EXPECT_EQ(expected_origin_value, origin_header);
  3459. }
  3460. }
  3461. void HTTPUploadDataOperationTest(const std::string& method) {
  3462. const int kMsgSize = 20000; // multiple of 10
  3463. const int kIterations = 50;
  3464. auto uploadBytes = std::make_unique<char[]>(kMsgSize + 1);
  3465. char* ptr = uploadBytes.get();
  3466. char marker = 'a';
  3467. for (int idx = 0; idx < kMsgSize / 10; idx++) {
  3468. memcpy(ptr, "----------", 10);
  3469. ptr += 10;
  3470. if (idx % 100 == 0) {
  3471. ptr--;
  3472. *ptr++ = marker;
  3473. if (++marker > 'z')
  3474. marker = 'a';
  3475. }
  3476. }
  3477. uploadBytes[kMsgSize] = '\0';
  3478. for (int i = 0; i < kIterations; ++i) {
  3479. TestDelegate d;
  3480. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  3481. test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
  3482. TRAFFIC_ANNOTATION_FOR_TESTS));
  3483. r->set_method(method.c_str());
  3484. r->set_upload(CreateSimpleUploadData(uploadBytes.get()));
  3485. r->Start();
  3486. EXPECT_TRUE(r->is_pending());
  3487. d.RunUntilComplete();
  3488. ASSERT_EQ(1, d.response_started_count())
  3489. << "request failed. Error: " << d.request_status();
  3490. EXPECT_FALSE(d.received_data_before_response());
  3491. EXPECT_EQ(base::StringPiece(uploadBytes.get(), kMsgSize),
  3492. d.data_received());
  3493. }
  3494. }
  3495. HttpTestServer* http_test_server() { return &test_server_; }
  3496. private:
  3497. base::test::ScopedFeatureList feature_list_;
  3498. HttpTestServer test_server_;
  3499. };
  3500. namespace {
  3501. std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
  3502. const test_server::HttpRequest& request) {
  3503. if (request.headers.find("Host") == request.headers.end() ||
  3504. request.headers.at("Host") != "www.redirect.com" ||
  3505. request.method != test_server::METHOD_CONNECT) {
  3506. return nullptr;
  3507. }
  3508. auto http_response = std::make_unique<test_server::BasicHttpResponse>();
  3509. http_response->set_code(HTTP_FOUND);
  3510. http_response->AddCustomHeader("Location",
  3511. "http://www.destination.com/foo.js");
  3512. return std::move(http_response);
  3513. }
  3514. } // namespace
  3515. // In this unit test, we're using the HTTPTestServer as a proxy server and
  3516. // issuing a CONNECT request with the magic host name "www.redirect.com".
  3517. // The EmbeddedTestServer will return a 302 response, which we should not
  3518. // follow.
  3519. TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
  3520. http_test_server()->RegisterRequestHandler(
  3521. base::BindRepeating(&HandleRedirectConnect));
  3522. ASSERT_TRUE(http_test_server()->Start());
  3523. auto context_builder = CreateTestURLRequestContextBuilder();
  3524. context_builder->set_proxy_resolution_service(
  3525. CreateFixedProxyResolutionService(
  3526. http_test_server()->host_port_pair().ToString()));
  3527. auto context = context_builder->Build();
  3528. TestDelegate d;
  3529. {
  3530. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3531. GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
  3532. TRAFFIC_ANNOTATION_FOR_TESTS));
  3533. r->Start();
  3534. EXPECT_TRUE(r->is_pending());
  3535. d.RunUntilComplete();
  3536. // The proxy server should be set before failure.
  3537. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  3538. http_test_server()->host_port_pair()),
  3539. r->proxy_server());
  3540. EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
  3541. EXPECT_EQ(1, d.response_started_count());
  3542. // We should not have followed the redirect.
  3543. EXPECT_EQ(0, d.received_redirect_count());
  3544. }
  3545. }
  3546. // This is the same as the previous test, but checks that the network delegate
  3547. // registers the error.
  3548. TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
  3549. ASSERT_TRUE(http_test_server()->Start());
  3550. auto context_builder = CreateTestURLRequestContextBuilder();
  3551. context_builder->set_proxy_resolution_service(
  3552. CreateFixedProxyResolutionService(
  3553. http_test_server()->host_port_pair().ToString()));
  3554. auto& network_delegate = *context_builder->set_network_delegate(
  3555. std::make_unique<TestNetworkDelegate>());
  3556. auto context = context_builder->Build();
  3557. TestDelegate d;
  3558. {
  3559. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3560. GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
  3561. TRAFFIC_ANNOTATION_FOR_TESTS));
  3562. r->Start();
  3563. EXPECT_TRUE(r->is_pending());
  3564. d.RunUntilComplete();
  3565. // The proxy server should be set before failure.
  3566. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  3567. http_test_server()->host_port_pair()),
  3568. r->proxy_server());
  3569. EXPECT_EQ(1, d.response_started_count());
  3570. EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
  3571. // We should not have followed the redirect.
  3572. EXPECT_EQ(0, d.received_redirect_count());
  3573. EXPECT_EQ(1, network_delegate.error_count());
  3574. EXPECT_THAT(network_delegate.last_error(),
  3575. IsError(ERR_TUNNEL_CONNECTION_FAILED));
  3576. }
  3577. }
  3578. // Tests that we can block and asynchronously return OK in various stages.
  3579. TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
  3580. static const BlockingNetworkDelegate::Stage blocking_stages[] = {
  3581. BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
  3582. BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
  3583. BlockingNetworkDelegate::ON_HEADERS_RECEIVED};
  3584. ASSERT_TRUE(http_test_server()->Start());
  3585. TestDelegate d;
  3586. auto context_builder = CreateTestURLRequestContextBuilder();
  3587. auto& network_delegate = *context_builder->set_network_delegate(
  3588. std::make_unique<BlockingNetworkDelegate>(
  3589. BlockingNetworkDelegate::USER_CALLBACK));
  3590. network_delegate.set_block_on(
  3591. BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
  3592. BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
  3593. BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
  3594. auto context = context_builder->Build();
  3595. {
  3596. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3597. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  3598. TRAFFIC_ANNOTATION_FOR_TESTS));
  3599. r->Start();
  3600. for (auto stage : blocking_stages) {
  3601. network_delegate.RunUntilBlocked();
  3602. EXPECT_EQ(stage, network_delegate.stage_blocked_for_callback());
  3603. network_delegate.DoCallback(OK);
  3604. }
  3605. d.RunUntilComplete();
  3606. EXPECT_EQ(200, r->GetResponseCode());
  3607. EXPECT_EQ(OK, d.request_status());
  3608. EXPECT_EQ(1, network_delegate.created_requests());
  3609. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3610. }
  3611. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3612. }
  3613. // Tests that the network delegate can block and cancel a request.
  3614. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
  3615. ASSERT_TRUE(http_test_server()->Start());
  3616. TestDelegate d;
  3617. auto context_builder = CreateTestURLRequestContextBuilder();
  3618. context_builder->set_proxy_resolution_service(
  3619. CreateFixedProxyResolutionService(
  3620. http_test_server()->host_port_pair().ToString()));
  3621. auto& network_delegate = *context_builder->set_network_delegate(
  3622. std::make_unique<BlockingNetworkDelegate>(
  3623. BlockingNetworkDelegate::AUTO_CALLBACK));
  3624. auto context = context_builder->Build();
  3625. network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
  3626. network_delegate.set_retval(ERR_EMPTY_RESPONSE);
  3627. {
  3628. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3629. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  3630. TRAFFIC_ANNOTATION_FOR_TESTS));
  3631. r->Start();
  3632. d.RunUntilComplete();
  3633. // The proxy server is not set before cancellation.
  3634. EXPECT_FALSE(r->proxy_server().is_valid());
  3635. EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
  3636. EXPECT_EQ(1, network_delegate.created_requests());
  3637. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3638. }
  3639. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3640. }
  3641. // Helper function for NetworkDelegateCancelRequestAsynchronously and
  3642. // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
  3643. // delegate operating in |block_mode| and a request for |url|. It blocks the
  3644. // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
  3645. void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
  3646. BlockingNetworkDelegate::Stage stage,
  3647. const GURL& url) {
  3648. TestDelegate d;
  3649. auto context_builder = CreateTestURLRequestContextBuilder();
  3650. auto& network_delegate = *context_builder->set_network_delegate(
  3651. std::make_unique<BlockingNetworkDelegate>(block_mode));
  3652. network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
  3653. network_delegate.set_block_on(stage);
  3654. auto context = context_builder->Build();
  3655. {
  3656. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3657. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3658. r->Start();
  3659. d.RunUntilComplete();
  3660. // The proxy server is not set before cancellation.
  3661. if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
  3662. stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
  3663. EXPECT_FALSE(r->proxy_server().is_valid());
  3664. } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
  3665. EXPECT_TRUE(r->proxy_server().is_direct());
  3666. } else {
  3667. NOTREACHED();
  3668. }
  3669. EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
  3670. EXPECT_EQ(1, network_delegate.created_requests());
  3671. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3672. }
  3673. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3674. }
  3675. // The following 3 tests check that the network delegate can cancel a request
  3676. // synchronously in various stages of the request.
  3677. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
  3678. ASSERT_TRUE(http_test_server()->Start());
  3679. NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
  3680. BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
  3681. http_test_server()->GetURL("/"));
  3682. }
  3683. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
  3684. ASSERT_TRUE(http_test_server()->Start());
  3685. NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
  3686. BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
  3687. http_test_server()->GetURL("/"));
  3688. }
  3689. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
  3690. ASSERT_TRUE(http_test_server()->Start());
  3691. NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
  3692. BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
  3693. http_test_server()->GetURL("/"));
  3694. }
  3695. // The following 3 tests check that the network delegate can cancel a request
  3696. // asynchronously in various stages of the request.
  3697. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
  3698. ASSERT_TRUE(http_test_server()->Start());
  3699. NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
  3700. BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
  3701. http_test_server()->GetURL("/"));
  3702. }
  3703. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
  3704. ASSERT_TRUE(http_test_server()->Start());
  3705. NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
  3706. BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
  3707. http_test_server()->GetURL("/"));
  3708. }
  3709. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
  3710. ASSERT_TRUE(http_test_server()->Start());
  3711. NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
  3712. BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
  3713. http_test_server()->GetURL("/"));
  3714. }
  3715. // Tests that the network delegate can block and redirect a request to a new
  3716. // URL.
  3717. TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
  3718. ASSERT_TRUE(http_test_server()->Start());
  3719. TestDelegate d;
  3720. auto context_builder = CreateTestURLRequestContextBuilder();
  3721. context_builder->set_proxy_resolution_service(
  3722. CreateFixedProxyResolutionService(
  3723. http_test_server()->host_port_pair().ToString()));
  3724. auto& network_delegate = *context_builder->set_network_delegate(
  3725. std::make_unique<BlockingNetworkDelegate>(
  3726. BlockingNetworkDelegate::AUTO_CALLBACK));
  3727. auto context = context_builder->Build();
  3728. GURL redirect_url("http://does.not.resolve.test/simple.html");
  3729. network_delegate.set_redirect_url(redirect_url);
  3730. {
  3731. GURL original_url("http://does.not.resolve.test/defaultresponse");
  3732. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3733. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3734. // Quit after hitting the redirect, so can check the headers.
  3735. r->Start();
  3736. d.RunUntilRedirect();
  3737. // Check headers from URLRequestJob.
  3738. EXPECT_EQ(307, r->GetResponseCode());
  3739. EXPECT_EQ(307, r->response_headers()->response_code());
  3740. std::string location;
  3741. ASSERT_TRUE(
  3742. r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
  3743. EXPECT_EQ(redirect_url, GURL(location));
  3744. // Let the request finish.
  3745. r->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  3746. absl::nullopt /* modified_headers */);
  3747. d.RunUntilComplete();
  3748. EXPECT_EQ(OK, d.request_status());
  3749. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  3750. http_test_server()->host_port_pair()),
  3751. r->proxy_server());
  3752. EXPECT_EQ(OK, d.request_status());
  3753. EXPECT_EQ(redirect_url, r->url());
  3754. EXPECT_EQ(original_url, r->original_url());
  3755. EXPECT_EQ(2U, r->url_chain().size());
  3756. EXPECT_EQ(1, network_delegate.created_requests());
  3757. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3758. }
  3759. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3760. }
  3761. // Tests that the network delegate can block and redirect a request to a new
  3762. // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
  3763. TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
  3764. ASSERT_TRUE(http_test_server()->Start());
  3765. TestDelegate d;
  3766. auto context_builder = CreateTestURLRequestContextBuilder();
  3767. context_builder->set_proxy_resolution_service(
  3768. CreateFixedProxyResolutionService(
  3769. http_test_server()->host_port_pair().ToString()));
  3770. auto& network_delegate = *context_builder->set_network_delegate(
  3771. std::make_unique<BlockingNetworkDelegate>(
  3772. BlockingNetworkDelegate::SYNCHRONOUS));
  3773. auto context = context_builder->Build();
  3774. GURL redirect_url("http://does.not.resolve.test/simple.html");
  3775. network_delegate.set_redirect_url(redirect_url);
  3776. {
  3777. GURL original_url("http://does.not.resolve.test/defaultresponse");
  3778. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3779. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3780. // Quit after hitting the redirect, so can check the headers.
  3781. r->Start();
  3782. d.RunUntilRedirect();
  3783. // Check headers from URLRequestJob.
  3784. EXPECT_EQ(307, r->GetResponseCode());
  3785. EXPECT_EQ(307, r->response_headers()->response_code());
  3786. std::string location;
  3787. ASSERT_TRUE(
  3788. r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
  3789. EXPECT_EQ(redirect_url, GURL(location));
  3790. // Let the request finish.
  3791. r->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  3792. absl::nullopt /* modified_headers */);
  3793. d.RunUntilComplete();
  3794. EXPECT_EQ(OK, d.request_status());
  3795. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  3796. http_test_server()->host_port_pair()),
  3797. r->proxy_server());
  3798. EXPECT_EQ(OK, d.request_status());
  3799. EXPECT_EQ(redirect_url, r->url());
  3800. EXPECT_EQ(original_url, r->original_url());
  3801. EXPECT_EQ(2U, r->url_chain().size());
  3802. EXPECT_EQ(1, network_delegate.created_requests());
  3803. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3804. }
  3805. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3806. }
  3807. // Tests that redirects caused by the network delegate preserve POST data.
  3808. TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
  3809. ASSERT_TRUE(http_test_server()->Start());
  3810. const char kData[] = "hello world";
  3811. TestDelegate d;
  3812. auto context_builder = CreateTestURLRequestContextBuilder();
  3813. auto& network_delegate = *context_builder->set_network_delegate(
  3814. std::make_unique<BlockingNetworkDelegate>(
  3815. BlockingNetworkDelegate::AUTO_CALLBACK));
  3816. network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
  3817. GURL redirect_url(http_test_server()->GetURL("/echo"));
  3818. network_delegate.set_redirect_url(redirect_url);
  3819. auto context = context_builder->Build();
  3820. {
  3821. GURL original_url(http_test_server()->GetURL("/defaultresponse"));
  3822. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3823. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3824. r->set_method("POST");
  3825. r->set_upload(CreateSimpleUploadData(kData));
  3826. HttpRequestHeaders headers;
  3827. headers.SetHeader(HttpRequestHeaders::kContentLength,
  3828. base::NumberToString(std::size(kData) - 1));
  3829. r->SetExtraRequestHeaders(headers);
  3830. // Quit after hitting the redirect, so can check the headers.
  3831. r->Start();
  3832. d.RunUntilRedirect();
  3833. // Check headers from URLRequestJob.
  3834. EXPECT_EQ(307, r->GetResponseCode());
  3835. EXPECT_EQ(307, r->response_headers()->response_code());
  3836. std::string location;
  3837. ASSERT_TRUE(
  3838. r->response_headers()->EnumerateHeader(nullptr, "Location", &location));
  3839. EXPECT_EQ(redirect_url, GURL(location));
  3840. // Let the request finish.
  3841. r->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  3842. absl::nullopt /* modified_headers */);
  3843. d.RunUntilComplete();
  3844. EXPECT_EQ(OK, d.request_status());
  3845. EXPECT_EQ(redirect_url, r->url());
  3846. EXPECT_EQ(original_url, r->original_url());
  3847. EXPECT_EQ(2U, r->url_chain().size());
  3848. EXPECT_EQ(1, network_delegate.created_requests());
  3849. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3850. EXPECT_EQ("POST", r->method());
  3851. EXPECT_EQ(kData, d.data_received());
  3852. }
  3853. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3854. }
  3855. // Tests that the network delegate can block and redirect a request to a new
  3856. // URL during OnHeadersReceived.
  3857. TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
  3858. ASSERT_TRUE(http_test_server()->Start());
  3859. TestDelegate d;
  3860. auto context_builder = CreateTestURLRequestContextBuilder();
  3861. context_builder->set_proxy_resolution_service(
  3862. CreateFixedProxyResolutionService(
  3863. http_test_server()->host_port_pair().ToString()));
  3864. auto& network_delegate = *context_builder->set_network_delegate(
  3865. std::make_unique<BlockingNetworkDelegate>(
  3866. BlockingNetworkDelegate::AUTO_CALLBACK));
  3867. auto context = context_builder->Build();
  3868. network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
  3869. GURL redirect_url("http://does.not.resolve.test/simple.html");
  3870. network_delegate.set_redirect_on_headers_received_url(redirect_url);
  3871. {
  3872. GURL original_url("http://does.not.resolve.test/defaultresponse");
  3873. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3874. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3875. r->Start();
  3876. d.RunUntilComplete();
  3877. EXPECT_EQ(OK, d.request_status());
  3878. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  3879. http_test_server()->host_port_pair()),
  3880. r->proxy_server());
  3881. EXPECT_EQ(OK, d.request_status());
  3882. EXPECT_EQ(redirect_url, r->url());
  3883. EXPECT_EQ(original_url, r->original_url());
  3884. EXPECT_EQ(2U, r->url_chain().size());
  3885. EXPECT_EQ(2, network_delegate.created_requests());
  3886. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3887. }
  3888. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3889. }
  3890. // Tests that the network delegate can synchronously complete OnAuthRequired
  3891. // by taking no action. This indicates that the NetworkDelegate does not want to
  3892. // handle the challenge, and is passing the buck along to the
  3893. // URLRequest::Delegate.
  3894. TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
  3895. ASSERT_TRUE(http_test_server()->Start());
  3896. TestDelegate d;
  3897. auto context_builder = CreateTestURLRequestContextBuilder();
  3898. auto& network_delegate = *context_builder->set_network_delegate(
  3899. std::make_unique<BlockingNetworkDelegate>(
  3900. BlockingNetworkDelegate::SYNCHRONOUS));
  3901. auto context = context_builder->Build();
  3902. d.set_credentials(AuthCredentials(kUser, kSecret));
  3903. {
  3904. GURL url(http_test_server()->GetURL("/auth-basic"));
  3905. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3906. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3907. r->Start();
  3908. d.RunUntilComplete();
  3909. EXPECT_EQ(OK, d.request_status());
  3910. EXPECT_EQ(200, r->GetResponseCode());
  3911. EXPECT_TRUE(d.auth_required_called());
  3912. EXPECT_EQ(1, network_delegate.created_requests());
  3913. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3914. }
  3915. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3916. }
  3917. // Tests that NetworkDelegate header overrides from the 401 response do not
  3918. // affect the 200 response. This is a regression test for
  3919. // https://crbug.com/801237.
  3920. TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
  3921. ASSERT_TRUE(http_test_server()->Start());
  3922. TestDelegate d;
  3923. d.set_credentials(AuthCredentials(kUser, kSecret));
  3924. default_network_delegate().set_add_header_to_first_response(true);
  3925. {
  3926. GURL url(http_test_server()->GetURL("/auth-basic"));
  3927. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  3928. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3929. r->Start();
  3930. d.RunUntilComplete();
  3931. EXPECT_EQ(OK, d.request_status());
  3932. EXPECT_EQ(200, r->GetResponseCode());
  3933. EXPECT_TRUE(d.auth_required_called());
  3934. EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
  3935. }
  3936. {
  3937. GURL url(http_test_server()->GetURL("/defaultresponse"));
  3938. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  3939. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  3940. r->Start();
  3941. d.RunUntilComplete();
  3942. // Check that set_add_header_to_first_response normally adds a header.
  3943. EXPECT_EQ(OK, d.request_status());
  3944. EXPECT_EQ(200, r->GetResponseCode());
  3945. EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
  3946. }
  3947. }
  3948. // Tests that we can handle when a network request was canceled while we were
  3949. // waiting for the network delegate.
  3950. // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
  3951. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
  3952. ASSERT_TRUE(http_test_server()->Start());
  3953. TestDelegate d;
  3954. auto context_builder = CreateTestURLRequestContextBuilder();
  3955. auto& network_delegate = *context_builder->set_network_delegate(
  3956. std::make_unique<BlockingNetworkDelegate>(
  3957. BlockingNetworkDelegate::USER_CALLBACK));
  3958. network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
  3959. auto context = context_builder->Build();
  3960. {
  3961. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3962. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  3963. TRAFFIC_ANNOTATION_FOR_TESTS));
  3964. r->Start();
  3965. network_delegate.RunUntilBlocked();
  3966. EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
  3967. network_delegate.stage_blocked_for_callback());
  3968. EXPECT_EQ(0, network_delegate.completed_requests());
  3969. // Cancel before callback.
  3970. r->Cancel();
  3971. // Ensure that network delegate is notified.
  3972. EXPECT_EQ(1, network_delegate.completed_requests());
  3973. EXPECT_EQ(1, network_delegate.canceled_requests());
  3974. EXPECT_EQ(1, network_delegate.created_requests());
  3975. EXPECT_EQ(0, network_delegate.destroyed_requests());
  3976. }
  3977. EXPECT_EQ(1, network_delegate.destroyed_requests());
  3978. }
  3979. // Tests that we can handle when a network request was canceled while we were
  3980. // waiting for the network delegate.
  3981. // Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
  3982. // callback.
  3983. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
  3984. ASSERT_TRUE(http_test_server()->Start());
  3985. TestDelegate d;
  3986. auto context_builder = CreateTestURLRequestContextBuilder();
  3987. auto& network_delegate = *context_builder->set_network_delegate(
  3988. std::make_unique<BlockingNetworkDelegate>(
  3989. BlockingNetworkDelegate::USER_CALLBACK));
  3990. network_delegate.set_block_on(
  3991. BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
  3992. auto context = context_builder->Build();
  3993. {
  3994. std::unique_ptr<URLRequest> r(context->CreateRequest(
  3995. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  3996. TRAFFIC_ANNOTATION_FOR_TESTS));
  3997. r->Start();
  3998. network_delegate.RunUntilBlocked();
  3999. EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
  4000. network_delegate.stage_blocked_for_callback());
  4001. EXPECT_EQ(0, network_delegate.completed_requests());
  4002. // Cancel before callback.
  4003. r->Cancel();
  4004. // Ensure that network delegate is notified.
  4005. EXPECT_EQ(1, network_delegate.completed_requests());
  4006. EXPECT_EQ(1, network_delegate.canceled_requests());
  4007. EXPECT_EQ(1, network_delegate.created_requests());
  4008. EXPECT_EQ(0, network_delegate.destroyed_requests());
  4009. }
  4010. EXPECT_EQ(1, network_delegate.destroyed_requests());
  4011. }
  4012. // Tests that we can handle when a network request was canceled while we were
  4013. // waiting for the network delegate.
  4014. // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
  4015. TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
  4016. ASSERT_TRUE(http_test_server()->Start());
  4017. TestDelegate d;
  4018. auto context_builder = CreateTestURLRequestContextBuilder();
  4019. auto& network_delegate = *context_builder->set_network_delegate(
  4020. std::make_unique<BlockingNetworkDelegate>(
  4021. BlockingNetworkDelegate::USER_CALLBACK));
  4022. network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
  4023. auto context = context_builder->Build();
  4024. {
  4025. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4026. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  4027. TRAFFIC_ANNOTATION_FOR_TESTS));
  4028. r->Start();
  4029. network_delegate.RunUntilBlocked();
  4030. EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
  4031. network_delegate.stage_blocked_for_callback());
  4032. EXPECT_EQ(0, network_delegate.completed_requests());
  4033. // Cancel before callback.
  4034. r->Cancel();
  4035. // Ensure that network delegate is notified.
  4036. EXPECT_EQ(1, network_delegate.completed_requests());
  4037. EXPECT_EQ(1, network_delegate.canceled_requests());
  4038. EXPECT_EQ(1, network_delegate.created_requests());
  4039. EXPECT_EQ(0, network_delegate.destroyed_requests());
  4040. }
  4041. EXPECT_EQ(1, network_delegate.destroyed_requests());
  4042. }
  4043. namespace {
  4044. std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
  4045. const test_server::HttpRequest& request) {
  4046. if (request.headers.find("Host") == request.headers.end() ||
  4047. request.headers.at("Host") != "www.server-auth.com" ||
  4048. request.method != test_server::METHOD_CONNECT) {
  4049. return nullptr;
  4050. }
  4051. auto http_response = std::make_unique<test_server::BasicHttpResponse>();
  4052. http_response->set_code(HTTP_UNAUTHORIZED);
  4053. http_response->AddCustomHeader("WWW-Authenticate",
  4054. "Basic realm=\"WallyWorld\"");
  4055. return http_response;
  4056. }
  4057. } // namespace
  4058. // In this unit test, we're using the EmbeddedTestServer as a proxy server and
  4059. // issuing a CONNECT request with the magic host name "www.server-auth.com".
  4060. // The EmbeddedTestServer will return a 401 response, which we should balk at.
  4061. TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
  4062. http_test_server()->RegisterRequestHandler(
  4063. base::BindRepeating(&HandleServerAuthConnect));
  4064. ASSERT_TRUE(http_test_server()->Start());
  4065. auto context_builder = CreateTestURLRequestContextBuilder();
  4066. context_builder->set_proxy_resolution_service(
  4067. CreateFixedProxyResolutionService(
  4068. http_test_server()->host_port_pair().ToString()));
  4069. auto context = context_builder->Build();
  4070. TestDelegate d;
  4071. {
  4072. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4073. GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
  4074. TRAFFIC_ANNOTATION_FOR_TESTS));
  4075. r->Start();
  4076. EXPECT_TRUE(r->is_pending());
  4077. d.RunUntilComplete();
  4078. // The proxy server should be set before failure.
  4079. EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
  4080. http_test_server()->host_port_pair()),
  4081. r->proxy_server());
  4082. EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
  4083. }
  4084. }
  4085. TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
  4086. ASSERT_TRUE(http_test_server()->Start());
  4087. TestDelegate d;
  4088. {
  4089. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4090. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  4091. TRAFFIC_ANNOTATION_FOR_TESTS));
  4092. r->Start();
  4093. EXPECT_TRUE(r->is_pending());
  4094. d.RunUntilComplete();
  4095. EXPECT_EQ(1, d.response_started_count());
  4096. EXPECT_FALSE(d.received_data_before_response());
  4097. EXPECT_NE(0, d.bytes_received());
  4098. EXPECT_EQ(http_test_server()->host_port_pair().host(),
  4099. r->GetResponseRemoteEndpoint().ToStringWithoutPort());
  4100. EXPECT_EQ(http_test_server()->host_port_pair().port(),
  4101. r->GetResponseRemoteEndpoint().port());
  4102. // TODO(eroman): Add back the NetLog tests...
  4103. }
  4104. }
  4105. TEST_F(URLRequestTestHTTP, GetTest) {
  4106. ASSERT_TRUE(http_test_server()->Start());
  4107. TestDelegate d;
  4108. {
  4109. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4110. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  4111. TRAFFIC_ANNOTATION_FOR_TESTS));
  4112. r->Start();
  4113. EXPECT_TRUE(r->is_pending());
  4114. d.RunUntilComplete();
  4115. EXPECT_EQ(1, d.response_started_count());
  4116. EXPECT_FALSE(d.received_data_before_response());
  4117. EXPECT_NE(0, d.bytes_received());
  4118. EXPECT_EQ(http_test_server()->host_port_pair().host(),
  4119. r->GetResponseRemoteEndpoint().ToStringWithoutPort());
  4120. EXPECT_EQ(http_test_server()->host_port_pair().port(),
  4121. r->GetResponseRemoteEndpoint().port());
  4122. }
  4123. }
  4124. TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
  4125. ASSERT_TRUE(http_test_server()->Start());
  4126. TestDelegate d;
  4127. {
  4128. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4129. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  4130. TRAFFIC_ANNOTATION_FOR_TESTS));
  4131. r->Start();
  4132. EXPECT_TRUE(r->is_pending());
  4133. d.RunUntilComplete();
  4134. LoadTimingInfo load_timing_info;
  4135. r->GetLoadTimingInfo(&load_timing_info);
  4136. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  4137. EXPECT_EQ(1, d.response_started_count());
  4138. EXPECT_FALSE(d.received_data_before_response());
  4139. EXPECT_NE(0, d.bytes_received());
  4140. EXPECT_EQ(http_test_server()->host_port_pair().host(),
  4141. r->GetResponseRemoteEndpoint().ToStringWithoutPort());
  4142. EXPECT_EQ(http_test_server()->host_port_pair().port(),
  4143. r->GetResponseRemoteEndpoint().port());
  4144. }
  4145. }
  4146. namespace {
  4147. // Sends the correct Content-Length matching the compressed length.
  4148. const char kZippedContentLengthCompressed[] = "C";
  4149. // Sends an incorrect Content-Length matching the uncompressed length.
  4150. const char kZippedContentLengthUncompressed[] = "U";
  4151. // Sends an incorrect Content-Length shorter than the compressed length.
  4152. const char kZippedContentLengthShort[] = "S";
  4153. // Sends an incorrect Content-Length between the compressed and uncompressed
  4154. // lengths.
  4155. const char kZippedContentLengthMedium[] = "M";
  4156. // Sends an incorrect Content-Length larger than both compressed and
  4157. // uncompressed lengths.
  4158. const char kZippedContentLengthLong[] = "L";
  4159. // Sends |compressed_content| which, when decoded with deflate, should have
  4160. // length |uncompressed_length|. The Content-Length header will be sent based on
  4161. // which of the constants above is sent in the query string.
  4162. std::unique_ptr<test_server::HttpResponse> HandleZippedRequest(
  4163. const std::string& compressed_content,
  4164. size_t uncompressed_length,
  4165. const test_server::HttpRequest& request) {
  4166. GURL url = request.GetURL();
  4167. if (url.path_piece() != "/compressedfiles/BullRunSpeech.txt")
  4168. return nullptr;
  4169. size_t length;
  4170. if (url.query_piece() == kZippedContentLengthCompressed) {
  4171. length = compressed_content.size();
  4172. } else if (url.query_piece() == kZippedContentLengthUncompressed) {
  4173. length = uncompressed_length;
  4174. } else if (url.query_piece() == kZippedContentLengthShort) {
  4175. length = compressed_content.size() / 2;
  4176. } else if (url.query_piece() == kZippedContentLengthMedium) {
  4177. length = (compressed_content.size() + uncompressed_length) / 2;
  4178. } else if (url.query_piece() == kZippedContentLengthLong) {
  4179. length = compressed_content.size() + uncompressed_length;
  4180. } else {
  4181. return nullptr;
  4182. }
  4183. std::string headers = "HTTP/1.1 200 OK\r\n";
  4184. headers += "Content-Encoding: deflate\r\n";
  4185. base::StringAppendF(&headers, "Content-Length: %zu\r\n", length);
  4186. return std::make_unique<test_server::RawHttpResponse>(headers,
  4187. compressed_content);
  4188. }
  4189. } // namespace
  4190. TEST_F(URLRequestTestHTTP, GetZippedTest) {
  4191. base::FilePath file_path;
  4192. base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
  4193. file_path = file_path.Append(kTestFilePath);
  4194. std::string expected_content, compressed_content;
  4195. ASSERT_TRUE(base::ReadFileToString(
  4196. file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt")),
  4197. &expected_content));
  4198. // This file is the output of the Python zlib.compress function on
  4199. // |expected_content|.
  4200. ASSERT_TRUE(base::ReadFileToString(
  4201. file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt.deflate")),
  4202. &compressed_content));
  4203. http_test_server()->RegisterRequestHandler(base::BindRepeating(
  4204. &HandleZippedRequest, compressed_content, expected_content.size()));
  4205. ASSERT_TRUE(http_test_server()->Start());
  4206. static const struct {
  4207. const char* parameter;
  4208. bool expect_success;
  4209. } kTests[] = {
  4210. // Sending the compressed Content-Length is correct.
  4211. {kZippedContentLengthCompressed, true},
  4212. // Sending the uncompressed Content-Length is incorrect, but we accept it
  4213. // to workaround some broken servers.
  4214. {kZippedContentLengthUncompressed, true},
  4215. // Sending too long of Content-Length is rejected.
  4216. {kZippedContentLengthLong, false},
  4217. {kZippedContentLengthMedium, false},
  4218. // Sending too short of Content-Length successfully fetches a response
  4219. // body, but it will be truncated.
  4220. {kZippedContentLengthShort, true},
  4221. };
  4222. for (const auto& test : kTests) {
  4223. SCOPED_TRACE(test.parameter);
  4224. TestDelegate d;
  4225. std::string test_file = base::StringPrintf(
  4226. "/compressedfiles/BullRunSpeech.txt?%s", test.parameter);
  4227. auto context_builder = CreateTestURLRequestContextBuilder();
  4228. context_builder->set_network_delegate(
  4229. std::make_unique<TestNetworkDelegate>());
  4230. auto context = context_builder->Build();
  4231. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4232. http_test_server()->GetURL(test_file), DEFAULT_PRIORITY, &d,
  4233. TRAFFIC_ANNOTATION_FOR_TESTS));
  4234. r->Start();
  4235. EXPECT_TRUE(r->is_pending());
  4236. d.RunUntilComplete();
  4237. EXPECT_EQ(1, d.response_started_count());
  4238. EXPECT_FALSE(d.received_data_before_response());
  4239. VLOG(1) << " Received " << d.bytes_received() << " bytes"
  4240. << " error = " << d.request_status();
  4241. if (test.expect_success) {
  4242. EXPECT_EQ(OK, d.request_status())
  4243. << " Parameter = \"" << test_file << "\"";
  4244. if (strcmp(test.parameter, kZippedContentLengthShort) == 0) {
  4245. // When content length is smaller than both compressed length and
  4246. // uncompressed length, HttpStreamParser might not read the full
  4247. // response body.
  4248. EXPECT_EQ(expected_content.substr(0, d.data_received().size()),
  4249. d.data_received());
  4250. } else {
  4251. EXPECT_EQ(expected_content, d.data_received());
  4252. }
  4253. } else {
  4254. EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
  4255. << " Parameter = \"" << test_file << "\"";
  4256. }
  4257. }
  4258. }
  4259. TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
  4260. ASSERT_TRUE(http_test_server()->Start());
  4261. GURL destination_url = http_test_server()->GetURL("/");
  4262. GURL original_url =
  4263. http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
  4264. TestDelegate d;
  4265. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  4266. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  4267. req->Start();
  4268. d.RunUntilComplete();
  4269. EXPECT_EQ(1, d.response_started_count());
  4270. EXPECT_EQ(1, d.received_redirect_count());
  4271. EXPECT_EQ(destination_url, req->url());
  4272. EXPECT_EQ(original_url, req->original_url());
  4273. ASSERT_EQ(2U, req->url_chain().size());
  4274. EXPECT_EQ(original_url, req->url_chain()[0]);
  4275. EXPECT_EQ(destination_url, req->url_chain()[1]);
  4276. LoadTimingInfo load_timing_info_before_redirect;
  4277. EXPECT_TRUE(default_network_delegate().GetLoadTimingInfoBeforeRedirect(
  4278. &load_timing_info_before_redirect));
  4279. TestLoadTimingNotReused(load_timing_info_before_redirect,
  4280. CONNECT_TIMING_HAS_DNS_TIMES);
  4281. LoadTimingInfo load_timing_info;
  4282. req->GetLoadTimingInfo(&load_timing_info);
  4283. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  4284. // Check that a new socket was used on redirect, since the server does not
  4285. // supposed keep-alive sockets, and that the times before the redirect are
  4286. // before the ones recorded for the second request.
  4287. EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
  4288. load_timing_info.socket_log_id);
  4289. EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
  4290. load_timing_info.connect_timing.connect_start);
  4291. }
  4292. TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
  4293. ASSERT_TRUE(http_test_server()->Start());
  4294. GURL destination_url = http_test_server()->GetURL("/");
  4295. GURL middle_redirect_url =
  4296. http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
  4297. GURL original_url = http_test_server()->GetURL("/server-redirect?" +
  4298. middle_redirect_url.spec());
  4299. TestDelegate d;
  4300. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  4301. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  4302. req->Start();
  4303. d.RunUntilComplete();
  4304. EXPECT_EQ(1, d.response_started_count());
  4305. EXPECT_EQ(2, d.received_redirect_count());
  4306. EXPECT_EQ(destination_url, req->url());
  4307. EXPECT_EQ(original_url, req->original_url());
  4308. ASSERT_EQ(3U, req->url_chain().size());
  4309. EXPECT_EQ(original_url, req->url_chain()[0]);
  4310. EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
  4311. EXPECT_EQ(destination_url, req->url_chain()[2]);
  4312. }
  4313. // This is a regression test for https://crbug.com/942073.
  4314. TEST_F(URLRequestTestHTTP, RedirectEscaping) {
  4315. ASSERT_TRUE(http_test_server()->Start());
  4316. // Assemble the destination URL as a string so it is not escaped by GURL.
  4317. GURL destination_base = http_test_server()->GetURL("/defaultresponse");
  4318. // Add a URL fragment of U+2603 unescaped, U+2603 escaped, and then a UTF-8
  4319. // encoding error.
  4320. std::string destination_url =
  4321. destination_base.spec() + "#\xE2\x98\x83_%E2%98%83_\xE0\xE0";
  4322. // Redirect resolution should percent-escape bytes and preserve the UTF-8
  4323. // error at the end.
  4324. std::string destination_escaped =
  4325. destination_base.spec() + "#%E2%98%83_%E2%98%83_%E0%E0";
  4326. GURL original_url = http_test_server()->GetURL(
  4327. "/server-redirect?" +
  4328. base::EscapeQueryParamValue(destination_url, false));
  4329. TestDelegate d;
  4330. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  4331. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  4332. req->Start();
  4333. d.RunUntilComplete();
  4334. EXPECT_EQ(1, d.response_started_count());
  4335. EXPECT_EQ(1, d.received_redirect_count());
  4336. EXPECT_EQ(destination_escaped, req->url().spec());
  4337. EXPECT_EQ(original_url, req->original_url());
  4338. ASSERT_EQ(2U, req->url_chain().size());
  4339. EXPECT_EQ(original_url, req->url_chain()[0]);
  4340. EXPECT_EQ(destination_escaped, req->url_chain()[1].spec());
  4341. }
  4342. // First and second pieces of information logged by delegates to URLRequests.
  4343. const char kFirstDelegateInfo[] = "Wonderful delegate";
  4344. const char16_t kFirstDelegateInfo16[] = u"Wonderful delegate";
  4345. const char kSecondDelegateInfo[] = "Exciting delegate";
  4346. const char16_t kSecondDelegateInfo16[] = u"Exciting delegate";
  4347. // Logs delegate information to a URLRequest. The first string is logged
  4348. // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
  4349. // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
  4350. // another asynchronous call is used to clear the delegate information
  4351. // before calling a callback. The object then deletes itself.
  4352. class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
  4353. public:
  4354. using Callback = base::OnceCallback<void()>;
  4355. AsyncDelegateLogger(const AsyncDelegateLogger&) = delete;
  4356. AsyncDelegateLogger& operator=(const AsyncDelegateLogger&) = delete;
  4357. // Each time delegate information is added to the URLRequest, the resulting
  4358. // load state is checked. The expected load state after each request is
  4359. // passed in as an argument.
  4360. static void Run(URLRequest* url_request,
  4361. LoadState expected_first_load_state,
  4362. LoadState expected_second_load_state,
  4363. LoadState expected_third_load_state,
  4364. Callback callback) {
  4365. // base::MakeRefCounted<AsyncDelegateLogger> is unavailable here, since the
  4366. // constructor of AsyncDelegateLogger is private.
  4367. auto logger = base::WrapRefCounted(new AsyncDelegateLogger(
  4368. url_request, expected_first_load_state, expected_second_load_state,
  4369. expected_third_load_state, std::move(callback)));
  4370. logger->Start();
  4371. }
  4372. // Checks that the log entries, starting with log_position, contain the
  4373. // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
  4374. // recorded. Returns the index of entry after the expected number of
  4375. // events this logged, or entries.size() if there aren't enough entries.
  4376. static size_t CheckDelegateInfo(const std::vector<NetLogEntry>& entries,
  4377. size_t log_position) {
  4378. // There should be 4 DELEGATE_INFO events: Two begins and two ends.
  4379. if (log_position + 3 >= entries.size()) {
  4380. ADD_FAILURE() << "Not enough log entries";
  4381. return entries.size();
  4382. }
  4383. std::string delegate_info;
  4384. EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
  4385. EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
  4386. EXPECT_EQ(
  4387. kFirstDelegateInfo,
  4388. GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
  4389. ++log_position;
  4390. EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
  4391. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4392. ++log_position;
  4393. EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
  4394. EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
  4395. EXPECT_EQ(
  4396. kSecondDelegateInfo,
  4397. GetStringValueFromParams(entries[log_position], "delegate_blocked_by"));
  4398. ++log_position;
  4399. EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
  4400. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4401. return log_position + 1;
  4402. }
  4403. private:
  4404. friend class base::RefCounted<AsyncDelegateLogger>;
  4405. AsyncDelegateLogger(URLRequest* url_request,
  4406. LoadState expected_first_load_state,
  4407. LoadState expected_second_load_state,
  4408. LoadState expected_third_load_state,
  4409. Callback callback)
  4410. : url_request_(url_request),
  4411. expected_first_load_state_(expected_first_load_state),
  4412. expected_second_load_state_(expected_second_load_state),
  4413. expected_third_load_state_(expected_third_load_state),
  4414. callback_(std::move(callback)) {}
  4415. ~AsyncDelegateLogger() = default;
  4416. void Start() {
  4417. url_request_->LogBlockedBy(kFirstDelegateInfo);
  4418. LoadStateWithParam load_state = url_request_->GetLoadState();
  4419. EXPECT_EQ(expected_first_load_state_, load_state.state);
  4420. EXPECT_NE(kFirstDelegateInfo16, load_state.param);
  4421. base::ThreadTaskRunnerHandle::Get()->PostTask(
  4422. FROM_HERE,
  4423. base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
  4424. }
  4425. void LogSecondDelegate() {
  4426. url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
  4427. LoadStateWithParam load_state = url_request_->GetLoadState();
  4428. EXPECT_EQ(expected_second_load_state_, load_state.state);
  4429. if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
  4430. EXPECT_EQ(kSecondDelegateInfo16, load_state.param);
  4431. } else {
  4432. EXPECT_NE(kSecondDelegateInfo16, load_state.param);
  4433. }
  4434. base::ThreadTaskRunnerHandle::Get()->PostTask(
  4435. FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
  4436. }
  4437. void LogComplete() {
  4438. url_request_->LogUnblocked();
  4439. LoadStateWithParam load_state = url_request_->GetLoadState();
  4440. EXPECT_EQ(expected_third_load_state_, load_state.state);
  4441. if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
  4442. EXPECT_EQ(std::u16string(), load_state.param);
  4443. std::move(callback_).Run();
  4444. }
  4445. raw_ptr<URLRequest> url_request_;
  4446. const int expected_first_load_state_;
  4447. const int expected_second_load_state_;
  4448. const int expected_third_load_state_;
  4449. Callback callback_;
  4450. };
  4451. // NetworkDelegate that logs delegate information before a request is started,
  4452. // before headers are sent, when headers are read, and when auth information
  4453. // is requested. Uses AsyncDelegateLogger.
  4454. class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
  4455. public:
  4456. AsyncLoggingNetworkDelegate() = default;
  4457. AsyncLoggingNetworkDelegate(const AsyncLoggingNetworkDelegate&) = delete;
  4458. AsyncLoggingNetworkDelegate& operator=(const AsyncLoggingNetworkDelegate&) =
  4459. delete;
  4460. ~AsyncLoggingNetworkDelegate() override = default;
  4461. // NetworkDelegate implementation.
  4462. int OnBeforeURLRequest(URLRequest* request,
  4463. CompletionOnceCallback callback,
  4464. GURL* new_url) override {
  4465. // TestNetworkDelegate always completes synchronously.
  4466. CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
  4467. request, base::NullCallback(), new_url));
  4468. return RunCallbackAsynchronously(request, std::move(callback));
  4469. }
  4470. int OnBeforeStartTransaction(
  4471. URLRequest* request,
  4472. const HttpRequestHeaders& headers,
  4473. OnBeforeStartTransactionCallback callback) override {
  4474. // TestNetworkDelegate always completes synchronously.
  4475. CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
  4476. request, headers, base::NullCallback()));
  4477. return RunCallbackAsynchronously(
  4478. request, base::BindOnce(
  4479. [](OnBeforeStartTransactionCallback callback, int result) {
  4480. std::move(callback).Run(result, absl::nullopt);
  4481. },
  4482. std::move(callback)));
  4483. }
  4484. int OnHeadersReceived(
  4485. URLRequest* request,
  4486. CompletionOnceCallback callback,
  4487. const HttpResponseHeaders* original_response_headers,
  4488. scoped_refptr<HttpResponseHeaders>* override_response_headers,
  4489. const IPEndPoint& endpoint,
  4490. absl::optional<GURL>* preserve_fragment_on_redirect_url) override {
  4491. // TestNetworkDelegate always completes synchronously.
  4492. CHECK_NE(ERR_IO_PENDING,
  4493. TestNetworkDelegate::OnHeadersReceived(
  4494. request, base::NullCallback(), original_response_headers,
  4495. override_response_headers, endpoint,
  4496. preserve_fragment_on_redirect_url));
  4497. return RunCallbackAsynchronously(request, std::move(callback));
  4498. }
  4499. private:
  4500. static int RunCallbackAsynchronously(URLRequest* request,
  4501. CompletionOnceCallback callback) {
  4502. AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
  4503. LOAD_STATE_WAITING_FOR_DELEGATE,
  4504. LOAD_STATE_WAITING_FOR_DELEGATE,
  4505. base::BindOnce(std::move(callback), OK));
  4506. return ERR_IO_PENDING;
  4507. }
  4508. };
  4509. // URLRequest::Delegate that logs delegate information when the headers
  4510. // are received, when each read completes, and during redirects. Uses
  4511. // AsyncDelegateLogger. Can optionally cancel a request in any phase.
  4512. //
  4513. // Inherits from TestDelegate to reuse the TestDelegate code to handle
  4514. // advancing to the next step in most cases, as well as cancellation.
  4515. class AsyncLoggingUrlRequestDelegate : public TestDelegate {
  4516. public:
  4517. enum CancelStage {
  4518. NO_CANCEL = 0,
  4519. CANCEL_ON_RECEIVED_REDIRECT,
  4520. CANCEL_ON_RESPONSE_STARTED,
  4521. CANCEL_ON_READ_COMPLETED
  4522. };
  4523. explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
  4524. : cancel_stage_(cancel_stage) {
  4525. if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
  4526. set_cancel_in_received_redirect(true);
  4527. else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
  4528. set_cancel_in_response_started(true);
  4529. else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
  4530. set_cancel_in_received_data(true);
  4531. }
  4532. AsyncLoggingUrlRequestDelegate(const AsyncLoggingUrlRequestDelegate&) =
  4533. delete;
  4534. AsyncLoggingUrlRequestDelegate& operator=(
  4535. const AsyncLoggingUrlRequestDelegate&) = delete;
  4536. ~AsyncLoggingUrlRequestDelegate() override = default;
  4537. // URLRequest::Delegate implementation:
  4538. void OnReceivedRedirect(URLRequest* request,
  4539. const RedirectInfo& redirect_info,
  4540. bool* defer_redirect) override {
  4541. *defer_redirect = true;
  4542. AsyncDelegateLogger::Run(
  4543. request, LOAD_STATE_WAITING_FOR_DELEGATE,
  4544. LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
  4545. base::BindOnce(
  4546. &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
  4547. base::Unretained(this), request, redirect_info));
  4548. }
  4549. void OnResponseStarted(URLRequest* request, int net_error) override {
  4550. AsyncDelegateLogger::Run(
  4551. request, LOAD_STATE_WAITING_FOR_DELEGATE,
  4552. LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
  4553. base::BindOnce(
  4554. &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
  4555. base::Unretained(this), request, net_error));
  4556. }
  4557. void OnReadCompleted(URLRequest* request, int bytes_read) override {
  4558. AsyncDelegateLogger::Run(
  4559. request, LOAD_STATE_IDLE, LOAD_STATE_IDLE, LOAD_STATE_IDLE,
  4560. base::BindOnce(
  4561. &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
  4562. base::Unretained(this), request, bytes_read));
  4563. }
  4564. private:
  4565. void OnReceivedRedirectLoggingComplete(URLRequest* request,
  4566. const RedirectInfo& redirect_info) {
  4567. bool defer_redirect = false;
  4568. TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
  4569. // FollowDeferredRedirect should not be called after cancellation.
  4570. if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
  4571. return;
  4572. if (!defer_redirect) {
  4573. request->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  4574. absl::nullopt /* modified_headers */);
  4575. }
  4576. }
  4577. void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
  4578. // The parent class continues the request.
  4579. TestDelegate::OnResponseStarted(request, net_error);
  4580. }
  4581. void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
  4582. // The parent class continues the request.
  4583. TestDelegate::OnReadCompleted(request, bytes_read);
  4584. }
  4585. const CancelStage cancel_stage_;
  4586. };
  4587. // Tests handling of delegate info before a request starts.
  4588. TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
  4589. ASSERT_TRUE(http_test_server()->Start());
  4590. TestDelegate request_delegate;
  4591. auto context_builder = CreateTestURLRequestContextBuilder();
  4592. context_builder->set_net_log(NetLog::Get());
  4593. auto context = context_builder->Build();
  4594. {
  4595. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4596. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
  4597. &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4598. LoadStateWithParam load_state = r->GetLoadState();
  4599. EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
  4600. EXPECT_EQ(std::u16string(), load_state.param);
  4601. AsyncDelegateLogger::Run(
  4602. r.get(), LOAD_STATE_WAITING_FOR_DELEGATE,
  4603. LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_IDLE,
  4604. base::BindOnce(&URLRequest::Start, base::Unretained(r.get())));
  4605. request_delegate.RunUntilComplete();
  4606. EXPECT_EQ(200, r->GetResponseCode());
  4607. EXPECT_EQ(OK, request_delegate.request_status());
  4608. }
  4609. auto entries = net_log_observer_.GetEntries();
  4610. size_t log_position = ExpectLogContainsSomewhereAfter(
  4611. entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
  4612. log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
  4613. // Nothing else should add any delegate info to the request.
  4614. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4615. NetLogEventType::DELEGATE_INFO));
  4616. }
  4617. // Tests handling of delegate info from a network delegate.
  4618. TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
  4619. ASSERT_TRUE(http_test_server()->Start());
  4620. TestDelegate request_delegate;
  4621. auto context_builder = CreateTestURLRequestContextBuilder();
  4622. auto& network_delegate = *context_builder->set_network_delegate(
  4623. std::make_unique<AsyncLoggingNetworkDelegate>());
  4624. context_builder->set_net_log(NetLog::Get());
  4625. auto context = context_builder->Build();
  4626. {
  4627. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4628. http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
  4629. &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4630. LoadStateWithParam load_state = r->GetLoadState();
  4631. EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
  4632. EXPECT_EQ(std::u16string(), load_state.param);
  4633. r->Start();
  4634. request_delegate.RunUntilComplete();
  4635. EXPECT_EQ(200, r->GetResponseCode());
  4636. EXPECT_EQ(OK, request_delegate.request_status());
  4637. EXPECT_EQ(1, network_delegate.created_requests());
  4638. EXPECT_EQ(0, network_delegate.destroyed_requests());
  4639. }
  4640. EXPECT_EQ(1, network_delegate.destroyed_requests());
  4641. size_t log_position = 0;
  4642. auto entries = net_log_observer_.GetEntries();
  4643. static const NetLogEventType kExpectedEvents[] = {
  4644. NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
  4645. NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
  4646. NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
  4647. };
  4648. for (NetLogEventType event : kExpectedEvents) {
  4649. SCOPED_TRACE(NetLogEventTypeToString(event));
  4650. log_position = ExpectLogContainsSomewhereAfter(
  4651. entries, log_position + 1, event, NetLogEventPhase::BEGIN);
  4652. log_position =
  4653. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4654. ASSERT_LT(log_position, entries.size());
  4655. EXPECT_EQ(event, entries[log_position].type);
  4656. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4657. }
  4658. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4659. NetLogEventType::DELEGATE_INFO));
  4660. }
  4661. // Tests handling of delegate info from a network delegate in the case of an
  4662. // HTTP redirect.
  4663. TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
  4664. ASSERT_TRUE(http_test_server()->Start());
  4665. TestDelegate request_delegate;
  4666. auto context_builder = CreateTestURLRequestContextBuilder();
  4667. auto& network_delegate = *context_builder->set_network_delegate(
  4668. std::make_unique<AsyncLoggingNetworkDelegate>());
  4669. auto context = context_builder->Build();
  4670. {
  4671. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4672. http_test_server()->GetURL("/server-redirect?simple.html"),
  4673. DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4674. LoadStateWithParam load_state = r->GetLoadState();
  4675. EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
  4676. EXPECT_EQ(std::u16string(), load_state.param);
  4677. r->Start();
  4678. request_delegate.RunUntilComplete();
  4679. EXPECT_EQ(200, r->GetResponseCode());
  4680. EXPECT_EQ(OK, request_delegate.request_status());
  4681. EXPECT_EQ(2, network_delegate.created_requests());
  4682. EXPECT_EQ(0, network_delegate.destroyed_requests());
  4683. }
  4684. EXPECT_EQ(1, network_delegate.destroyed_requests());
  4685. size_t log_position = 0;
  4686. auto entries = net_log_observer_.GetEntries();
  4687. static const NetLogEventType kExpectedEvents[] = {
  4688. NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
  4689. NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
  4690. NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
  4691. };
  4692. for (NetLogEventType event : kExpectedEvents) {
  4693. SCOPED_TRACE(NetLogEventTypeToString(event));
  4694. log_position = ExpectLogContainsSomewhereAfter(
  4695. entries, log_position + 1, event, NetLogEventPhase::BEGIN);
  4696. log_position =
  4697. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4698. ASSERT_LT(log_position, entries.size());
  4699. EXPECT_EQ(event, entries[log_position].type);
  4700. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4701. }
  4702. // The URLRequest::Delegate then gets informed about the redirect.
  4703. log_position = ExpectLogContainsSomewhereAfter(
  4704. entries, log_position + 1,
  4705. NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
  4706. NetLogEventPhase::BEGIN);
  4707. // The NetworkDelegate logged information in the same three events as before.
  4708. for (NetLogEventType event : kExpectedEvents) {
  4709. SCOPED_TRACE(NetLogEventTypeToString(event));
  4710. log_position = ExpectLogContainsSomewhereAfter(
  4711. entries, log_position + 1, event, NetLogEventPhase::BEGIN);
  4712. log_position =
  4713. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4714. ASSERT_LT(log_position, entries.size());
  4715. EXPECT_EQ(event, entries[log_position].type);
  4716. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4717. }
  4718. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4719. NetLogEventType::DELEGATE_INFO));
  4720. }
  4721. // Tests handling of delegate info from a URLRequest::Delegate.
  4722. TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
  4723. ASSERT_TRUE(http_test_server()->Start());
  4724. AsyncLoggingUrlRequestDelegate request_delegate(
  4725. AsyncLoggingUrlRequestDelegate::NO_CANCEL);
  4726. auto context_builder = CreateTestURLRequestContextBuilder();
  4727. context_builder->set_net_log(NetLog::Get());
  4728. auto context = context_builder->Build();
  4729. {
  4730. // A chunked response with delays between chunks is used to make sure that
  4731. // attempts by the URLRequest delegate to log information while reading the
  4732. // body are ignored. Since they are ignored, this test is robust against
  4733. // the possibility of multiple reads being combined in the unlikely event
  4734. // that it occurs.
  4735. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4736. http_test_server()->GetURL("/chunked?waitBetweenChunks=20"),
  4737. DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4738. LoadStateWithParam load_state = r->GetLoadState();
  4739. r->Start();
  4740. request_delegate.RunUntilComplete();
  4741. EXPECT_EQ(200, r->GetResponseCode());
  4742. EXPECT_EQ(OK, request_delegate.request_status());
  4743. }
  4744. auto entries = net_log_observer_.GetEntries();
  4745. size_t log_position = 0;
  4746. // The delegate info should only have been logged on header complete. Other
  4747. // times it should silently be ignored.
  4748. log_position = ExpectLogContainsSomewhereAfter(
  4749. entries, log_position + 1,
  4750. NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
  4751. NetLogEventPhase::BEGIN);
  4752. log_position =
  4753. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4754. ASSERT_LT(log_position, entries.size());
  4755. EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
  4756. entries[log_position].type);
  4757. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4758. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4759. NetLogEventType::DELEGATE_INFO));
  4760. EXPECT_FALSE(LogContainsEntryWithTypeAfter(
  4761. entries, log_position + 1,
  4762. NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
  4763. }
  4764. // Tests handling of delegate info from a URLRequest::Delegate in the case of
  4765. // an HTTP redirect.
  4766. TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
  4767. ASSERT_TRUE(http_test_server()->Start());
  4768. AsyncLoggingUrlRequestDelegate request_delegate(
  4769. AsyncLoggingUrlRequestDelegate::NO_CANCEL);
  4770. auto context_builder = CreateTestURLRequestContextBuilder();
  4771. context_builder->set_net_log(NetLog::Get());
  4772. auto context = context_builder->Build();
  4773. {
  4774. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4775. http_test_server()->GetURL("/server-redirect?simple.html"),
  4776. DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4777. LoadStateWithParam load_state = r->GetLoadState();
  4778. r->Start();
  4779. request_delegate.RunUntilComplete();
  4780. EXPECT_EQ(200, r->GetResponseCode());
  4781. EXPECT_EQ(OK, request_delegate.request_status());
  4782. }
  4783. auto entries = net_log_observer_.GetEntries();
  4784. // Delegate info should only have been logged in OnReceivedRedirect and
  4785. // OnResponseStarted.
  4786. size_t log_position = 0;
  4787. static const NetLogEventType kExpectedEvents[] = {
  4788. NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
  4789. NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
  4790. };
  4791. for (NetLogEventType event : kExpectedEvents) {
  4792. SCOPED_TRACE(NetLogEventTypeToString(event));
  4793. log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
  4794. NetLogEventPhase::BEGIN);
  4795. log_position =
  4796. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4797. ASSERT_LT(log_position, entries.size());
  4798. EXPECT_EQ(event, entries[log_position].type);
  4799. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4800. }
  4801. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4802. NetLogEventType::DELEGATE_INFO));
  4803. }
  4804. // Tests handling of delegate info from a URLRequest::Delegate in the case of
  4805. // an HTTP redirect, with cancellation at various points.
  4806. TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
  4807. ASSERT_TRUE(http_test_server()->Start());
  4808. const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
  4809. AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
  4810. AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
  4811. AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
  4812. };
  4813. for (auto cancel_stage : kCancelStages) {
  4814. AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
  4815. RecordingNetLogObserver net_log_observer;
  4816. auto context_builder = CreateTestURLRequestContextBuilder();
  4817. context_builder->set_net_log(NetLog::Get());
  4818. auto context = context_builder->Build();
  4819. {
  4820. std::unique_ptr<URLRequest> r(context->CreateRequest(
  4821. http_test_server()->GetURL("/server-redirect?simple.html"),
  4822. DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  4823. LoadStateWithParam load_state = r->GetLoadState();
  4824. r->Start();
  4825. request_delegate.RunUntilComplete();
  4826. EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
  4827. // Spin the message loop to run AsyncDelegateLogger task(s) posted after
  4828. // the |request_delegate| completion task.
  4829. base::RunLoop().RunUntilIdle();
  4830. }
  4831. auto entries = net_log_observer.GetEntries();
  4832. // Delegate info is always logged in both OnReceivedRedirect and
  4833. // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
  4834. // OnResponseStarted delegate call is after cancellation, but logging is
  4835. // still currently supported in that call.
  4836. size_t log_position = 0;
  4837. static const NetLogEventType kExpectedEvents[] = {
  4838. NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
  4839. NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
  4840. };
  4841. for (NetLogEventType event : kExpectedEvents) {
  4842. SCOPED_TRACE(NetLogEventTypeToString(event));
  4843. log_position = ExpectLogContainsSomewhereAfter(
  4844. entries, log_position, event, NetLogEventPhase::BEGIN);
  4845. log_position =
  4846. AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
  4847. ASSERT_LT(log_position, entries.size());
  4848. EXPECT_EQ(event, entries[log_position].type);
  4849. EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
  4850. }
  4851. EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
  4852. NetLogEventType::DELEGATE_INFO));
  4853. }
  4854. }
  4855. namespace {
  4856. const char kExtraHeader[] = "Allow-Snafu";
  4857. const char kExtraValue[] = "fubar";
  4858. class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
  4859. void OnReceivedRedirect(URLRequest* request,
  4860. const RedirectInfo& redirect_info,
  4861. bool* defer_redirect) override {
  4862. TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
  4863. request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
  4864. }
  4865. };
  4866. } // namespace
  4867. TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
  4868. ASSERT_TRUE(http_test_server()->Start());
  4869. GURL destination_url =
  4870. http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
  4871. GURL original_url =
  4872. http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
  4873. RedirectWithAdditionalHeadersDelegate d;
  4874. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  4875. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  4876. req->Start();
  4877. d.RunUntilComplete();
  4878. std::string value;
  4879. const HttpRequestHeaders& headers = req->extra_request_headers();
  4880. EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
  4881. EXPECT_EQ(kExtraValue, value);
  4882. EXPECT_FALSE(req->is_pending());
  4883. EXPECT_FALSE(req->is_redirecting());
  4884. EXPECT_EQ(kExtraValue, d.data_received());
  4885. }
  4886. namespace {
  4887. const char kExtraHeaderToRemove[] = "To-Be-Removed";
  4888. class RedirectWithHeaderRemovalDelegate : public TestDelegate {
  4889. void OnReceivedRedirect(URLRequest* request,
  4890. const RedirectInfo& redirect_info,
  4891. bool* defer_redirect) override {
  4892. TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
  4893. request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
  4894. }
  4895. };
  4896. } // namespace
  4897. TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
  4898. ASSERT_TRUE(http_test_server()->Start());
  4899. GURL destination_url = http_test_server()->GetURL(
  4900. "/echoheader?" + std::string(kExtraHeaderToRemove));
  4901. GURL original_url =
  4902. http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
  4903. RedirectWithHeaderRemovalDelegate d;
  4904. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  4905. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  4906. req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
  4907. req->Start();
  4908. d.RunUntilComplete();
  4909. std::string value;
  4910. const HttpRequestHeaders& headers = req->extra_request_headers();
  4911. EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
  4912. EXPECT_FALSE(req->is_pending());
  4913. EXPECT_FALSE(req->is_redirecting());
  4914. EXPECT_EQ("None", d.data_received());
  4915. }
  4916. TEST_F(URLRequestTestHTTP, CancelAfterStart) {
  4917. TestDelegate d;
  4918. {
  4919. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4920. GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
  4921. TRAFFIC_ANNOTATION_FOR_TESTS));
  4922. r->Start();
  4923. EXPECT_TRUE(r->is_pending());
  4924. r->Cancel();
  4925. d.RunUntilComplete();
  4926. // We expect to receive OnResponseStarted even though the request has been
  4927. // cancelled.
  4928. EXPECT_EQ(1, d.response_started_count());
  4929. EXPECT_EQ(0, d.bytes_received());
  4930. EXPECT_FALSE(d.received_data_before_response());
  4931. }
  4932. }
  4933. TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
  4934. ASSERT_TRUE(http_test_server()->Start());
  4935. TestDelegate d;
  4936. {
  4937. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4938. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  4939. TRAFFIC_ANNOTATION_FOR_TESTS));
  4940. d.set_cancel_in_response_started(true);
  4941. r->Start();
  4942. EXPECT_TRUE(r->is_pending());
  4943. d.RunUntilComplete();
  4944. EXPECT_EQ(1, d.response_started_count());
  4945. EXPECT_EQ(0, d.bytes_received());
  4946. EXPECT_FALSE(d.received_data_before_response());
  4947. EXPECT_EQ(ERR_ABORTED, d.request_status());
  4948. }
  4949. }
  4950. TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
  4951. ASSERT_TRUE(http_test_server()->Start());
  4952. TestDelegate d;
  4953. {
  4954. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4955. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  4956. TRAFFIC_ANNOTATION_FOR_TESTS));
  4957. d.set_cancel_in_received_data(true);
  4958. r->Start();
  4959. EXPECT_TRUE(r->is_pending());
  4960. d.RunUntilComplete();
  4961. EXPECT_EQ(1, d.response_started_count());
  4962. EXPECT_NE(0, d.received_bytes_count());
  4963. EXPECT_FALSE(d.received_data_before_response());
  4964. EXPECT_EQ(ERR_ABORTED, d.request_status());
  4965. }
  4966. }
  4967. TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
  4968. ASSERT_TRUE(http_test_server()->Start());
  4969. TestDelegate d;
  4970. {
  4971. // This returns an empty response (With headers).
  4972. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4973. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  4974. TRAFFIC_ANNOTATION_FOR_TESTS));
  4975. d.set_cancel_in_received_data(true);
  4976. r->Start();
  4977. EXPECT_TRUE(r->is_pending());
  4978. d.RunUntilComplete();
  4979. EXPECT_EQ(1, d.response_started_count());
  4980. EXPECT_EQ(0, d.received_bytes_count());
  4981. EXPECT_FALSE(d.received_data_before_response());
  4982. EXPECT_EQ(ERR_ABORTED, d.request_status());
  4983. }
  4984. }
  4985. TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
  4986. ASSERT_TRUE(http_test_server()->Start());
  4987. TestDelegate d;
  4988. {
  4989. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  4990. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  4991. TRAFFIC_ANNOTATION_FOR_TESTS));
  4992. r->Start();
  4993. EXPECT_TRUE(r->is_pending());
  4994. // The request will be implicitly canceled when it is destroyed. The
  4995. // test delegate must not post a quit message when this happens because
  4996. // this test doesn't actually have a message loop. The quit message would
  4997. // get put on this thread's message queue and the next test would exit
  4998. // early, causing problems.
  4999. d.set_on_complete(base::DoNothing());
  5000. }
  5001. // expect things to just cleanup properly.
  5002. // we won't actually get a received response here because we've never run the
  5003. // message loop
  5004. EXPECT_FALSE(d.received_data_before_response());
  5005. EXPECT_EQ(0, d.bytes_received());
  5006. }
  5007. TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
  5008. ASSERT_TRUE(http_test_server()->Start());
  5009. // populate cache
  5010. {
  5011. TestDelegate d;
  5012. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5013. http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
  5014. TRAFFIC_ANNOTATION_FOR_TESTS));
  5015. r->Start();
  5016. d.RunUntilComplete();
  5017. EXPECT_EQ(OK, d.request_status());
  5018. }
  5019. // cancel read from cache (see bug 990242)
  5020. {
  5021. TestDelegate d;
  5022. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5023. http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
  5024. TRAFFIC_ANNOTATION_FOR_TESTS));
  5025. r->Start();
  5026. r->Cancel();
  5027. d.RunUntilComplete();
  5028. EXPECT_EQ(ERR_ABORTED, d.request_status());
  5029. EXPECT_EQ(1, d.response_started_count());
  5030. EXPECT_EQ(0, d.bytes_received());
  5031. EXPECT_FALSE(d.received_data_before_response());
  5032. }
  5033. }
  5034. TEST_F(URLRequestTestHTTP, PostTest) {
  5035. ASSERT_TRUE(http_test_server()->Start());
  5036. HTTPUploadDataOperationTest("POST");
  5037. }
  5038. TEST_F(URLRequestTestHTTP, PutTest) {
  5039. ASSERT_TRUE(http_test_server()->Start());
  5040. HTTPUploadDataOperationTest("PUT");
  5041. }
  5042. TEST_F(URLRequestTestHTTP, PostEmptyTest) {
  5043. ASSERT_TRUE(http_test_server()->Start());
  5044. TestDelegate d;
  5045. {
  5046. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5047. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5048. TRAFFIC_ANNOTATION_FOR_TESTS));
  5049. r->set_method("POST");
  5050. r->Start();
  5051. EXPECT_TRUE(r->is_pending());
  5052. d.RunUntilComplete();
  5053. ASSERT_EQ(1, d.response_started_count())
  5054. << "request failed. Error: " << d.request_status();
  5055. EXPECT_FALSE(d.received_data_before_response());
  5056. EXPECT_TRUE(d.data_received().empty());
  5057. }
  5058. }
  5059. TEST_F(URLRequestTestHTTP, PostFileTest) {
  5060. ASSERT_TRUE(http_test_server()->Start());
  5061. TestDelegate d;
  5062. {
  5063. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5064. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5065. TRAFFIC_ANNOTATION_FOR_TESTS));
  5066. r->set_method("POST");
  5067. base::FilePath dir;
  5068. base::PathService::Get(base::DIR_EXE, &dir);
  5069. base::SetCurrentDirectory(dir);
  5070. std::vector<std::unique_ptr<UploadElementReader>> element_readers;
  5071. base::FilePath path;
  5072. base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
  5073. path = path.Append(kTestFilePath);
  5074. path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
  5075. element_readers.push_back(std::make_unique<UploadFileElementReader>(
  5076. base::ThreadTaskRunnerHandle::Get().get(), path, 0,
  5077. std::numeric_limits<uint64_t>::max(), base::Time()));
  5078. r->set_upload(std::make_unique<ElementsUploadDataStream>(
  5079. std::move(element_readers), 0));
  5080. r->Start();
  5081. EXPECT_TRUE(r->is_pending());
  5082. d.RunUntilComplete();
  5083. int64_t size64 = 0;
  5084. ASSERT_EQ(true, base::GetFileSize(path, &size64));
  5085. ASSERT_LE(size64, std::numeric_limits<int>::max());
  5086. int size = static_cast<int>(size64);
  5087. auto buf = std::make_unique<char[]>(size);
  5088. ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
  5089. ASSERT_EQ(1, d.response_started_count())
  5090. << "request failed. Error: " << d.request_status();
  5091. EXPECT_FALSE(d.received_data_before_response());
  5092. EXPECT_EQ(size, d.bytes_received());
  5093. EXPECT_EQ(std::string(&buf[0], size), d.data_received());
  5094. }
  5095. }
  5096. TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
  5097. ASSERT_TRUE(http_test_server()->Start());
  5098. TestDelegate d;
  5099. {
  5100. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5101. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5102. TRAFFIC_ANNOTATION_FOR_TESTS));
  5103. r->set_method("POST");
  5104. std::vector<std::unique_ptr<UploadElementReader>> element_readers;
  5105. element_readers.push_back(std::make_unique<UploadFileElementReader>(
  5106. base::ThreadTaskRunnerHandle::Get().get(),
  5107. base::FilePath(FILE_PATH_LITERAL(
  5108. "c:\\path\\to\\non\\existant\\file.randomness.12345")),
  5109. 0, std::numeric_limits<uint64_t>::max(), base::Time()));
  5110. r->set_upload(std::make_unique<ElementsUploadDataStream>(
  5111. std::move(element_readers), 0));
  5112. r->Start();
  5113. EXPECT_TRUE(r->is_pending());
  5114. d.RunUntilComplete();
  5115. EXPECT_TRUE(d.request_failed());
  5116. EXPECT_FALSE(d.received_data_before_response());
  5117. EXPECT_EQ(0, d.bytes_received());
  5118. EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
  5119. }
  5120. }
  5121. namespace {
  5122. // Adds a standard set of data to an upload for chunked upload integration
  5123. // tests.
  5124. void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
  5125. writer->AppendData("a", 1, false);
  5126. writer->AppendData("bcd", 3, false);
  5127. writer->AppendData("this is a longer chunk than before.", 35, false);
  5128. writer->AppendData("\r\n\r\n", 4, false);
  5129. writer->AppendData("0", 1, false);
  5130. writer->AppendData("2323", 4, true);
  5131. }
  5132. // Checks that the upload data added in AddChunksToUpload() was echoed back from
  5133. // the server.
  5134. void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
  5135. // This should match the chunks sent by AddChunksToUpload().
  5136. const std::string expected_data =
  5137. "abcdthis is a longer chunk than before.\r\n\r\n02323";
  5138. ASSERT_EQ(1, d->response_started_count())
  5139. << "request failed. Error: " << d->request_status();
  5140. EXPECT_FALSE(d->received_data_before_response());
  5141. EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
  5142. EXPECT_EQ(expected_data, d->data_received());
  5143. }
  5144. } // namespace
  5145. TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
  5146. ASSERT_TRUE(http_test_server()->Start());
  5147. TestDelegate d;
  5148. {
  5149. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5150. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5151. TRAFFIC_ANNOTATION_FOR_TESTS));
  5152. auto upload_data_stream = std::make_unique<ChunkedUploadDataStream>(0);
  5153. std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
  5154. upload_data_stream->CreateWriter();
  5155. r->set_upload(std::move(upload_data_stream));
  5156. r->set_method("POST");
  5157. AddDataToUpload(writer.get());
  5158. r->Start();
  5159. EXPECT_TRUE(r->is_pending());
  5160. d.RunUntilComplete();
  5161. VerifyReceivedDataMatchesChunks(r.get(), &d);
  5162. }
  5163. }
  5164. TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
  5165. ASSERT_TRUE(http_test_server()->Start());
  5166. TestDelegate d;
  5167. {
  5168. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5169. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5170. TRAFFIC_ANNOTATION_FOR_TESTS));
  5171. auto upload_data_stream = std::make_unique<ChunkedUploadDataStream>(0);
  5172. std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
  5173. upload_data_stream->CreateWriter();
  5174. r->set_upload(std::move(upload_data_stream));
  5175. r->set_method("POST");
  5176. r->Start();
  5177. EXPECT_TRUE(r->is_pending());
  5178. AddDataToUpload(writer.get());
  5179. d.RunUntilComplete();
  5180. VerifyReceivedDataMatchesChunks(r.get(), &d);
  5181. }
  5182. }
  5183. TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
  5184. ASSERT_TRUE(http_test_server()->Start());
  5185. TestDelegate d;
  5186. {
  5187. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  5188. http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
  5189. TRAFFIC_ANNOTATION_FOR_TESTS));
  5190. auto upload_data_stream = std::make_unique<ChunkedUploadDataStream>(0);
  5191. std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
  5192. upload_data_stream->CreateWriter();
  5193. r->set_upload(std::move(upload_data_stream));
  5194. r->set_method("POST");
  5195. r->Start();
  5196. EXPECT_TRUE(r->is_pending());
  5197. // Pump messages until we start sending headers..
  5198. base::RunLoop().RunUntilIdle();
  5199. // And now wait for completion.
  5200. base::RunLoop run_loop;
  5201. d.set_on_complete(run_loop.QuitClosure());
  5202. AddDataToUpload(writer.get());
  5203. run_loop.Run();
  5204. VerifyReceivedDataMatchesChunks(r.get(), &d);
  5205. }
  5206. }
  5207. TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
  5208. ASSERT_TRUE(http_test_server()->Start());
  5209. TestDelegate d;
  5210. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  5211. http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
  5212. TRAFFIC_ANNOTATION_FOR_TESTS));
  5213. req->Start();
  5214. d.RunUntilComplete();
  5215. const HttpResponseHeaders* headers = req->response_headers();
  5216. // Simple sanity check that response_info() accesses the same data.
  5217. EXPECT_EQ(headers, req->response_info().headers.get());
  5218. std::string header;
  5219. EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
  5220. EXPECT_EQ("private", header);
  5221. header.clear();
  5222. EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
  5223. EXPECT_EQ("text/html; charset=ISO-8859-1", header);
  5224. // The response has two "X-Multiple-Entries" headers.
  5225. // This verfies our output has them concatenated together.
  5226. header.clear();
  5227. EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
  5228. EXPECT_EQ("a, b", header);
  5229. }
  5230. // TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
  5231. // security state. (see http://crbug.com/550977).
  5232. #if !BUILDFLAG(IS_IOS)
  5233. TEST_F(URLRequestTestHTTP, ProcessSTS) {
  5234. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5235. https_test_server.SetSSLConfig(
  5236. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5237. https_test_server.ServeFilesFromSourceDirectory(
  5238. base::FilePath(kTestFilePath));
  5239. ASSERT_TRUE(https_test_server.Start());
  5240. std::string test_server_hostname = https_test_server.GetURL("/").host();
  5241. TestDelegate d;
  5242. std::unique_ptr<URLRequest> request(default_context().CreateRequest(
  5243. https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
  5244. TRAFFIC_ANNOTATION_FOR_TESTS));
  5245. request->Start();
  5246. d.RunUntilComplete();
  5247. TransportSecurityState* security_state =
  5248. default_context().transport_security_state();
  5249. TransportSecurityState::STSState sts_state;
  5250. TransportSecurityState::PKPState pkp_state;
  5251. EXPECT_TRUE(
  5252. security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
  5253. EXPECT_FALSE(
  5254. security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
  5255. EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
  5256. sts_state.upgrade_mode);
  5257. EXPECT_TRUE(sts_state.include_subdomains);
  5258. EXPECT_FALSE(pkp_state.include_subdomains);
  5259. #if BUILDFLAG(IS_ANDROID)
  5260. // Android's CertVerifyProc does not (yet) handle pins.
  5261. #else
  5262. EXPECT_FALSE(pkp_state.HasPublicKeyPins());
  5263. #endif
  5264. }
  5265. TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
  5266. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5267. https_test_server.ServeFilesFromSourceDirectory(
  5268. base::FilePath(kTestFilePath));
  5269. ASSERT_TRUE(https_test_server.Start());
  5270. // Make sure this test fails if the test server is changed to not
  5271. // listen on an IP by default.
  5272. ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
  5273. std::string test_server_hostname = https_test_server.GetURL("/").host();
  5274. TestDelegate d;
  5275. std::unique_ptr<URLRequest> request(default_context().CreateRequest(
  5276. https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
  5277. TRAFFIC_ANNOTATION_FOR_TESTS));
  5278. request->Start();
  5279. d.RunUntilComplete();
  5280. TransportSecurityState* security_state =
  5281. default_context().transport_security_state();
  5282. TransportSecurityState::STSState sts_state;
  5283. EXPECT_FALSE(
  5284. security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
  5285. }
  5286. namespace {
  5287. const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
  5288. const char kPKPReportUri[] = "http://report-uri.preloaded.test/pkp";
  5289. const char kPKPHost[] = "with-report-uri-pkp.preloaded.test";
  5290. } // namespace
  5291. // Tests that reports get sent on PKP violations when a report-uri is set.
  5292. TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
  5293. base::test::ScopedFeatureList scoped_feature_list_;
  5294. scoped_feature_list_.InitAndEnableFeature(
  5295. net::features::kStaticKeyPinningEnforcement);
  5296. GURL report_uri(kPKPReportUri);
  5297. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5298. https_test_server.SetSSLConfig(
  5299. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5300. https_test_server.ServeFilesFromSourceDirectory(
  5301. base::FilePath(kTestFilePath));
  5302. ASSERT_TRUE(https_test_server.Start());
  5303. std::string test_server_hostname = kPKPHost;
  5304. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  5305. // Set up a MockCertVerifier to trigger a violation of the previously
  5306. // set pin.
  5307. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5308. ASSERT_TRUE(cert);
  5309. CertVerifyResult verify_result;
  5310. verify_result.verified_cert = cert;
  5311. verify_result.is_issued_by_known_root = true;
  5312. HashValue hash3;
  5313. ASSERT_TRUE(
  5314. hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
  5315. verify_result.public_key_hashes.push_back(hash3);
  5316. auto cert_verifier = std::make_unique<MockCertVerifier>();
  5317. cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5318. auto context_builder = CreateTestURLRequestContextBuilder();
  5319. context_builder->SetCertVerifier(std::move(cert_verifier));
  5320. auto context = context_builder->Build();
  5321. MockCertificateReportSender mock_report_sender;
  5322. context->transport_security_state()->EnableStaticPinsForTesting();
  5323. context->transport_security_state()->SetPinningListAlwaysTimelyForTesting(
  5324. true);
  5325. context->transport_security_state()->SetReportSender(&mock_report_sender);
  5326. IsolationInfo isolation_info = IsolationInfo::CreateTransient();
  5327. // Now send a request to trigger the violation.
  5328. TestDelegate d;
  5329. std::unique_ptr<URLRequest> violating_request(context->CreateRequest(
  5330. https_test_server.GetURL(test_server_hostname, "/simple.html"),
  5331. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5332. violating_request->set_isolation_info(isolation_info);
  5333. violating_request->Start();
  5334. d.RunUntilComplete();
  5335. // Check that a report was sent.
  5336. EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
  5337. ASSERT_FALSE(mock_report_sender.latest_report().empty());
  5338. EXPECT_EQ("application/json; charset=utf-8",
  5339. mock_report_sender.latest_content_type());
  5340. std::unique_ptr<base::Value> value(
  5341. base::JSONReader::ReadDeprecated(mock_report_sender.latest_report()));
  5342. ASSERT_TRUE(value);
  5343. base::Value::Dict* report_dict = value->GetIfDict();
  5344. ASSERT_TRUE(report_dict);
  5345. std::string* report_hostname = report_dict->FindString("hostname");
  5346. ASSERT_TRUE(report_hostname);
  5347. EXPECT_EQ(test_server_hostname, *report_hostname);
  5348. EXPECT_EQ(isolation_info.network_isolation_key(),
  5349. mock_report_sender.latest_network_isolation_key());
  5350. }
  5351. // Tests that reports do not get sent on requests to static pkp hosts that
  5352. // don't have pin violations.
  5353. TEST_F(URLRequestTestHTTP, ProcessPKPWithNoViolation) {
  5354. base::test::ScopedFeatureList scoped_feature_list_;
  5355. scoped_feature_list_.InitAndEnableFeature(
  5356. net::features::kStaticKeyPinningEnforcement);
  5357. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5358. https_test_server.SetSSLConfig(
  5359. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5360. https_test_server.ServeFilesFromSourceDirectory(
  5361. base::FilePath(kTestFilePath));
  5362. ASSERT_TRUE(https_test_server.Start());
  5363. std::string test_server_hostname = kPKPHost;
  5364. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  5365. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5366. ASSERT_TRUE(cert);
  5367. CertVerifyResult verify_result;
  5368. verify_result.verified_cert = cert;
  5369. verify_result.is_issued_by_known_root = true;
  5370. HashValue hash;
  5371. // The expected value of GoodPin1 used by |test_default::kHSTSSource|.
  5372. ASSERT_TRUE(
  5373. hash.FromString("sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY="));
  5374. verify_result.public_key_hashes.push_back(hash);
  5375. auto mock_cert_verifier = std::make_unique<MockCertVerifier>();
  5376. mock_cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5377. auto context_builder = CreateTestURLRequestContextBuilder();
  5378. context_builder->SetCertVerifier(std::move(mock_cert_verifier));
  5379. auto context = context_builder->Build();
  5380. MockCertificateReportSender mock_report_sender;
  5381. context->transport_security_state()->EnableStaticPinsForTesting();
  5382. context->transport_security_state()->SetPinningListAlwaysTimelyForTesting(
  5383. true);
  5384. context->transport_security_state()->SetReportSender(&mock_report_sender);
  5385. // Now send a request that does not trigger the violation.
  5386. TestDelegate d;
  5387. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5388. https_test_server.GetURL(test_server_hostname, "/simple.html"),
  5389. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5390. request->set_isolation_info(IsolationInfo::CreateTransient());
  5391. request->Start();
  5392. d.RunUntilComplete();
  5393. // Check that the request succeeded, a report was not sent and the pkp was
  5394. // not bypassed.
  5395. EXPECT_EQ(OK, d.request_status());
  5396. EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
  5397. EXPECT_EQ(std::string(), mock_report_sender.latest_report());
  5398. EXPECT_EQ(NetworkIsolationKey(),
  5399. mock_report_sender.latest_network_isolation_key());
  5400. TransportSecurityState::PKPState pkp_state;
  5401. EXPECT_TRUE(context->transport_security_state()->GetStaticPKPState(
  5402. test_server_hostname, &pkp_state));
  5403. EXPECT_TRUE(pkp_state.HasPublicKeyPins());
  5404. EXPECT_FALSE(request->ssl_info().pkp_bypassed);
  5405. }
  5406. TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
  5407. base::test::ScopedFeatureList scoped_feature_list_;
  5408. scoped_feature_list_.InitAndEnableFeature(
  5409. net::features::kStaticKeyPinningEnforcement);
  5410. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5411. https_test_server.SetSSLConfig(
  5412. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5413. https_test_server.ServeFilesFromSourceDirectory(
  5414. base::FilePath(kTestFilePath));
  5415. ASSERT_TRUE(https_test_server.Start());
  5416. // Set up a MockCertVerifier to be a local root that violates the pin
  5417. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5418. ASSERT_TRUE(cert);
  5419. CertVerifyResult verify_result;
  5420. verify_result.verified_cert = cert;
  5421. verify_result.is_issued_by_known_root = false;
  5422. HashValue hash;
  5423. ASSERT_TRUE(
  5424. hash.FromString("sha256/1111111111111111111111111111111111111111111="));
  5425. verify_result.public_key_hashes.push_back(hash);
  5426. auto cert_verifier = std::make_unique<MockCertVerifier>();
  5427. cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5428. std::string test_server_hostname = kPKPHost;
  5429. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  5430. auto context_builder = CreateTestURLRequestContextBuilder();
  5431. context_builder->SetCertVerifier(std::move(cert_verifier));
  5432. auto context = context_builder->Build();
  5433. MockCertificateReportSender mock_report_sender;
  5434. context->transport_security_state()->EnableStaticPinsForTesting();
  5435. context->transport_security_state()->SetPinningListAlwaysTimelyForTesting(
  5436. true);
  5437. context->transport_security_state()->SetReportSender(&mock_report_sender);
  5438. TestDelegate d;
  5439. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5440. https_test_server.GetURL(test_server_hostname, "/simple.html"),
  5441. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5442. request->set_isolation_info(IsolationInfo::CreateTransient());
  5443. request->Start();
  5444. d.RunUntilComplete();
  5445. // Check that the request succeeded, a report was not sent and the PKP was
  5446. // bypassed.
  5447. EXPECT_EQ(OK, d.request_status());
  5448. EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
  5449. EXPECT_EQ(std::string(), mock_report_sender.latest_report());
  5450. EXPECT_EQ(NetworkIsolationKey(),
  5451. mock_report_sender.latest_network_isolation_key());
  5452. TransportSecurityState::PKPState pkp_state;
  5453. EXPECT_TRUE(context->transport_security_state()->GetStaticPKPState(
  5454. test_server_hostname, &pkp_state));
  5455. EXPECT_TRUE(pkp_state.HasPublicKeyPins());
  5456. EXPECT_TRUE(request->ssl_info().pkp_bypassed);
  5457. }
  5458. TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
  5459. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5460. https_test_server.SetSSLConfig(
  5461. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5462. https_test_server.ServeFilesFromSourceDirectory(
  5463. base::FilePath(kTestFilePath));
  5464. ASSERT_TRUE(https_test_server.Start());
  5465. std::string test_server_hostname = https_test_server.GetURL("/").host();
  5466. TestDelegate d;
  5467. std::unique_ptr<URLRequest> request(default_context().CreateRequest(
  5468. https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
  5469. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5470. request->Start();
  5471. d.RunUntilComplete();
  5472. // We should have set parameters from the first header, not the second.
  5473. TransportSecurityState* security_state =
  5474. default_context().transport_security_state();
  5475. TransportSecurityState::STSState sts_state;
  5476. EXPECT_TRUE(
  5477. security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
  5478. EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
  5479. sts_state.upgrade_mode);
  5480. EXPECT_FALSE(sts_state.include_subdomains);
  5481. EXPECT_FALSE(sts_state.include_subdomains);
  5482. }
  5483. // An ExpectCTReporter that records the number of times OnExpectCTFailed() was
  5484. // called.
  5485. class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
  5486. public:
  5487. MockExpectCTReporter() = default;
  5488. ~MockExpectCTReporter() override = default;
  5489. void OnExpectCTFailed(
  5490. const HostPortPair& host_port_pair,
  5491. const GURL& report_uri,
  5492. base::Time expiration,
  5493. const X509Certificate* validated_certificate_chain,
  5494. const X509Certificate* served_certificate_chain,
  5495. const SignedCertificateTimestampAndStatusList&
  5496. signed_certificate_timestamps,
  5497. const NetworkIsolationKey& network_isolation_key) override {
  5498. num_failures_++;
  5499. }
  5500. uint32_t num_failures() { return num_failures_; }
  5501. private:
  5502. uint32_t num_failures_ = 0;
  5503. };
  5504. // A CTPolicyEnforcer that returns a default CTPolicyCompliance value
  5505. // for every certificate.
  5506. class MockCTPolicyEnforcer : public CTPolicyEnforcer {
  5507. public:
  5508. MockCTPolicyEnforcer() = default;
  5509. ~MockCTPolicyEnforcer() override = default;
  5510. ct::CTPolicyCompliance CheckCompliance(
  5511. X509Certificate* cert,
  5512. const ct::SCTList& verified_scts,
  5513. const NetLogWithSource& net_log) override {
  5514. return default_result_;
  5515. }
  5516. void set_default_result(ct::CTPolicyCompliance default_result) {
  5517. default_result_ = default_result;
  5518. }
  5519. private:
  5520. ct::CTPolicyCompliance default_result_ =
  5521. ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
  5522. };
  5523. // Tests that Expect CT headers for the preload list are processed correctly.
  5524. TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
  5525. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  5526. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5527. https_test_server.SetSSLConfig(
  5528. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5529. https_test_server.ServeFilesFromSourceDirectory(
  5530. base::FilePath(kTestFilePath));
  5531. ASSERT_TRUE(https_test_server.Start());
  5532. // Set up a MockCertVerifier to accept the certificate that the server sends.
  5533. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5534. ASSERT_TRUE(cert);
  5535. CertVerifyResult verify_result;
  5536. verify_result.verified_cert = cert;
  5537. verify_result.is_issued_by_known_root = true;
  5538. auto cert_verifier = std::make_unique<MockCertVerifier>();
  5539. cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5540. // Set up a MockCTPolicyEnforcer to trigger an Expect CT violation.
  5541. auto ct_policy_enforcer = std::make_unique<MockCTPolicyEnforcer>();
  5542. ct_policy_enforcer->set_default_result(
  5543. ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
  5544. // Use a MockHostResolver, so that the request can be sent to a site on the
  5545. // Expect CT preload list.
  5546. auto host_resolver = std::make_unique<MockHostResolver>();
  5547. host_resolver->rules()->AddRule(kExpectCTStaticHostname,
  5548. https_test_server.GetIPLiteralString());
  5549. auto context_builder = CreateTestURLRequestContextBuilder();
  5550. context_builder->set_host_resolver(std::move(host_resolver));
  5551. context_builder->SetCertVerifier(std::move(cert_verifier));
  5552. context_builder->set_ct_policy_enforcer(std::move(ct_policy_enforcer));
  5553. context_builder->set_hsts_policy_bypass_list({});
  5554. auto context = context_builder->Build();
  5555. MockExpectCTReporter expect_ct_reporter;
  5556. context->transport_security_state()->enable_static_expect_ct_ = true;
  5557. context->transport_security_state()->SetExpectCTReporter(&expect_ct_reporter);
  5558. context->transport_security_state()->ct_log_list_last_update_time_ =
  5559. base::Time::Now();
  5560. // Now send a request to trigger the violation.
  5561. TestDelegate d;
  5562. GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
  5563. GURL::Replacements replace_host;
  5564. replace_host.SetHostStr(kExpectCTStaticHostname);
  5565. url = url.ReplaceComponents(replace_host);
  5566. std::unique_ptr<URLRequest> violating_request(context->CreateRequest(
  5567. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5568. violating_request->Start();
  5569. d.RunUntilComplete();
  5570. EXPECT_EQ(1u, expect_ct_reporter.num_failures());
  5571. }
  5572. // Tests that Expect CT HTTP headers are processed correctly.
  5573. TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
  5574. base::test::ScopedFeatureList feature_list;
  5575. feature_list.InitAndEnableFeature(
  5576. TransportSecurityState::kDynamicExpectCTFeature);
  5577. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5578. https_test_server.SetSSLConfig(
  5579. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5580. https_test_server.ServeFilesFromSourceDirectory(
  5581. base::FilePath(kTestFilePath));
  5582. ASSERT_TRUE(https_test_server.Start());
  5583. // Set up a MockCertVerifier to accept the certificate that the server sends.
  5584. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5585. ASSERT_TRUE(cert);
  5586. CertVerifyResult verify_result;
  5587. verify_result.verified_cert = cert;
  5588. verify_result.is_issued_by_known_root = true;
  5589. auto cert_verifier = std::make_unique<MockCertVerifier>();
  5590. cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5591. // Set up a MockCTPolicyEnforcer to simulate CT compliance.
  5592. auto ct_policy_enforcer = std::make_unique<MockCTPolicyEnforcer>();
  5593. ct_policy_enforcer->set_default_result(
  5594. ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
  5595. auto context_builder = CreateTestURLRequestContextBuilder();
  5596. context_builder->SetCertVerifier(std::move(cert_verifier));
  5597. context_builder->set_ct_policy_enforcer(std::move(ct_policy_enforcer));
  5598. auto context = context_builder->Build();
  5599. MockExpectCTReporter expect_ct_reporter;
  5600. context->transport_security_state()->SetExpectCTReporter(&expect_ct_reporter);
  5601. // Now send a request to trigger the header processing.
  5602. TestDelegate d;
  5603. GURL url = https_test_server.GetURL("/expect-ct-header.html");
  5604. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5605. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5606. request->Start();
  5607. d.RunUntilComplete();
  5608. TransportSecurityState::ExpectCTState state;
  5609. ASSERT_TRUE(context->transport_security_state()->GetDynamicExpectCTState(
  5610. url.host(), NetworkIsolationKey(), &state));
  5611. EXPECT_TRUE(state.enforce);
  5612. EXPECT_EQ(GURL("https://example.test"), state.report_uri);
  5613. }
  5614. // Tests that if multiple Expect CT HTTP headers are sent, they are all
  5615. // processed.
  5616. TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
  5617. base::test::ScopedFeatureList feature_list;
  5618. feature_list.InitAndEnableFeature(
  5619. TransportSecurityState::kDynamicExpectCTFeature);
  5620. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5621. https_test_server.SetSSLConfig(
  5622. net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
  5623. https_test_server.ServeFilesFromSourceDirectory(
  5624. base::FilePath(kTestFilePath));
  5625. ASSERT_TRUE(https_test_server.Start());
  5626. // Set up a MockCertVerifier to accept the certificate that the server sends.
  5627. scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
  5628. ASSERT_TRUE(cert);
  5629. CertVerifyResult verify_result;
  5630. verify_result.verified_cert = cert;
  5631. verify_result.is_issued_by_known_root = true;
  5632. auto cert_verifier = std::make_unique<MockCertVerifier>();
  5633. cert_verifier->AddResultForCert(cert.get(), verify_result, OK);
  5634. // Set up a MockCTPolicyEnforcer to simulate CT compliance.
  5635. DoNothingCTVerifier ct_verifier;
  5636. auto ct_policy_enforcer = std::make_unique<MockCTPolicyEnforcer>();
  5637. ct_policy_enforcer->set_default_result(
  5638. ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
  5639. auto context_builder = CreateTestURLRequestContextBuilder();
  5640. context_builder->SetCertVerifier(std::move(cert_verifier));
  5641. context_builder->set_ct_policy_enforcer(std::move(ct_policy_enforcer));
  5642. auto context = context_builder->Build();
  5643. MockExpectCTReporter expect_ct_reporter;
  5644. context->transport_security_state()->SetExpectCTReporter(&expect_ct_reporter);
  5645. // Now send a request to trigger the header processing.
  5646. TestDelegate d;
  5647. GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
  5648. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5649. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5650. request->Start();
  5651. d.RunUntilComplete();
  5652. TransportSecurityState::ExpectCTState state;
  5653. ASSERT_TRUE(context->transport_security_state()->GetDynamicExpectCTState(
  5654. url.host(), NetworkIsolationKey(), &state));
  5655. EXPECT_TRUE(state.enforce);
  5656. EXPECT_EQ(GURL("https://example.test"), state.report_uri);
  5657. }
  5658. #endif // !BUILDFLAG(IS_IOS)
  5659. #if BUILDFLAG(ENABLE_REPORTING)
  5660. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_DontReportIfNetworkNotAccessed) {
  5661. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5662. RegisterDefaultHandlers(&https_test_server);
  5663. ASSERT_TRUE(https_test_server.Start());
  5664. GURL request_url = https_test_server.GetURL("/cachetime");
  5665. auto context_builder = CreateTestURLRequestContextBuilder();
  5666. context_builder->set_network_error_logging_enabled(true);
  5667. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5668. std::make_unique<TestNetworkErrorLoggingService>());
  5669. auto context = context_builder->Build();
  5670. // Populate the cache.
  5671. TestDelegate d;
  5672. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5673. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5674. request->set_isolation_info(isolation_info1_);
  5675. request->Start();
  5676. d.RunUntilComplete();
  5677. ASSERT_EQ(1u, nel_service.errors().size());
  5678. const TestNetworkErrorLoggingService::RequestDetails& error =
  5679. nel_service.errors()[0];
  5680. EXPECT_EQ(request_url, error.uri);
  5681. EXPECT_EQ(200, error.status_code);
  5682. EXPECT_EQ(OK, error.type);
  5683. request = context->CreateRequest(request_url, DEFAULT_PRIORITY, &d,
  5684. TRAFFIC_ANNOTATION_FOR_TESTS);
  5685. request->set_isolation_info(isolation_info1_);
  5686. request->Start();
  5687. d.RunUntilComplete();
  5688. EXPECT_FALSE(request->response_info().network_accessed);
  5689. EXPECT_TRUE(request->response_info().was_cached);
  5690. // No additional NEL report was generated.
  5691. EXPECT_EQ(1u, nel_service.errors().size());
  5692. }
  5693. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicSuccess) {
  5694. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5695. https_test_server.ServeFilesFromSourceDirectory(
  5696. base::FilePath(kTestFilePath));
  5697. ASSERT_TRUE(https_test_server.Start());
  5698. GURL request_url = https_test_server.GetURL("/simple.html");
  5699. auto context_builder = CreateTestURLRequestContextBuilder();
  5700. context_builder->set_network_error_logging_enabled(true);
  5701. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5702. std::make_unique<TestNetworkErrorLoggingService>());
  5703. auto context = context_builder->Build();
  5704. TestDelegate d;
  5705. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5706. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5707. request->Start();
  5708. d.RunUntilComplete();
  5709. ASSERT_EQ(1u, nel_service.errors().size());
  5710. const TestNetworkErrorLoggingService::RequestDetails& error =
  5711. nel_service.errors()[0];
  5712. EXPECT_EQ(request_url, error.uri);
  5713. EXPECT_EQ(200, error.status_code);
  5714. EXPECT_EQ(OK, error.type);
  5715. }
  5716. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_BasicError) {
  5717. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5718. RegisterDefaultHandlers(&https_test_server);
  5719. ASSERT_TRUE(https_test_server.Start());
  5720. GURL request_url = https_test_server.GetURL("/close-socket");
  5721. auto context_builder = CreateTestURLRequestContextBuilder();
  5722. context_builder->set_network_error_logging_enabled(true);
  5723. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5724. std::make_unique<TestNetworkErrorLoggingService>());
  5725. auto context = context_builder->Build();
  5726. TestDelegate d;
  5727. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5728. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5729. request->Start();
  5730. d.RunUntilComplete();
  5731. ASSERT_EQ(1u, nel_service.errors().size());
  5732. const TestNetworkErrorLoggingService::RequestDetails& error =
  5733. nel_service.errors()[0];
  5734. EXPECT_EQ(request_url, error.uri);
  5735. EXPECT_EQ(0, error.status_code);
  5736. EXPECT_EQ(ERR_EMPTY_RESPONSE, error.type);
  5737. }
  5738. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Redirect) {
  5739. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5740. https_test_server.ServeFilesFromSourceDirectory(
  5741. base::FilePath(kTestFilePath));
  5742. ASSERT_TRUE(https_test_server.Start());
  5743. GURL request_url = https_test_server.GetURL("/redirect-test.html");
  5744. GURL redirect_url = https_test_server.GetURL("/with-headers.html");
  5745. auto context_builder = CreateTestURLRequestContextBuilder();
  5746. context_builder->set_network_error_logging_enabled(true);
  5747. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5748. std::make_unique<TestNetworkErrorLoggingService>());
  5749. auto context = context_builder->Build();
  5750. TestDelegate d;
  5751. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5752. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5753. request->Start();
  5754. d.RunUntilComplete();
  5755. ASSERT_EQ(2u, nel_service.errors().size());
  5756. const TestNetworkErrorLoggingService::RequestDetails& error1 =
  5757. nel_service.errors()[0];
  5758. EXPECT_EQ(request_url, error1.uri);
  5759. EXPECT_EQ(302, error1.status_code);
  5760. EXPECT_EQ(OK, error1.type);
  5761. const TestNetworkErrorLoggingService::RequestDetails& error2 =
  5762. nel_service.errors()[1];
  5763. EXPECT_EQ(redirect_url, error2.uri);
  5764. EXPECT_EQ(200, error2.status_code);
  5765. EXPECT_EQ(OK, error2.type);
  5766. }
  5767. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_RedirectWithoutLocationHeader) {
  5768. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5769. https_test_server.ServeFilesFromSourceDirectory(
  5770. base::FilePath(kTestFilePath));
  5771. ASSERT_TRUE(https_test_server.Start());
  5772. GURL request_url = https_test_server.GetURL("/308-without-location-header");
  5773. auto context_builder = CreateTestURLRequestContextBuilder();
  5774. context_builder->set_network_error_logging_enabled(true);
  5775. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5776. std::make_unique<TestNetworkErrorLoggingService>());
  5777. auto context = context_builder->Build();
  5778. TestDelegate d;
  5779. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5780. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5781. request->Start();
  5782. d.RunUntilComplete();
  5783. ASSERT_EQ(1u, nel_service.errors().size());
  5784. const TestNetworkErrorLoggingService::RequestDetails& error =
  5785. nel_service.errors()[0];
  5786. EXPECT_EQ(request_url, error.uri);
  5787. EXPECT_EQ(308, error.status_code);
  5788. // The body of the response was successfully read.
  5789. EXPECT_EQ(OK, error.type);
  5790. }
  5791. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_Auth) {
  5792. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5793. RegisterDefaultHandlers(&https_test_server);
  5794. ASSERT_TRUE(https_test_server.Start());
  5795. GURL request_url = https_test_server.GetURL("/auth-basic");
  5796. auto context_builder = CreateTestURLRequestContextBuilder();
  5797. context_builder->set_network_error_logging_enabled(true);
  5798. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5799. std::make_unique<TestNetworkErrorLoggingService>());
  5800. auto context = context_builder->Build();
  5801. TestDelegate d;
  5802. d.set_credentials(AuthCredentials(kUser, kSecret));
  5803. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5804. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5805. request->Start();
  5806. d.RunUntilComplete();
  5807. ASSERT_EQ(2u, nel_service.errors().size());
  5808. const TestNetworkErrorLoggingService::RequestDetails& error1 =
  5809. nel_service.errors()[0];
  5810. EXPECT_EQ(request_url, error1.uri);
  5811. EXPECT_EQ(401, error1.status_code);
  5812. EXPECT_EQ(OK, error1.type);
  5813. const TestNetworkErrorLoggingService::RequestDetails& error2 =
  5814. nel_service.errors()[1];
  5815. EXPECT_EQ(request_url, error2.uri);
  5816. EXPECT_EQ(200, error2.status_code);
  5817. EXPECT_EQ(OK, error2.type);
  5818. }
  5819. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_304Response) {
  5820. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5821. RegisterDefaultHandlers(&https_test_server);
  5822. ASSERT_TRUE(https_test_server.Start());
  5823. GURL request_url = https_test_server.GetURL("/auth-basic");
  5824. auto context_builder = CreateTestURLRequestContextBuilder();
  5825. context_builder->set_network_error_logging_enabled(true);
  5826. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5827. std::make_unique<TestNetworkErrorLoggingService>());
  5828. auto context = context_builder->Build();
  5829. // populate the cache
  5830. {
  5831. TestDelegate d;
  5832. d.set_credentials(AuthCredentials(kUser, kSecret));
  5833. std::unique_ptr<URLRequest> r(context->CreateRequest(
  5834. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5835. r->set_isolation_info(isolation_info1_);
  5836. r->Start();
  5837. d.RunUntilComplete();
  5838. }
  5839. ASSERT_EQ(2u, nel_service.errors().size());
  5840. const TestNetworkErrorLoggingService::RequestDetails& error1 =
  5841. nel_service.errors()[0];
  5842. EXPECT_EQ(request_url, error1.uri);
  5843. EXPECT_EQ(401, error1.status_code);
  5844. EXPECT_EQ(OK, error1.type);
  5845. const TestNetworkErrorLoggingService::RequestDetails& error2 =
  5846. nel_service.errors()[1];
  5847. EXPECT_EQ(request_url, error2.uri);
  5848. EXPECT_EQ(200, error2.status_code);
  5849. EXPECT_EQ(OK, error2.type);
  5850. // repeat request with end-to-end validation. since auth-basic results in a
  5851. // cachable page, we expect this test to result in a 304. in which case, the
  5852. // response should be fetched from the cache.
  5853. {
  5854. TestDelegate d;
  5855. d.set_credentials(AuthCredentials(kUser, kSecret));
  5856. std::unique_ptr<URLRequest> r(context->CreateRequest(
  5857. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5858. r->SetLoadFlags(LOAD_VALIDATE_CACHE);
  5859. r->set_isolation_info(isolation_info1_);
  5860. r->Start();
  5861. d.RunUntilComplete();
  5862. // Should be the same cached document.
  5863. EXPECT_TRUE(r->was_cached());
  5864. }
  5865. ASSERT_EQ(3u, nel_service.errors().size());
  5866. const TestNetworkErrorLoggingService::RequestDetails& error3 =
  5867. nel_service.errors()[2];
  5868. EXPECT_EQ(request_url, error3.uri);
  5869. EXPECT_EQ(304, error3.status_code);
  5870. EXPECT_EQ(OK, error3.type);
  5871. }
  5872. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelInResponseStarted) {
  5873. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5874. https_test_server.ServeFilesFromSourceDirectory(
  5875. base::FilePath(kTestFilePath));
  5876. ASSERT_TRUE(https_test_server.Start());
  5877. GURL request_url = https_test_server.GetURL("/simple.html");
  5878. auto context_builder = CreateTestURLRequestContextBuilder();
  5879. context_builder->set_network_error_logging_enabled(true);
  5880. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5881. std::make_unique<TestNetworkErrorLoggingService>());
  5882. auto context = context_builder->Build();
  5883. TestDelegate d;
  5884. d.set_cancel_in_response_started(true);
  5885. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5886. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5887. request->Start();
  5888. d.RunUntilComplete();
  5889. ASSERT_EQ(1u, nel_service.errors().size());
  5890. const TestNetworkErrorLoggingService::RequestDetails& error =
  5891. nel_service.errors()[0];
  5892. EXPECT_EQ(request_url, error.uri);
  5893. EXPECT_EQ(200, error.status_code);
  5894. // Headers were received and the body should have been read but was not.
  5895. EXPECT_EQ(ERR_ABORTED, error.type);
  5896. }
  5897. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelOnDataReceived) {
  5898. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5899. https_test_server.ServeFilesFromSourceDirectory(
  5900. base::FilePath(kTestFilePath));
  5901. ASSERT_TRUE(https_test_server.Start());
  5902. GURL request_url = https_test_server.GetURL("/simple.html");
  5903. auto context_builder = CreateTestURLRequestContextBuilder();
  5904. context_builder->set_network_error_logging_enabled(true);
  5905. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5906. std::make_unique<TestNetworkErrorLoggingService>());
  5907. auto context = context_builder->Build();
  5908. TestDelegate d;
  5909. d.set_cancel_in_received_data(true);
  5910. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5911. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5912. request->Start();
  5913. d.RunUntilComplete();
  5914. ASSERT_EQ(1u, nel_service.errors().size());
  5915. const TestNetworkErrorLoggingService::RequestDetails& error =
  5916. nel_service.errors()[0];
  5917. EXPECT_EQ(request_url, error.uri);
  5918. EXPECT_EQ(200, error.status_code);
  5919. // Data was received but the body was not completely read.
  5920. EXPECT_EQ(ERR_ABORTED, error.type);
  5921. }
  5922. TEST_F(URLRequestTestHTTP, NetworkErrorLogging_CancelRedirect) {
  5923. EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  5924. https_test_server.ServeFilesFromSourceDirectory(
  5925. base::FilePath(kTestFilePath));
  5926. ASSERT_TRUE(https_test_server.Start());
  5927. GURL request_url = https_test_server.GetURL("/redirect-test.html");
  5928. auto context_builder = CreateTestURLRequestContextBuilder();
  5929. context_builder->set_network_error_logging_enabled(true);
  5930. auto& nel_service = *context_builder->SetNetworkErrorLoggingServiceForTesting(
  5931. std::make_unique<TestNetworkErrorLoggingService>());
  5932. auto context = context_builder->Build();
  5933. TestDelegate d;
  5934. d.set_cancel_in_received_redirect(true);
  5935. std::unique_ptr<URLRequest> request(context->CreateRequest(
  5936. request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5937. request->Start();
  5938. d.RunUntilComplete();
  5939. ASSERT_EQ(1u, nel_service.errors().size());
  5940. const TestNetworkErrorLoggingService::RequestDetails& error =
  5941. nel_service.errors()[0];
  5942. EXPECT_EQ(request_url, error.uri);
  5943. EXPECT_EQ(302, error.status_code);
  5944. // A valid HTTP response was received, even though the request was cancelled.
  5945. EXPECT_EQ(OK, error.type);
  5946. }
  5947. #endif // BUILDFLAG(ENABLE_REPORTING)
  5948. TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
  5949. ASSERT_TRUE(http_test_server()->Start());
  5950. TestDelegate d;
  5951. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  5952. http_test_server()->GetURL("/content-type-normalization.html"),
  5953. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5954. req->Start();
  5955. d.RunUntilComplete();
  5956. std::string mime_type;
  5957. req->GetMimeType(&mime_type);
  5958. EXPECT_EQ("text/html", mime_type);
  5959. std::string charset;
  5960. req->GetCharset(&charset);
  5961. EXPECT_EQ("utf-8", charset);
  5962. req->Cancel();
  5963. }
  5964. TEST_F(URLRequestTestHTTP, FileRedirect) {
  5965. ASSERT_TRUE(http_test_server()->Start());
  5966. TestDelegate d;
  5967. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  5968. http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
  5969. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5970. req->Start();
  5971. d.RunUntilComplete();
  5972. EXPECT_EQ(ERR_UNKNOWN_URL_SCHEME, d.request_status());
  5973. EXPECT_EQ(1, d.received_redirect_count());
  5974. }
  5975. TEST_F(URLRequestTestHTTP, DataRedirect) {
  5976. ASSERT_TRUE(http_test_server()->Start());
  5977. TestDelegate d;
  5978. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  5979. http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
  5980. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5981. req->Start();
  5982. d.RunUntilComplete();
  5983. EXPECT_EQ(ERR_UNKNOWN_URL_SCHEME, d.request_status());
  5984. EXPECT_EQ(1, d.received_redirect_count());
  5985. }
  5986. TEST_F(URLRequestTestHTTP, RestrictUnsafeRedirect) {
  5987. ASSERT_TRUE(http_test_server()->Start());
  5988. TestDelegate d;
  5989. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  5990. http_test_server()->GetURL(
  5991. "/server-redirect?unsafe://here-there-be-dragons"),
  5992. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  5993. req->Start();
  5994. d.RunUntilComplete();
  5995. EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
  5996. // The redirect should have been rejected before reporting it to the
  5997. // caller. See https://crbug.com/723796
  5998. EXPECT_EQ(0, d.received_redirect_count());
  5999. }
  6000. // Test that redirects to invalid URLs are rejected. See
  6001. // https://crbug.com/462272.
  6002. TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
  6003. ASSERT_TRUE(http_test_server()->Start());
  6004. TestDelegate d;
  6005. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6006. http_test_server()->GetURL("/redirect-to-invalid-url.html"),
  6007. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6008. req->Start();
  6009. d.RunUntilComplete();
  6010. EXPECT_EQ(1, d.response_started_count());
  6011. EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
  6012. // The redirect should have been rejected before reporting it to the caller.
  6013. EXPECT_EQ(0, d.received_redirect_count());
  6014. }
  6015. // Make sure redirects are cached, despite not reading their bodies.
  6016. TEST_F(URLRequestTestHTTP, CacheRedirect) {
  6017. ASSERT_TRUE(http_test_server()->Start());
  6018. GURL redirect_url =
  6019. http_test_server()->GetURL("/redirect302-to-echo-cacheable");
  6020. {
  6021. TestDelegate d;
  6022. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6023. redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6024. req->set_isolation_info(isolation_info1_);
  6025. req->Start();
  6026. d.RunUntilComplete();
  6027. EXPECT_EQ(OK, d.request_status());
  6028. EXPECT_EQ(1, d.received_redirect_count());
  6029. EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
  6030. }
  6031. {
  6032. TestDelegate d;
  6033. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6034. redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6035. req->set_isolation_info(isolation_info1_);
  6036. req->Start();
  6037. d.RunUntilRedirect();
  6038. EXPECT_EQ(1, d.received_redirect_count());
  6039. EXPECT_EQ(0, d.response_started_count());
  6040. EXPECT_TRUE(req->was_cached());
  6041. req->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  6042. absl::nullopt /* modified_headers */);
  6043. d.RunUntilComplete();
  6044. EXPECT_EQ(1, d.received_redirect_count());
  6045. EXPECT_EQ(1, d.response_started_count());
  6046. EXPECT_EQ(OK, d.request_status());
  6047. EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
  6048. }
  6049. }
  6050. // Make sure a request isn't cached when a NetworkDelegate forces a redirect
  6051. // when the headers are read, since the body won't have been read.
  6052. TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
  6053. ASSERT_TRUE(http_test_server()->Start());
  6054. // URL that is normally cached.
  6055. GURL initial_url = http_test_server()->GetURL("/cachetime");
  6056. {
  6057. // Set up the TestNetworkDelegate tp force a redirect.
  6058. GURL redirect_to_url = http_test_server()->GetURL("/echo");
  6059. default_network_delegate().set_redirect_on_headers_received_url(
  6060. redirect_to_url);
  6061. TestDelegate d;
  6062. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6063. initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6064. req->Start();
  6065. d.RunUntilComplete();
  6066. EXPECT_EQ(OK, d.request_status());
  6067. EXPECT_EQ(1, d.received_redirect_count());
  6068. EXPECT_EQ(redirect_to_url, req->url());
  6069. }
  6070. {
  6071. TestDelegate d;
  6072. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6073. initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6074. req->Start();
  6075. d.RunUntilComplete();
  6076. EXPECT_EQ(OK, d.request_status());
  6077. EXPECT_FALSE(req->was_cached());
  6078. EXPECT_EQ(0, d.received_redirect_count());
  6079. EXPECT_EQ(initial_url, req->url());
  6080. }
  6081. }
  6082. // Check that |preserve_fragment_on_redirect_url| is respected.
  6083. TEST_F(URLRequestTestHTTP, PreserveFragmentOnRedirectUrl) {
  6084. ASSERT_TRUE(http_test_server()->Start());
  6085. GURL original_url(http_test_server()->GetURL("/original#fragment1"));
  6086. GURL preserve_fragement_url(http_test_server()->GetURL("/echo"));
  6087. default_network_delegate().set_redirect_on_headers_received_url(
  6088. preserve_fragement_url);
  6089. default_network_delegate().set_preserve_fragment_on_redirect_url(
  6090. preserve_fragement_url);
  6091. TestDelegate d;
  6092. {
  6093. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6094. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6095. r->Start();
  6096. d.RunUntilComplete();
  6097. EXPECT_EQ(2U, r->url_chain().size());
  6098. EXPECT_EQ(OK, d.request_status());
  6099. EXPECT_EQ(original_url, r->original_url());
  6100. EXPECT_EQ(preserve_fragement_url, r->url());
  6101. }
  6102. }
  6103. // Check that |preserve_fragment_on_redirect_url| has no effect when it doesn't
  6104. // match the URL being redirected to.
  6105. TEST_F(URLRequestTestHTTP, PreserveFragmentOnRedirectUrlMismatch) {
  6106. ASSERT_TRUE(http_test_server()->Start());
  6107. GURL original_url(http_test_server()->GetURL("/original#fragment1"));
  6108. GURL preserve_fragement_url(http_test_server()->GetURL("/echo#fragment2"));
  6109. GURL redirect_url(http_test_server()->GetURL("/echo"));
  6110. GURL expected_url(http_test_server()->GetURL("/echo#fragment1"));
  6111. default_network_delegate().set_redirect_on_headers_received_url(redirect_url);
  6112. default_network_delegate().set_preserve_fragment_on_redirect_url(
  6113. preserve_fragement_url);
  6114. TestDelegate d;
  6115. {
  6116. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6117. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6118. r->Start();
  6119. d.RunUntilComplete();
  6120. EXPECT_EQ(2U, r->url_chain().size());
  6121. EXPECT_EQ(OK, d.request_status());
  6122. EXPECT_EQ(original_url, r->original_url());
  6123. EXPECT_EQ(expected_url, r->url());
  6124. }
  6125. }
  6126. // When a URLRequestRedirectJob is created, the redirection must be followed and
  6127. // the reference fragment of the target URL must not be modified.
  6128. TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
  6129. ASSERT_TRUE(http_test_server()->Start());
  6130. GURL original_url(
  6131. http_test_server()->GetURL("/original#should-not-be-appended"));
  6132. GURL redirect_url(http_test_server()->GetURL("/echo"));
  6133. TestDelegate d;
  6134. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6135. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6136. std::unique_ptr<URLRequestRedirectJob> job =
  6137. std::make_unique<URLRequestRedirectJob>(
  6138. r.get(), redirect_url, RedirectUtil::ResponseCode::REDIRECT_302_FOUND,
  6139. "Very Good Reason");
  6140. TestScopedURLInterceptor interceptor(r->url(), std::move(job));
  6141. r->Start();
  6142. d.RunUntilComplete();
  6143. EXPECT_EQ(OK, d.request_status());
  6144. EXPECT_EQ(original_url, r->original_url());
  6145. EXPECT_EQ(redirect_url, r->url());
  6146. }
  6147. TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
  6148. ASSERT_TRUE(http_test_server()->Start());
  6149. const std::string referrer("foobar://totally.legit.referrer");
  6150. TestDelegate d;
  6151. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6152. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6153. TRAFFIC_ANNOTATION_FOR_TESTS));
  6154. req->SetReferrer(referrer);
  6155. req->Start();
  6156. d.RunUntilComplete();
  6157. EXPECT_EQ(std::string("None"), d.data_received());
  6158. }
  6159. TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
  6160. ASSERT_TRUE(http_test_server()->Start());
  6161. TestDelegate d;
  6162. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6163. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6164. TRAFFIC_ANNOTATION_FOR_TESTS));
  6165. req->SetReferrer("http://user:pass@foo.com/");
  6166. req->Start();
  6167. d.RunUntilComplete();
  6168. EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
  6169. }
  6170. TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
  6171. ASSERT_TRUE(http_test_server()->Start());
  6172. TestDelegate d;
  6173. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6174. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6175. TRAFFIC_ANNOTATION_FOR_TESTS));
  6176. req->SetReferrer("http://foo.com/test#fragment");
  6177. req->Start();
  6178. d.RunUntilComplete();
  6179. EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
  6180. }
  6181. TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
  6182. ASSERT_TRUE(http_test_server()->Start());
  6183. TestDelegate d;
  6184. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6185. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6186. TRAFFIC_ANNOTATION_FOR_TESTS));
  6187. req->SetReferrer("http://foo.com/test#fragment");
  6188. req->SetReferrer("");
  6189. req->Start();
  6190. d.RunUntilComplete();
  6191. EXPECT_EQ(std::string("None"), d.data_received());
  6192. }
  6193. TEST_F(URLRequestTestHTTP, CapRefererHeaderLength) {
  6194. ASSERT_TRUE(http_test_server()->Start());
  6195. // Verify that referrers over 4k are stripped to an origin, and referrers at
  6196. // or under 4k are unmodified.
  6197. {
  6198. std::string original_header = "http://example.com/";
  6199. original_header.resize(4097, 'a');
  6200. TestDelegate d;
  6201. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6202. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6203. TRAFFIC_ANNOTATION_FOR_TESTS));
  6204. req->SetReferrer(original_header);
  6205. req->Start();
  6206. d.RunUntilComplete();
  6207. // The request's referrer will be stripped since (1) there will be a
  6208. // mismatch between the request's referrer and the output of
  6209. // URLRequestJob::ComputeReferrerForPolicy and (2) the delegate, when
  6210. // offered the opportunity to cancel the request for this reason, will
  6211. // decline.
  6212. EXPECT_EQ("None", d.data_received());
  6213. }
  6214. {
  6215. std::string original_header = "http://example.com/";
  6216. original_header.resize(4096, 'a');
  6217. TestDelegate d;
  6218. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6219. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6220. TRAFFIC_ANNOTATION_FOR_TESTS));
  6221. req->SetReferrer(original_header);
  6222. req->Start();
  6223. d.RunUntilComplete();
  6224. EXPECT_EQ(original_header, d.data_received());
  6225. }
  6226. {
  6227. std::string original_header = "http://example.com/";
  6228. original_header.resize(4095, 'a');
  6229. TestDelegate d;
  6230. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6231. http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
  6232. TRAFFIC_ANNOTATION_FOR_TESTS));
  6233. req->SetReferrer(original_header);
  6234. req->Start();
  6235. d.RunUntilComplete();
  6236. EXPECT_EQ(original_header, d.data_received());
  6237. }
  6238. }
  6239. TEST_F(URLRequestTestHTTP, CancelRedirect) {
  6240. ASSERT_TRUE(http_test_server()->Start());
  6241. TestDelegate d;
  6242. {
  6243. d.set_cancel_in_received_redirect(true);
  6244. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6245. http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
  6246. TRAFFIC_ANNOTATION_FOR_TESTS));
  6247. req->Start();
  6248. d.RunUntilComplete();
  6249. EXPECT_EQ(1, d.response_started_count());
  6250. EXPECT_EQ(0, d.bytes_received());
  6251. EXPECT_FALSE(d.received_data_before_response());
  6252. EXPECT_EQ(ERR_ABORTED, d.request_status());
  6253. }
  6254. }
  6255. TEST_F(URLRequestTestHTTP, DeferredRedirect) {
  6256. ASSERT_TRUE(http_test_server()->Start());
  6257. TestDelegate d;
  6258. {
  6259. GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
  6260. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6261. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6262. req->Start();
  6263. d.RunUntilRedirect();
  6264. EXPECT_EQ(1, d.received_redirect_count());
  6265. req->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  6266. absl::nullopt /* modified_headers */);
  6267. d.RunUntilComplete();
  6268. EXPECT_EQ(1, d.response_started_count());
  6269. EXPECT_FALSE(d.received_data_before_response());
  6270. EXPECT_EQ(OK, d.request_status());
  6271. base::FilePath path;
  6272. base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
  6273. path = path.Append(kTestFilePath);
  6274. path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
  6275. std::string contents;
  6276. EXPECT_TRUE(base::ReadFileToString(path, &contents));
  6277. EXPECT_EQ(contents, d.data_received());
  6278. }
  6279. }
  6280. TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedHeaders) {
  6281. test_server::HttpRequest http_request;
  6282. int num_observed_requests = 0;
  6283. http_test_server()->RegisterRequestMonitor(
  6284. base::BindLambdaForTesting([&](const test_server::HttpRequest& request) {
  6285. http_request = request;
  6286. ++num_observed_requests;
  6287. }));
  6288. ASSERT_TRUE(http_test_server()->Start());
  6289. TestDelegate d;
  6290. {
  6291. GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
  6292. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6293. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6294. // Set initial headers for the request.
  6295. req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
  6296. req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
  6297. req->Start();
  6298. d.RunUntilRedirect();
  6299. // Initial request should only have initial headers.
  6300. EXPECT_EQ(1, d.received_redirect_count());
  6301. EXPECT_EQ(1, num_observed_requests);
  6302. EXPECT_EQ("Value1", http_request.headers["Header1"]);
  6303. EXPECT_EQ("Value2", http_request.headers["Header2"]);
  6304. EXPECT_EQ(0u, http_request.headers.count("Header3"));
  6305. // Overwrite Header2 and add Header3.
  6306. net::HttpRequestHeaders modified_headers;
  6307. modified_headers.SetHeader("Header2", "");
  6308. modified_headers.SetHeader("Header3", "Value3");
  6309. req->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  6310. modified_headers);
  6311. d.RunUntilComplete();
  6312. EXPECT_EQ(1, d.response_started_count());
  6313. EXPECT_FALSE(d.received_data_before_response());
  6314. EXPECT_EQ(OK, d.request_status());
  6315. // Redirected request should also have modified headers.
  6316. EXPECT_EQ(2, num_observed_requests);
  6317. EXPECT_EQ("Value1", http_request.headers["Header1"]);
  6318. EXPECT_EQ(1u, http_request.headers.count("Header2"));
  6319. EXPECT_EQ("", http_request.headers["Header2"]);
  6320. EXPECT_EQ("Value3", http_request.headers["Header3"]);
  6321. }
  6322. }
  6323. TEST_F(URLRequestTestHTTP, DeferredRedirect_RemovedHeaders) {
  6324. test_server::HttpRequest http_request;
  6325. int num_observed_requests = 0;
  6326. http_test_server()->RegisterRequestMonitor(
  6327. base::BindLambdaForTesting([&](const test_server::HttpRequest& request) {
  6328. http_request = request;
  6329. ++num_observed_requests;
  6330. }));
  6331. ASSERT_TRUE(http_test_server()->Start());
  6332. TestDelegate d;
  6333. {
  6334. GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
  6335. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6336. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6337. // Set initial headers for the request.
  6338. req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
  6339. req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
  6340. req->Start();
  6341. d.RunUntilRedirect();
  6342. // Initial request should have initial headers.
  6343. EXPECT_EQ(1, d.received_redirect_count());
  6344. EXPECT_EQ(1, num_observed_requests);
  6345. EXPECT_EQ("Value1", http_request.headers["Header1"]);
  6346. EXPECT_EQ("Value2", http_request.headers["Header2"]);
  6347. // Keep Header1 and remove Header2.
  6348. std::vector<std::string> removed_headers({"Header2"});
  6349. req->FollowDeferredRedirect(removed_headers,
  6350. absl::nullopt /* modified_headers */);
  6351. d.RunUntilComplete();
  6352. EXPECT_EQ(1, d.response_started_count());
  6353. EXPECT_FALSE(d.received_data_before_response());
  6354. EXPECT_EQ(OK, d.request_status());
  6355. // Redirected request should have modified headers.
  6356. EXPECT_EQ(2, num_observed_requests);
  6357. EXPECT_EQ("Value1", http_request.headers["Header1"]);
  6358. EXPECT_EQ(0u, http_request.headers.count("Header2"));
  6359. }
  6360. }
  6361. TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
  6362. ASSERT_TRUE(http_test_server()->Start());
  6363. TestDelegate d;
  6364. {
  6365. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6366. http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
  6367. TRAFFIC_ANNOTATION_FOR_TESTS));
  6368. req->Start();
  6369. d.RunUntilRedirect();
  6370. EXPECT_EQ(1, d.received_redirect_count());
  6371. req->Cancel();
  6372. d.RunUntilComplete();
  6373. EXPECT_EQ(1, d.response_started_count());
  6374. EXPECT_EQ(0, d.bytes_received());
  6375. EXPECT_FALSE(d.received_data_before_response());
  6376. EXPECT_EQ(ERR_ABORTED, d.request_status());
  6377. }
  6378. }
  6379. TEST_F(URLRequestTestHTTP, VaryHeader) {
  6380. ASSERT_TRUE(http_test_server()->Start());
  6381. // Populate the cache.
  6382. {
  6383. TestDelegate d;
  6384. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6385. http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
  6386. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6387. HttpRequestHeaders headers;
  6388. headers.SetHeader("foo", "1");
  6389. req->SetExtraRequestHeaders(headers);
  6390. req->set_isolation_info(isolation_info1_);
  6391. req->Start();
  6392. d.RunUntilComplete();
  6393. LoadTimingInfo load_timing_info;
  6394. req->GetLoadTimingInfo(&load_timing_info);
  6395. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  6396. }
  6397. // Expect a cache hit.
  6398. {
  6399. TestDelegate d;
  6400. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6401. http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
  6402. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6403. HttpRequestHeaders headers;
  6404. headers.SetHeader("foo", "1");
  6405. req->SetExtraRequestHeaders(headers);
  6406. req->set_isolation_info(isolation_info1_);
  6407. req->Start();
  6408. d.RunUntilComplete();
  6409. EXPECT_TRUE(req->was_cached());
  6410. LoadTimingInfo load_timing_info;
  6411. req->GetLoadTimingInfo(&load_timing_info);
  6412. TestLoadTimingCacheHitNoNetwork(load_timing_info);
  6413. }
  6414. // Expect a cache miss.
  6415. {
  6416. TestDelegate d;
  6417. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  6418. http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
  6419. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6420. HttpRequestHeaders headers;
  6421. headers.SetHeader("foo", "2");
  6422. req->SetExtraRequestHeaders(headers);
  6423. req->set_isolation_info(isolation_info1_);
  6424. req->Start();
  6425. d.RunUntilComplete();
  6426. EXPECT_FALSE(req->was_cached());
  6427. LoadTimingInfo load_timing_info;
  6428. req->GetLoadTimingInfo(&load_timing_info);
  6429. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  6430. }
  6431. }
  6432. TEST_F(URLRequestTestHTTP, BasicAuth) {
  6433. ASSERT_TRUE(http_test_server()->Start());
  6434. // populate the cache
  6435. {
  6436. TestDelegate d;
  6437. d.set_credentials(AuthCredentials(kUser, kSecret));
  6438. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6439. http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
  6440. TRAFFIC_ANNOTATION_FOR_TESTS));
  6441. r->set_isolation_info(isolation_info1_);
  6442. r->Start();
  6443. d.RunUntilComplete();
  6444. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  6445. }
  6446. // repeat request with end-to-end validation. since auth-basic results in a
  6447. // cachable page, we expect this test to result in a 304. in which case, the
  6448. // response should be fetched from the cache.
  6449. {
  6450. TestDelegate d;
  6451. d.set_credentials(AuthCredentials(kUser, kSecret));
  6452. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6453. http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
  6454. TRAFFIC_ANNOTATION_FOR_TESTS));
  6455. r->SetLoadFlags(LOAD_VALIDATE_CACHE);
  6456. r->set_isolation_info(isolation_info1_);
  6457. r->Start();
  6458. d.RunUntilComplete();
  6459. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  6460. // Should be the same cached document.
  6461. EXPECT_TRUE(r->was_cached());
  6462. }
  6463. }
  6464. // Check that Set-Cookie headers in 401 responses are respected.
  6465. // http://crbug.com/6450
  6466. TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
  6467. ASSERT_TRUE(http_test_server()->Start());
  6468. GURL url_requiring_auth =
  6469. http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
  6470. // Request a page that will give a 401 containing a Set-Cookie header.
  6471. // Verify that when the transaction is restarted, it includes the new cookie.
  6472. TestDelegate d;
  6473. d.set_credentials(AuthCredentials(kUser, kSecret));
  6474. std::unique_ptr<URLRequest> r =
  6475. CreateFirstPartyRequest(default_context(), url_requiring_auth, &d);
  6476. r->Start();
  6477. d.RunUntilComplete();
  6478. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  6479. // Make sure we sent the cookie in the restarted transaction.
  6480. EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true") !=
  6481. std::string::npos);
  6482. }
  6483. // Same test as above, except this time the restart is initiated earlier
  6484. // (without user intervention since identity is embedded in the URL).
  6485. TEST_F(URLRequestTestHTTP, BasicAuthWithCredentialsWithCookies) {
  6486. ASSERT_TRUE(http_test_server()->Start());
  6487. GURL url_requiring_auth =
  6488. http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
  6489. GURL::Replacements replacements;
  6490. replacements.SetUsernameStr("user2");
  6491. replacements.SetPasswordStr("secret");
  6492. GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
  6493. TestDelegate d;
  6494. std::unique_ptr<URLRequest> r =
  6495. CreateFirstPartyRequest(default_context(), url_with_identity, &d);
  6496. r->Start();
  6497. d.RunUntilComplete();
  6498. EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
  6499. // Make sure we sent the cookie in the restarted transaction.
  6500. EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true") !=
  6501. std::string::npos);
  6502. }
  6503. TEST_F(URLRequestTestHTTP, BasicAuthWithCookiesCancelAuth) {
  6504. ASSERT_TRUE(http_test_server()->Start());
  6505. GURL url_requiring_auth =
  6506. http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
  6507. // Request a page that will give a 401 containing a Set-Cookie header.
  6508. // Verify that cookies are set before credentials are provided, and then
  6509. // cancelling auth does not result in setting the cookies again.
  6510. TestDelegate d;
  6511. EXPECT_TRUE(GetAllCookies(&default_context()).empty());
  6512. std::unique_ptr<URLRequest> r =
  6513. CreateFirstPartyRequest(default_context(), url_requiring_auth, &d);
  6514. r->Start();
  6515. d.RunUntilAuthRequired();
  6516. // Cookie should have been set.
  6517. EXPECT_EQ(1, default_network_delegate().set_cookie_count());
  6518. CookieList cookies = GetAllCookies(&default_context());
  6519. ASSERT_EQ(1u, cookies.size());
  6520. EXPECT_EQ("got_challenged", cookies[0].Name());
  6521. EXPECT_EQ("true", cookies[0].Value());
  6522. // Delete cookie.
  6523. default_context().cookie_store()->DeleteAllAsync(
  6524. CookieStore::DeleteCallback());
  6525. // Cancel auth and continue the request.
  6526. r->CancelAuth();
  6527. d.RunUntilComplete();
  6528. ASSERT_TRUE(r->response_headers());
  6529. EXPECT_EQ(401, r->response_headers()->response_code());
  6530. // Cookie should not have been set again.
  6531. EXPECT_TRUE(GetAllCookies(&default_context()).empty());
  6532. EXPECT_EQ(1, default_network_delegate().set_cookie_count());
  6533. }
  6534. // Tests the IsolationInfo is updated approiately on redirect.
  6535. TEST_F(URLRequestTestHTTP, IsolationInfoUpdatedOnRedirect) {
  6536. base::test::ScopedFeatureList feature_list;
  6537. feature_list.InitAndEnableFeature(
  6538. net::features::kSplitCacheByNetworkIsolationKey);
  6539. ASSERT_TRUE(http_test_server()->Start());
  6540. GURL redirect_url =
  6541. http_test_server()->GetURL("redirected.test", "/cachetime");
  6542. GURL original_url = http_test_server()->GetURL(
  6543. "original.test", "/server-redirect?" + redirect_url.spec());
  6544. url::Origin original_origin = url::Origin::Create(original_url);
  6545. url::Origin redirect_origin = url::Origin::Create(redirect_url);
  6546. // Since transient IsolationInfos use opaque origins, need to create a single
  6547. // consistent transient origin one for be used as the original and updated
  6548. // info in the same test case.
  6549. IsolationInfo transient_isolation_info = IsolationInfo::CreateTransient();
  6550. const struct {
  6551. IsolationInfo info_before_redirect;
  6552. IsolationInfo expected_info_after_redirect;
  6553. } kTestCases[] = {
  6554. {IsolationInfo(), IsolationInfo()},
  6555. {IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame,
  6556. original_origin, original_origin,
  6557. SiteForCookies()),
  6558. IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame,
  6559. redirect_origin, redirect_origin,
  6560. SiteForCookies::FromOrigin(redirect_origin))},
  6561. {IsolationInfo::Create(IsolationInfo::RequestType::kSubFrame,
  6562. original_origin, original_origin,
  6563. SiteForCookies::FromOrigin(original_origin)),
  6564. IsolationInfo::Create(IsolationInfo::RequestType::kSubFrame,
  6565. original_origin, redirect_origin,
  6566. SiteForCookies::FromOrigin(original_origin))},
  6567. {IsolationInfo::Create(IsolationInfo::RequestType::kOther,
  6568. original_origin, original_origin,
  6569. SiteForCookies()),
  6570. IsolationInfo::Create(IsolationInfo::RequestType::kOther,
  6571. original_origin, original_origin,
  6572. SiteForCookies())},
  6573. {transient_isolation_info, transient_isolation_info},
  6574. };
  6575. for (const auto& test_case : kTestCases) {
  6576. // Populate the cache, using the expected final IsolationInfo.
  6577. {
  6578. TestDelegate d;
  6579. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6580. redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6581. r->set_isolation_info(test_case.expected_info_after_redirect);
  6582. r->Start();
  6583. d.RunUntilComplete();
  6584. EXPECT_THAT(d.request_status(), IsOk());
  6585. }
  6586. // Send a request using the initial IsolationInfo that should be redirected
  6587. // to the cached url, and should use the cached entry if the NIK was
  6588. // updated, except in the case the IsolationInfo's NIK was empty.
  6589. {
  6590. TestDelegate d;
  6591. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  6592. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6593. r->set_isolation_info(test_case.info_before_redirect);
  6594. r->Start();
  6595. d.RunUntilComplete();
  6596. EXPECT_THAT(d.request_status(), IsOk());
  6597. EXPECT_EQ(redirect_url, r->url());
  6598. EXPECT_EQ(!test_case.expected_info_after_redirect.network_isolation_key()
  6599. .IsTransient(),
  6600. r->was_cached());
  6601. EXPECT_EQ(test_case.expected_info_after_redirect.request_type(),
  6602. r->isolation_info().request_type());
  6603. EXPECT_EQ(test_case.expected_info_after_redirect.top_frame_origin(),
  6604. r->isolation_info().top_frame_origin());
  6605. EXPECT_EQ(test_case.expected_info_after_redirect.frame_origin(),
  6606. r->isolation_info().frame_origin());
  6607. EXPECT_EQ(test_case.expected_info_after_redirect.network_isolation_key(),
  6608. r->isolation_info().network_isolation_key());
  6609. EXPECT_TRUE(test_case.expected_info_after_redirect.site_for_cookies()
  6610. .IsEquivalent(r->isolation_info().site_for_cookies()));
  6611. }
  6612. }
  6613. }
  6614. // Tests that |key_auth_cache_by_network_isolation_key| is respected.
  6615. TEST_F(URLRequestTestHTTP, AuthWithNetworkIsolationKey) {
  6616. ASSERT_TRUE(http_test_server()->Start());
  6617. for (bool key_auth_cache_by_network_isolation_key : {false, true}) {
  6618. auto context_builder = CreateTestURLRequestContextBuilder();
  6619. HttpNetworkSessionParams network_session_params;
  6620. network_session_params
  6621. .key_auth_cache_server_entries_by_network_isolation_key =
  6622. key_auth_cache_by_network_isolation_key;
  6623. context_builder->set_http_network_session_params(network_session_params);
  6624. auto context = context_builder->Build();
  6625. // Populate the auth cache using one NetworkIsolationKey.
  6626. {
  6627. TestDelegate d;
  6628. GURL url(base::StringPrintf(
  6629. "http://%s:%s@%s/auth-basic", base::UTF16ToASCII(kUser).c_str(),
  6630. base::UTF16ToASCII(kSecret).c_str(),
  6631. http_test_server()->host_port_pair().ToString().c_str()));
  6632. std::unique_ptr<URLRequest> r(context->CreateRequest(
  6633. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6634. r->SetLoadFlags(LOAD_BYPASS_CACHE);
  6635. r->set_isolation_info(isolation_info1_);
  6636. r->Start();
  6637. d.RunUntilComplete();
  6638. EXPECT_THAT(d.request_status(), IsOk());
  6639. ASSERT_TRUE(r->response_headers());
  6640. EXPECT_EQ(200, r->response_headers()->response_code());
  6641. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  6642. }
  6643. // Make a request with another NetworkIsolationKey. This may or may not use
  6644. // the cached auth credentials, depending on whether or not the
  6645. // HttpAuthCache is configured to respect the NetworkIsolationKey.
  6646. {
  6647. TestDelegate d;
  6648. std::unique_ptr<URLRequest> r(context->CreateRequest(
  6649. http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
  6650. TRAFFIC_ANNOTATION_FOR_TESTS));
  6651. r->SetLoadFlags(LOAD_BYPASS_CACHE);
  6652. r->set_isolation_info(isolation_info2_);
  6653. r->Start();
  6654. d.RunUntilComplete();
  6655. EXPECT_THAT(d.request_status(), IsOk());
  6656. ASSERT_TRUE(r->response_headers());
  6657. if (key_auth_cache_by_network_isolation_key) {
  6658. EXPECT_EQ(401, r->response_headers()->response_code());
  6659. } else {
  6660. EXPECT_EQ(200, r->response_headers()->response_code());
  6661. }
  6662. EXPECT_EQ(!key_auth_cache_by_network_isolation_key,
  6663. d.data_received().find("user/secret") != std::string::npos);
  6664. }
  6665. }
  6666. }
  6667. TEST_F(URLRequestTest, ReportCookieActivity) {
  6668. HttpTestServer test_server;
  6669. ASSERT_TRUE(test_server.Start());
  6670. RecordingNetLogObserver net_log_observer;
  6671. auto context_builder = CreateTestURLRequestContextBuilder();
  6672. auto& network_delegate = *context_builder->set_network_delegate(
  6673. std::make_unique<FilteringTestNetworkDelegate>());
  6674. network_delegate.SetCookieFilter("not_stored_cookie");
  6675. network_delegate.set_block_annotate_cookies();
  6676. context_builder->set_net_log(net::NetLog::Get());
  6677. auto context = context_builder->Build();
  6678. // Make sure cookies blocked from being stored are caught, and those that are
  6679. // accepted are reported as well.
  6680. GURL set_cookie_test_url = test_server.GetURL(
  6681. "/set-cookie?not_stored_cookie=true&"
  6682. "stored_cookie=tasty"
  6683. "&path_cookie=narrow;path=/set-cookie");
  6684. {
  6685. TestDelegate d;
  6686. std::unique_ptr<URLRequest> req =
  6687. CreateFirstPartyRequest(*context, set_cookie_test_url, &d);
  6688. req->Start();
  6689. d.RunUntilComplete();
  6690. ASSERT_EQ(3u, req->maybe_stored_cookies().size());
  6691. EXPECT_EQ("not_stored_cookie",
  6692. req->maybe_stored_cookies()[0].cookie->Name());
  6693. EXPECT_TRUE(req->maybe_stored_cookies()[0]
  6694. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6695. {CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  6696. EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
  6697. EXPECT_TRUE(
  6698. req->maybe_stored_cookies()[1].access_result.status.IsInclude());
  6699. EXPECT_EQ("stored_cookie", req->maybe_stored_cookies()[1].cookie->Name());
  6700. EXPECT_TRUE(
  6701. req->maybe_stored_cookies()[2].access_result.status.IsInclude());
  6702. EXPECT_EQ("path_cookie", req->maybe_stored_cookies()[2].cookie->Name());
  6703. auto entries = net_log_observer.GetEntriesWithType(
  6704. NetLogEventType::COOKIE_INCLUSION_STATUS);
  6705. EXPECT_EQ(3u, entries.size());
  6706. EXPECT_EQ("{\"domain\":\"" + set_cookie_test_url.host() +
  6707. "\",\"name\":\"not_stored_cookie\",\"operation\":\"store\","
  6708. "\"path\":\"/\",\"status\":\"EXCLUDE_USER_PREFERENCES, "
  6709. "DO_NOT_WARN\"}",
  6710. SerializeNetLogValueToJson(entries[0].params));
  6711. EXPECT_EQ("{\"domain\":\"" + set_cookie_test_url.host() +
  6712. "\",\"name\":\"stored_cookie\",\"operation\":\"store\","
  6713. "\"path\":\"/\",\"status\":\"INCLUDE, DO_NOT_WARN\"}",
  6714. SerializeNetLogValueToJson(entries[1].params));
  6715. EXPECT_EQ(
  6716. "{\"domain\":\"" + set_cookie_test_url.host() +
  6717. "\",\"name\":\"path_cookie\",\"operation\":\"store\","
  6718. "\"path\":\"/set-cookie\",\"status\":\"INCLUDE, DO_NOT_WARN\"}",
  6719. SerializeNetLogValueToJson(entries[2].params));
  6720. net_log_observer.Clear();
  6721. }
  6722. {
  6723. TestDelegate d;
  6724. // Make sure cookies blocked from being sent are caught.
  6725. GURL test_url = test_server.GetURL("/echoheader?Cookie");
  6726. std::unique_ptr<URLRequest> req =
  6727. CreateFirstPartyRequest(*context, test_url, &d);
  6728. req->Start();
  6729. d.RunUntilComplete();
  6730. EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") ==
  6731. std::string::npos);
  6732. ASSERT_EQ(2u, req->maybe_sent_cookies().size());
  6733. EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
  6734. EXPECT_TRUE(
  6735. req->maybe_sent_cookies()[0]
  6736. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6737. {net::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
  6738. net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  6739. EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
  6740. EXPECT_TRUE(
  6741. req->maybe_sent_cookies()[1]
  6742. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6743. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  6744. auto entries = net_log_observer.GetEntriesWithType(
  6745. NetLogEventType::COOKIE_INCLUSION_STATUS);
  6746. EXPECT_EQ(2u, entries.size());
  6747. EXPECT_EQ("{\"domain\":\"" + set_cookie_test_url.host() +
  6748. "\",\"name\":\"path_cookie\",\"operation\":\"send\",\"path\":"
  6749. "\"/set-cookie\",\"status\":\"EXCLUDE_NOT_ON_PATH, "
  6750. "EXCLUDE_USER_PREFERENCES, DO_NOT_WARN\"}",
  6751. SerializeNetLogValueToJson(entries[0].params));
  6752. EXPECT_EQ(
  6753. "{\"domain\":\"" + set_cookie_test_url.host() +
  6754. "\",\"name\":\"stored_cookie\",\"operation\":\"send\",\"path\":\"/"
  6755. "\",\"status\":\"EXCLUDE_USER_PREFERENCES, DO_NOT_WARN\"}",
  6756. SerializeNetLogValueToJson(entries[1].params));
  6757. net_log_observer.Clear();
  6758. }
  6759. {
  6760. TestDelegate d;
  6761. // Ensure that the log does not contain cookie names when not set to collect
  6762. // sensitive data.
  6763. net_log_observer.SetObserverCaptureMode(NetLogCaptureMode::kDefault);
  6764. GURL test_url = test_server.GetURL("/echoheader?Cookie");
  6765. std::unique_ptr<URLRequest> req =
  6766. CreateFirstPartyRequest(*context, test_url, &d);
  6767. req->Start();
  6768. d.RunUntilComplete();
  6769. auto entries = net_log_observer.GetEntriesWithType(
  6770. NetLogEventType::COOKIE_INCLUSION_STATUS);
  6771. EXPECT_EQ(2u, entries.size());
  6772. // Ensure that the potentially-sensitive |name|, |domain|, and |path| fields
  6773. // are omitted, but other fields are logged as expected.
  6774. EXPECT_EQ(
  6775. "{\"operation\":\"send\",\"status\":\"EXCLUDE_NOT_ON_PATH, "
  6776. "EXCLUDE_USER_PREFERENCES, DO_NOT_WARN\"}",
  6777. SerializeNetLogValueToJson(entries[0].params));
  6778. EXPECT_EQ(
  6779. "{\"operation\":\"send\",\"status\":\"EXCLUDE_USER_PREFERENCES, "
  6780. "DO_NOT_WARN\"}",
  6781. SerializeNetLogValueToJson(entries[1].params));
  6782. net_log_observer.Clear();
  6783. net_log_observer.SetObserverCaptureMode(
  6784. NetLogCaptureMode::kIncludeSensitive);
  6785. }
  6786. network_delegate.unset_block_annotate_cookies();
  6787. {
  6788. // Now with sending cookies re-enabled, it should actually be sent.
  6789. TestDelegate d;
  6790. GURL test_url = test_server.GetURL("/echoheader?Cookie");
  6791. std::unique_ptr<URLRequest> req =
  6792. CreateFirstPartyRequest(*context, test_url, &d);
  6793. req->Start();
  6794. d.RunUntilComplete();
  6795. EXPECT_TRUE(d.data_received().find("stored_cookie=tasty") !=
  6796. std::string::npos);
  6797. ASSERT_EQ(2u, req->maybe_sent_cookies().size());
  6798. EXPECT_EQ("path_cookie", req->maybe_sent_cookies()[0].cookie.Name());
  6799. EXPECT_TRUE(req->maybe_sent_cookies()[0]
  6800. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6801. {net::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH}));
  6802. EXPECT_EQ("stored_cookie", req->maybe_sent_cookies()[1].cookie.Name());
  6803. EXPECT_TRUE(req->maybe_sent_cookies()[1].access_result.status.IsInclude());
  6804. auto entries = net_log_observer.GetEntriesWithType(
  6805. NetLogEventType::COOKIE_INCLUSION_STATUS);
  6806. EXPECT_EQ(2u, entries.size());
  6807. EXPECT_EQ(
  6808. "{\"domain\":\"" + set_cookie_test_url.host() +
  6809. "\",\"name\":\"path_cookie\",\"operation\":\"send\",\"path\":\"/"
  6810. "set-cookie\",\"status\":\"EXCLUDE_NOT_ON_PATH, DO_NOT_WARN\"}",
  6811. SerializeNetLogValueToJson(entries[0].params));
  6812. EXPECT_EQ("{\"domain\":\"" + set_cookie_test_url.host() +
  6813. "\",\"name\":\"stored_cookie\",\"operation\":\"send\","
  6814. "\"path\":\"/\",\"status\":\"INCLUDE, DO_NOT_WARN\"}",
  6815. SerializeNetLogValueToJson(entries[1].params));
  6816. net_log_observer.Clear();
  6817. }
  6818. }
  6819. // Test that the SameSite-by-default CookieInclusionStatus warnings do not get
  6820. // set if the cookie would have been rejected for other reasons.
  6821. // Regression test for https://crbug.com/1027318.
  6822. TEST_F(URLRequestTest, NoCookieInclusionStatusWarningIfWouldBeExcludedAnyway) {
  6823. HttpTestServer test_server;
  6824. ASSERT_TRUE(test_server.Start());
  6825. auto context_builder = CreateTestURLRequestContextBuilder();
  6826. auto& network_delegate = *context_builder->set_network_delegate(
  6827. std::make_unique<FilteringTestNetworkDelegate>());
  6828. network_delegate.SetCookieFilter("blockeduserpreference");
  6829. context_builder->SetCookieStore(std::make_unique<CookieMonster>(
  6830. nullptr, nullptr, /*first_party_sets_enabled=*/false));
  6831. auto context = context_builder->Build();
  6832. auto& cm = *static_cast<CookieMonster*>(context->cookie_store());
  6833. // Set cookies
  6834. {
  6835. // Attempt to set some cookies in a cross-site context without a SameSite
  6836. // attribute. They should all be blocked. Only the one that would have been
  6837. // included had it not been for the new SameSite features should have a
  6838. // warning attached.
  6839. TestDelegate d;
  6840. GURL test_url = test_server.GetURL("this.example",
  6841. "/set-cookie?blockeduserpreference=true&"
  6842. "unspecifiedsamesite=1&"
  6843. "invalidsecure=1;Secure");
  6844. GURL cross_site_url = test_server.GetURL("other.example", "/");
  6845. std::unique_ptr<URLRequest> req(context->CreateRequest(
  6846. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6847. req->set_site_for_cookies(
  6848. net::SiteForCookies::FromUrl(cross_site_url)); // cross-site context
  6849. req->Start();
  6850. d.RunUntilComplete();
  6851. ASSERT_EQ(3u, req->maybe_stored_cookies().size());
  6852. // Cookie blocked by user preferences is not warned about.
  6853. EXPECT_EQ("blockeduserpreference",
  6854. req->maybe_stored_cookies()[0].cookie->Name());
  6855. // It doesn't pick up the EXCLUDE_UNSPECIFIED_TREATED_AS_LAX because it
  6856. // doesn't even make it to the cookie store (it is filtered out beforehand).
  6857. EXPECT_TRUE(req->maybe_stored_cookies()[0]
  6858. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6859. {CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  6860. EXPECT_FALSE(
  6861. req->maybe_stored_cookies()[0].access_result.status.ShouldWarn());
  6862. // Cookie that would be included had it not been for the new SameSite rules
  6863. // is warned about.
  6864. EXPECT_EQ("unspecifiedsamesite",
  6865. req->maybe_stored_cookies()[1].cookie->Name());
  6866. EXPECT_TRUE(req->maybe_stored_cookies()[1]
  6867. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6868. {CookieInclusionStatus::
  6869. EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX}));
  6870. EXPECT_TRUE(req->maybe_stored_cookies()[1]
  6871. .access_result.status.HasExactlyWarningReasonsForTesting(
  6872. {CookieInclusionStatus::
  6873. WARN_SAMESITE_UNSPECIFIED_CROSS_SITE_CONTEXT}));
  6874. // Cookie that is blocked because of invalid Secure attribute is not warned
  6875. // about.
  6876. EXPECT_EQ("invalidsecure", req->maybe_stored_cookies()[2].cookie->Name());
  6877. EXPECT_TRUE(req->maybe_stored_cookies()[2]
  6878. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6879. {CookieInclusionStatus::EXCLUDE_SECURE_ONLY,
  6880. CookieInclusionStatus::
  6881. EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX}));
  6882. EXPECT_FALSE(
  6883. req->maybe_stored_cookies()[2].access_result.status.ShouldWarn());
  6884. }
  6885. // Get cookies (blocked by user preference)
  6886. network_delegate.set_block_annotate_cookies();
  6887. {
  6888. GURL url = test_server.GetURL("/");
  6889. auto cookie1 = CanonicalCookie::Create(
  6890. url, "cookienosamesite=1", base::Time::Now(), absl::nullopt,
  6891. absl::nullopt /* cookie_partition_key */);
  6892. base::RunLoop run_loop;
  6893. CookieAccessResult access_result;
  6894. cm.SetCanonicalCookieAsync(
  6895. std::move(cookie1), url, CookieOptions::MakeAllInclusive(),
  6896. base::BindLambdaForTesting([&](CookieAccessResult result) {
  6897. access_result = result;
  6898. run_loop.Quit();
  6899. }));
  6900. run_loop.Run();
  6901. EXPECT_TRUE(access_result.status.IsInclude());
  6902. TestDelegate d;
  6903. GURL test_url = test_server.GetURL("/echoheader?Cookie");
  6904. std::unique_ptr<URLRequest> req(context->CreateRequest(
  6905. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6906. GURL cross_site_url = test_server.GetURL("other.example", "/");
  6907. req->set_site_for_cookies(
  6908. net::SiteForCookies::FromUrl(cross_site_url)); // cross-site context
  6909. req->Start();
  6910. d.RunUntilComplete();
  6911. // No cookies were sent with the request because getting cookies is blocked.
  6912. EXPECT_EQ("None", d.data_received());
  6913. ASSERT_EQ(1u, req->maybe_sent_cookies().size());
  6914. EXPECT_EQ("cookienosamesite", req->maybe_sent_cookies()[0].cookie.Name());
  6915. EXPECT_TRUE(req->maybe_sent_cookies()[0]
  6916. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6917. {CookieInclusionStatus::EXCLUDE_USER_PREFERENCES,
  6918. CookieInclusionStatus::
  6919. EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX}));
  6920. // Cookie should not be warned about because it was blocked because of user
  6921. // preferences.
  6922. EXPECT_FALSE(
  6923. req->maybe_sent_cookies()[0].access_result.status.ShouldWarn());
  6924. }
  6925. network_delegate.unset_block_annotate_cookies();
  6926. // Get cookies
  6927. {
  6928. GURL url = test_server.GetURL("/");
  6929. auto cookie2 = CanonicalCookie::Create(
  6930. url, "cookiewithpath=1;path=/foo", base::Time::Now(), absl::nullopt,
  6931. absl::nullopt /* cookie_partition_key */);
  6932. base::RunLoop run_loop;
  6933. // Note: cookie1 from the previous testcase is still in the cookie store.
  6934. CookieAccessResult access_result;
  6935. cm.SetCanonicalCookieAsync(
  6936. std::move(cookie2), url, CookieOptions::MakeAllInclusive(),
  6937. base::BindLambdaForTesting([&](CookieAccessResult result) {
  6938. access_result = result;
  6939. run_loop.Quit();
  6940. }));
  6941. run_loop.Run();
  6942. EXPECT_TRUE(access_result.status.IsInclude());
  6943. TestDelegate d;
  6944. GURL test_url = test_server.GetURL("/echoheader?Cookie");
  6945. std::unique_ptr<URLRequest> req(context->CreateRequest(
  6946. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  6947. GURL cross_site_url = test_server.GetURL("other.example", "/");
  6948. req->set_site_for_cookies(
  6949. net::SiteForCookies::FromUrl(cross_site_url)); // cross-site context
  6950. req->Start();
  6951. d.RunUntilComplete();
  6952. // No cookies were sent with the request because they don't specify SameSite
  6953. // and the request is cross-site.
  6954. EXPECT_EQ("None", d.data_received());
  6955. ASSERT_EQ(2u, req->maybe_sent_cookies().size());
  6956. // Cookie excluded for other reasons is not warned about.
  6957. // Note: this cookie is first because the cookies are sorted by path length
  6958. // with longest first. See CookieSorter() in cookie_monster.cc.
  6959. EXPECT_EQ("cookiewithpath", req->maybe_sent_cookies()[0].cookie.Name());
  6960. EXPECT_TRUE(req->maybe_sent_cookies()[0]
  6961. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6962. {CookieInclusionStatus::EXCLUDE_NOT_ON_PATH,
  6963. CookieInclusionStatus::
  6964. EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX}));
  6965. EXPECT_FALSE(
  6966. req->maybe_sent_cookies()[0].access_result.status.ShouldWarn());
  6967. // Cookie that was only blocked because of unspecified SameSite should be
  6968. // warned about.
  6969. EXPECT_EQ("cookienosamesite", req->maybe_sent_cookies()[1].cookie.Name());
  6970. EXPECT_TRUE(req->maybe_sent_cookies()[1]
  6971. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6972. {CookieInclusionStatus::
  6973. EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX}));
  6974. EXPECT_TRUE(req->maybe_sent_cookies()[1]
  6975. .access_result.status.HasExactlyWarningReasonsForTesting(
  6976. {CookieInclusionStatus::
  6977. WARN_SAMESITE_UNSPECIFIED_CROSS_SITE_CONTEXT}));
  6978. }
  6979. }
  6980. TEST_F(URLRequestTestHTTP, AuthChallengeCancelCookieCollect) {
  6981. ASSERT_TRUE(http_test_server()->Start());
  6982. GURL url_requiring_auth =
  6983. http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
  6984. auto context_builder = CreateTestURLRequestContextBuilder();
  6985. auto filtering_network_delegate =
  6986. std::make_unique<FilteringTestNetworkDelegate>();
  6987. filtering_network_delegate->SetCookieFilter("got_challenged");
  6988. context_builder->set_network_delegate(std::move(filtering_network_delegate));
  6989. auto context = context_builder->Build();
  6990. TestDelegate delegate;
  6991. std::unique_ptr<URLRequest> request =
  6992. CreateFirstPartyRequest(*context, url_requiring_auth, &delegate);
  6993. request->Start();
  6994. delegate.RunUntilAuthRequired();
  6995. ASSERT_EQ(1u, request->maybe_stored_cookies().size());
  6996. EXPECT_TRUE(request->maybe_stored_cookies()[0]
  6997. .access_result.status.HasExactlyExclusionReasonsForTesting(
  6998. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  6999. EXPECT_EQ("got_challenged=true",
  7000. request->maybe_stored_cookies()[0].cookie_string);
  7001. // This shouldn't DCHECK-fail.
  7002. request->CancelAuth();
  7003. delegate.RunUntilComplete();
  7004. }
  7005. TEST_F(URLRequestTestHTTP, AuthChallengeWithFilteredCookies) {
  7006. ASSERT_TRUE(http_test_server()->Start());
  7007. GURL url_requiring_auth =
  7008. http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
  7009. GURL url_requiring_auth_wo_cookies =
  7010. http_test_server()->GetURL("/auth-basic");
  7011. // Check maybe_stored_cookies is populated first round trip, and cleared on
  7012. // the second.
  7013. {
  7014. auto context_builder = CreateTestURLRequestContextBuilder();
  7015. auto& filtering_network_delegate = *context_builder->set_network_delegate(
  7016. std::make_unique<FilteringTestNetworkDelegate>());
  7017. filtering_network_delegate.SetCookieFilter("got_challenged");
  7018. auto context = context_builder->Build();
  7019. TestDelegate delegate;
  7020. std::unique_ptr<URLRequest> request =
  7021. CreateFirstPartyRequest(*context, url_requiring_auth, &delegate);
  7022. request->Start();
  7023. delegate.RunUntilAuthRequired();
  7024. // Make sure it was blocked once.
  7025. EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
  7026. // The number of cookies blocked from the most recent round trip.
  7027. ASSERT_EQ(1u, request->maybe_stored_cookies().size());
  7028. EXPECT_TRUE(
  7029. request->maybe_stored_cookies()
  7030. .front()
  7031. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7032. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7033. // Now check the second round trip
  7034. request->SetAuth(AuthCredentials(kUser, kSecret));
  7035. delegate.RunUntilComplete();
  7036. EXPECT_THAT(delegate.request_status(), IsOk());
  7037. // There are DCHECKs in URLRequestHttpJob that would fail if
  7038. // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
  7039. // Make sure the cookie was actually filtered and not sent.
  7040. EXPECT_EQ(std::string::npos,
  7041. delegate.data_received().find("Cookie: got_challenged=true"));
  7042. // The number of cookies that most recent round trip tried to set.
  7043. ASSERT_EQ(0u, request->maybe_stored_cookies().size());
  7044. }
  7045. // Check maybe_sent_cookies on first round trip (and cleared for the second).
  7046. {
  7047. auto context_builder = CreateTestURLRequestContextBuilder();
  7048. auto& filtering_network_delegate = *context_builder->set_network_delegate(
  7049. std::make_unique<FilteringTestNetworkDelegate>());
  7050. filtering_network_delegate.set_block_annotate_cookies();
  7051. context_builder->SetCookieStore(std::make_unique<CookieMonster>(
  7052. nullptr, nullptr, /*first_party_sets_enabled=*/false));
  7053. auto context = context_builder->Build();
  7054. auto* cm = static_cast<CookieMonster*>(context->cookie_store());
  7055. auto another_cookie = CanonicalCookie::Create(
  7056. url_requiring_auth_wo_cookies, "another_cookie=true", base::Time::Now(),
  7057. absl::nullopt /* server_time */,
  7058. absl::nullopt /* cookie_partition_key */);
  7059. cm->SetCanonicalCookieAsync(std::move(another_cookie),
  7060. url_requiring_auth_wo_cookies,
  7061. net::CookieOptions::MakeAllInclusive(),
  7062. CookieStore::SetCookiesCallback());
  7063. TestDelegate delegate;
  7064. std::unique_ptr<URLRequest> request = CreateFirstPartyRequest(
  7065. *context, url_requiring_auth_wo_cookies, &delegate);
  7066. request->Start();
  7067. delegate.RunUntilAuthRequired();
  7068. ASSERT_EQ(1u, request->maybe_sent_cookies().size());
  7069. EXPECT_EQ("another_cookie",
  7070. request->maybe_sent_cookies().front().cookie.Name());
  7071. EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
  7072. EXPECT_TRUE(
  7073. request->maybe_sent_cookies()
  7074. .front()
  7075. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7076. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7077. // Check maybe_sent_cookies on second roundtrip.
  7078. request->set_maybe_sent_cookies({});
  7079. cm->DeleteAllAsync(CookieStore::DeleteCallback());
  7080. auto one_more_cookie = CanonicalCookie::Create(
  7081. url_requiring_auth_wo_cookies, "one_more_cookie=true",
  7082. base::Time::Now(), absl::nullopt /* server_time */,
  7083. absl::nullopt /* cookie_partition_key */);
  7084. cm->SetCanonicalCookieAsync(std::move(one_more_cookie),
  7085. url_requiring_auth_wo_cookies,
  7086. net::CookieOptions::MakeAllInclusive(),
  7087. CookieStore::SetCookiesCallback());
  7088. request->SetAuth(AuthCredentials(kUser, kSecret));
  7089. delegate.RunUntilComplete();
  7090. EXPECT_THAT(delegate.request_status(), IsOk());
  7091. // There are DCHECKs in URLRequestHttpJob that would fail if
  7092. // maybe_sent_cookies and maybe_stored_cookies were not cleared properly.
  7093. // Make sure the cookie was actually filtered.
  7094. EXPECT_EQ(std::string::npos,
  7095. delegate.data_received().find("Cookie: one_more_cookie=true"));
  7096. // got_challenged was set after the first request and blocked on the second,
  7097. // so it should only have been blocked this time
  7098. EXPECT_EQ(2, filtering_network_delegate.blocked_annotate_cookies_count());
  7099. // // The number of cookies blocked from the most recent round trip.
  7100. ASSERT_EQ(1u, request->maybe_sent_cookies().size());
  7101. EXPECT_EQ("one_more_cookie",
  7102. request->maybe_sent_cookies().front().cookie.Name());
  7103. EXPECT_TRUE(
  7104. request->maybe_sent_cookies()
  7105. .front()
  7106. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7107. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7108. }
  7109. }
  7110. // Tests that load timing works as expected with auth and the cache.
  7111. TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
  7112. ASSERT_TRUE(http_test_server()->Start());
  7113. // populate the cache
  7114. {
  7115. TestDelegate d;
  7116. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  7117. http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
  7118. TRAFFIC_ANNOTATION_FOR_TESTS));
  7119. r->set_isolation_info(isolation_info1_);
  7120. r->Start();
  7121. d.RunUntilAuthRequired();
  7122. LoadTimingInfo load_timing_info_before_auth;
  7123. r->GetLoadTimingInfo(&load_timing_info_before_auth);
  7124. TestLoadTimingNotReused(load_timing_info_before_auth,
  7125. CONNECT_TIMING_HAS_DNS_TIMES);
  7126. r->SetAuth(AuthCredentials(kUser, kSecret));
  7127. d.RunUntilComplete();
  7128. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  7129. LoadTimingInfo load_timing_info;
  7130. r->GetLoadTimingInfo(&load_timing_info);
  7131. // The test server does not support keep alive sockets, so the second
  7132. // request with auth should use a new socket.
  7133. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  7134. EXPECT_NE(load_timing_info_before_auth.socket_log_id,
  7135. load_timing_info.socket_log_id);
  7136. EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
  7137. load_timing_info.connect_timing.connect_start);
  7138. }
  7139. // Repeat request with end-to-end validation. Since auth-basic results in a
  7140. // cachable page, we expect this test to result in a 304. In which case, the
  7141. // response should be fetched from the cache.
  7142. {
  7143. TestDelegate d;
  7144. d.set_credentials(AuthCredentials(kUser, kSecret));
  7145. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  7146. http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
  7147. TRAFFIC_ANNOTATION_FOR_TESTS));
  7148. r->SetLoadFlags(LOAD_VALIDATE_CACHE);
  7149. r->set_isolation_info(isolation_info1_);
  7150. r->Start();
  7151. d.RunUntilComplete();
  7152. EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
  7153. // Should be the same cached document.
  7154. EXPECT_TRUE(r->was_cached());
  7155. // Since there was a request that went over the wire, the load timing
  7156. // information should include connection times.
  7157. LoadTimingInfo load_timing_info;
  7158. r->GetLoadTimingInfo(&load_timing_info);
  7159. TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
  7160. }
  7161. }
  7162. // In this test, we do a POST which the server will 302 redirect.
  7163. // The subsequent transaction should use GET, and should not send the
  7164. // Content-Type header.
  7165. // http://code.google.com/p/chromium/issues/detail?id=843
  7166. TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
  7167. ASSERT_TRUE(http_test_server()->Start());
  7168. const char kData[] = "hello world";
  7169. TestDelegate d;
  7170. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7171. http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
  7172. TRAFFIC_ANNOTATION_FOR_TESTS));
  7173. req->set_method("POST");
  7174. req->set_upload(CreateSimpleUploadData(kData));
  7175. // Set headers (some of which are specific to the POST).
  7176. HttpRequestHeaders headers;
  7177. headers.SetHeader("Content-Type",
  7178. "multipart/form-data;"
  7179. "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ");
  7180. headers.SetHeader("Accept",
  7181. "text/xml,application/xml,application/xhtml+xml,"
  7182. "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
  7183. headers.SetHeader("Accept-Language", "en-US,en");
  7184. headers.SetHeader("Accept-Charset", "ISO-8859-1,*,utf-8");
  7185. headers.SetHeader("Content-Length", "11");
  7186. headers.SetHeader("Origin", "http://localhost:1337/");
  7187. req->SetExtraRequestHeaders(headers);
  7188. req->Start();
  7189. d.RunUntilComplete();
  7190. std::string mime_type;
  7191. req->GetMimeType(&mime_type);
  7192. EXPECT_EQ("text/html", mime_type);
  7193. const std::string& data = d.data_received();
  7194. // Check that the post-specific headers were stripped:
  7195. EXPECT_FALSE(ContainsString(data, "Content-Length:"));
  7196. EXPECT_FALSE(ContainsString(data, "Content-Type:"));
  7197. EXPECT_FALSE(ContainsString(data, "Origin:"));
  7198. // These extra request headers should not have been stripped.
  7199. EXPECT_TRUE(ContainsString(data, "Accept:"));
  7200. EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
  7201. EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
  7202. }
  7203. // The following tests check that we handle mutating the request for HTTP
  7204. // redirects as expected.
  7205. // See https://crbug.com/56373, https://crbug.com/102130, and
  7206. // https://crbug.com/465517.
  7207. TEST_F(URLRequestTestHTTP, Redirect301Tests) {
  7208. ASSERT_TRUE(http_test_server()->Start());
  7209. const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
  7210. const GURL https_redirect_url =
  7211. http_test_server()->GetURL("/redirect301-to-https");
  7212. HTTPRedirectMethodTest(url, "POST", "GET", true);
  7213. HTTPRedirectMethodTest(url, "PUT", "PUT", true);
  7214. HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
  7215. HTTPRedirectOriginHeaderTest(url, "GET", "GET",
  7216. url.DeprecatedGetOriginAsURL().spec());
  7217. HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
  7218. HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
  7219. HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
  7220. std::string());
  7221. HTTPRedirectOriginHeaderTest(url, "PUT", "PUT",
  7222. url.DeprecatedGetOriginAsURL().spec());
  7223. HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
  7224. }
  7225. TEST_F(URLRequestTestHTTP, Redirect302Tests) {
  7226. ASSERT_TRUE(http_test_server()->Start());
  7227. const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
  7228. const GURL https_redirect_url =
  7229. http_test_server()->GetURL("/redirect302-to-https");
  7230. HTTPRedirectMethodTest(url, "POST", "GET", true);
  7231. HTTPRedirectMethodTest(url, "PUT", "PUT", true);
  7232. HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
  7233. HTTPRedirectOriginHeaderTest(url, "GET", "GET",
  7234. url.DeprecatedGetOriginAsURL().spec());
  7235. HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
  7236. HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
  7237. HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
  7238. std::string());
  7239. HTTPRedirectOriginHeaderTest(url, "PUT", "PUT",
  7240. url.DeprecatedGetOriginAsURL().spec());
  7241. HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
  7242. }
  7243. TEST_F(URLRequestTestHTTP, Redirect303Tests) {
  7244. ASSERT_TRUE(http_test_server()->Start());
  7245. const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
  7246. const GURL https_redirect_url =
  7247. http_test_server()->GetURL("/redirect303-to-https");
  7248. HTTPRedirectMethodTest(url, "POST", "GET", true);
  7249. HTTPRedirectMethodTest(url, "PUT", "GET", true);
  7250. HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
  7251. HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
  7252. HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
  7253. std::string());
  7254. HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
  7255. HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
  7256. std::string());
  7257. HTTPRedirectOriginHeaderTest(url, "GET", "GET",
  7258. url.DeprecatedGetOriginAsURL().spec());
  7259. HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
  7260. HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD",
  7261. url.DeprecatedGetOriginAsURL().spec());
  7262. HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
  7263. HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
  7264. HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
  7265. std::string());
  7266. HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
  7267. HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
  7268. std::string());
  7269. HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
  7270. HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
  7271. }
  7272. TEST_F(URLRequestTestHTTP, Redirect307Tests) {
  7273. ASSERT_TRUE(http_test_server()->Start());
  7274. const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
  7275. const GURL https_redirect_url =
  7276. http_test_server()->GetURL("/redirect307-to-https");
  7277. HTTPRedirectMethodTest(url, "POST", "POST", true);
  7278. HTTPRedirectMethodTest(url, "PUT", "PUT", true);
  7279. HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
  7280. HTTPRedirectOriginHeaderTest(url, "GET", "GET",
  7281. url.DeprecatedGetOriginAsURL().spec());
  7282. HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
  7283. HTTPRedirectOriginHeaderTest(url, "POST", "POST",
  7284. url.DeprecatedGetOriginAsURL().spec());
  7285. HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
  7286. HTTPRedirectOriginHeaderTest(url, "PUT", "PUT",
  7287. url.DeprecatedGetOriginAsURL().spec());
  7288. HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
  7289. }
  7290. TEST_F(URLRequestTestHTTP, Redirect308Tests) {
  7291. ASSERT_TRUE(http_test_server()->Start());
  7292. const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
  7293. const GURL https_redirect_url =
  7294. http_test_server()->GetURL("/redirect308-to-https");
  7295. HTTPRedirectMethodTest(url, "POST", "POST", true);
  7296. HTTPRedirectMethodTest(url, "PUT", "PUT", true);
  7297. HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
  7298. HTTPRedirectOriginHeaderTest(url, "GET", "GET",
  7299. url.DeprecatedGetOriginAsURL().spec());
  7300. HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
  7301. HTTPRedirectOriginHeaderTest(url, "POST", "POST",
  7302. url.DeprecatedGetOriginAsURL().spec());
  7303. HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
  7304. HTTPRedirectOriginHeaderTest(url, "PUT", "PUT",
  7305. url.DeprecatedGetOriginAsURL().spec());
  7306. HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
  7307. }
  7308. // Make sure that 308 responses without bodies are not treated as redirects.
  7309. // Certain legacy apis that pre-date the response code expect this behavior
  7310. // (Like Google Drive).
  7311. TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
  7312. ASSERT_TRUE(http_test_server()->Start());
  7313. TestDelegate d;
  7314. const GURL url = http_test_server()->GetURL("/308-without-location-header");
  7315. std::unique_ptr<URLRequest> request(default_context().CreateRequest(
  7316. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7317. request->Start();
  7318. d.RunUntilComplete();
  7319. EXPECT_EQ(OK, d.request_status());
  7320. EXPECT_EQ(0, d.received_redirect_count());
  7321. EXPECT_EQ(308, request->response_headers()->response_code());
  7322. EXPECT_EQ("This is not a redirect.", d.data_received());
  7323. }
  7324. TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
  7325. ASSERT_TRUE(http_test_server()->Start());
  7326. GURL original_url(
  7327. http_test_server()->GetURL("/redirect302-to-echo#fragment"));
  7328. GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
  7329. TestDelegate d;
  7330. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  7331. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7332. r->Start();
  7333. d.RunUntilComplete();
  7334. EXPECT_EQ(2U, r->url_chain().size());
  7335. EXPECT_EQ(OK, d.request_status());
  7336. EXPECT_EQ(original_url, r->original_url());
  7337. EXPECT_EQ(expected_url, r->url());
  7338. }
  7339. TEST_F(URLRequestTestHTTP, RedirectWithFilteredCookies) {
  7340. ASSERT_TRUE(http_test_server()->Start());
  7341. // FilteringTestNetworkDelegate filters by name, so the names of the two
  7342. // cookies have to be the same. The values have been set to different strings
  7343. // (the value of the server-redirect cookies is "true" and set-cookie is
  7344. // "other") to differentiate between the two round trips.
  7345. GURL redirect_to(
  7346. http_test_server()->GetURL("/set-cookie?server-redirect=other"));
  7347. GURL original_url(http_test_server()->GetURL("/server-redirect-with-cookie?" +
  7348. redirect_to.spec()));
  7349. GURL original_url_wo_cookie(
  7350. http_test_server()->GetURL("/server-redirect?" + redirect_to.spec()));
  7351. // Check maybe_stored_cookies on first round trip.
  7352. {
  7353. auto context_builder = CreateTestURLRequestContextBuilder();
  7354. auto& filtering_network_delegate = *context_builder->set_network_delegate(
  7355. std::make_unique<FilteringTestNetworkDelegate>());
  7356. filtering_network_delegate.SetCookieFilter(
  7357. "server-redirect"); // Filter the cookie server-redirect sets.
  7358. auto context = context_builder->Build();
  7359. TestDelegate delegate;
  7360. std::unique_ptr<URLRequest> request =
  7361. CreateFirstPartyRequest(*context, original_url, &delegate);
  7362. request->Start();
  7363. delegate.RunUntilRedirect();
  7364. // Make sure it was blocked once.
  7365. EXPECT_EQ(1, filtering_network_delegate.blocked_set_cookie_count());
  7366. // The number of cookies blocked from the most recent round trip.
  7367. ASSERT_EQ(1u, request->maybe_stored_cookies().size());
  7368. EXPECT_EQ("server-redirect",
  7369. request->maybe_stored_cookies().front().cookie->Name());
  7370. EXPECT_EQ("true", request->maybe_stored_cookies().front().cookie->Value());
  7371. EXPECT_TRUE(
  7372. request->maybe_stored_cookies()
  7373. .front()
  7374. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7375. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7376. // Check maybe_stored_cookies on second round trip (and clearing from the
  7377. // first).
  7378. request->FollowDeferredRedirect(absl::nullopt, absl::nullopt);
  7379. delegate.RunUntilComplete();
  7380. EXPECT_THAT(delegate.request_status(), IsOk());
  7381. // There are DCHECKs in URLRequestHttpJob that would fail if
  7382. // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
  7383. // Make sure it was blocked twice.
  7384. EXPECT_EQ(2, filtering_network_delegate.blocked_set_cookie_count());
  7385. // The number of cookies blocked from the most recent round trip.
  7386. ASSERT_EQ(1u, request->maybe_stored_cookies().size());
  7387. EXPECT_EQ("server-redirect",
  7388. request->maybe_stored_cookies().front().cookie->Name());
  7389. EXPECT_EQ("other", request->maybe_stored_cookies().front().cookie->Value());
  7390. EXPECT_TRUE(
  7391. request->maybe_stored_cookies()
  7392. .front()
  7393. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7394. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7395. }
  7396. // Check maybe_sent_cookies on first round trip.
  7397. {
  7398. auto context_builder = CreateTestURLRequestContextBuilder();
  7399. auto& filtering_network_delegate = *context_builder->set_network_delegate(
  7400. std::make_unique<FilteringTestNetworkDelegate>());
  7401. filtering_network_delegate.set_block_annotate_cookies();
  7402. context_builder->SetCookieStore(std::make_unique<CookieMonster>(
  7403. nullptr, nullptr, /*first_party_sets_enabled=*/false));
  7404. auto context = context_builder->Build();
  7405. auto* cm = static_cast<CookieMonster*>(context->cookie_store());
  7406. auto another_cookie = CanonicalCookie::Create(
  7407. original_url, "another_cookie=true", base::Time::Now(),
  7408. absl::nullopt /* server_time */,
  7409. absl::nullopt /* cookie_partition_key */);
  7410. cm->SetCanonicalCookieAsync(std::move(another_cookie), original_url,
  7411. net::CookieOptions::MakeAllInclusive(),
  7412. CookieStore::SetCookiesCallback());
  7413. TestDelegate delegate;
  7414. std::unique_ptr<URLRequest> request =
  7415. CreateFirstPartyRequest(*context, original_url_wo_cookie, &delegate);
  7416. request->Start();
  7417. delegate.RunUntilRedirect();
  7418. ASSERT_EQ(1u, request->maybe_sent_cookies().size());
  7419. EXPECT_EQ("another_cookie",
  7420. request->maybe_sent_cookies().front().cookie.Name());
  7421. EXPECT_TRUE(
  7422. request->maybe_sent_cookies()
  7423. .front()
  7424. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7425. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7426. // Check maybe_sent_cookies on second round trip
  7427. request->set_maybe_sent_cookies({});
  7428. cm->DeleteAllAsync(CookieStore::DeleteCallback());
  7429. auto one_more_cookie = CanonicalCookie::Create(
  7430. original_url_wo_cookie, "one_more_cookie=true", base::Time::Now(),
  7431. absl::nullopt /* server_time */,
  7432. absl::nullopt /* cookie_partition_key */);
  7433. cm->SetCanonicalCookieAsync(std::move(one_more_cookie),
  7434. original_url_wo_cookie,
  7435. net::CookieOptions::MakeAllInclusive(),
  7436. CookieStore::SetCookiesCallback());
  7437. request->FollowDeferredRedirect(absl::nullopt, absl::nullopt);
  7438. delegate.RunUntilComplete();
  7439. EXPECT_THAT(delegate.request_status(), IsOk());
  7440. // There are DCHECKs in URLRequestHttpJob that would fail if
  7441. // maybe_sent_cookies and maybe_stored_cookies we not cleared properly.
  7442. EXPECT_EQ(2, filtering_network_delegate.blocked_annotate_cookies_count());
  7443. // The number of cookies blocked from the most recent round trip.
  7444. ASSERT_EQ(1u, request->maybe_sent_cookies().size());
  7445. EXPECT_EQ("one_more_cookie",
  7446. request->maybe_sent_cookies().front().cookie.Name());
  7447. EXPECT_EQ("true", request->maybe_sent_cookies().front().cookie.Value());
  7448. EXPECT_TRUE(
  7449. request->maybe_sent_cookies()
  7450. .front()
  7451. .access_result.status.HasExactlyExclusionReasonsForTesting(
  7452. {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES}));
  7453. }
  7454. }
  7455. TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
  7456. ASSERT_TRUE(http_test_server()->Start());
  7457. GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
  7458. GURL first_party_url("http://example.com");
  7459. TestDelegate d;
  7460. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  7461. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7462. r->set_site_for_cookies(SiteForCookies::FromUrl(first_party_url));
  7463. r->Start();
  7464. d.RunUntilComplete();
  7465. EXPECT_EQ(2U, r->url_chain().size());
  7466. EXPECT_EQ(OK, d.request_status());
  7467. EXPECT_TRUE(SiteForCookies::FromUrl(first_party_url)
  7468. .IsEquivalent(r->site_for_cookies()));
  7469. }
  7470. TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
  7471. ASSERT_TRUE(http_test_server()->Start());
  7472. GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
  7473. GURL original_first_party_url("http://example.com");
  7474. GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
  7475. TestDelegate d;
  7476. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  7477. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7478. r->set_site_for_cookies(SiteForCookies::FromUrl(original_first_party_url));
  7479. r->set_first_party_url_policy(
  7480. RedirectInfo::FirstPartyURLPolicy::UPDATE_URL_ON_REDIRECT);
  7481. r->Start();
  7482. d.RunUntilComplete();
  7483. EXPECT_EQ(2U, r->url_chain().size());
  7484. EXPECT_EQ(OK, d.request_status());
  7485. EXPECT_TRUE(SiteForCookies::FromUrl(expected_first_party_url)
  7486. .IsEquivalent(r->site_for_cookies()));
  7487. }
  7488. TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
  7489. ASSERT_TRUE(http_test_server()->Start());
  7490. const char kData[] = "hello world";
  7491. TestDelegate d;
  7492. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7493. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  7494. TRAFFIC_ANNOTATION_FOR_TESTS));
  7495. req->set_method("POST");
  7496. req->set_upload(CreateSimpleUploadData(kData));
  7497. HttpRequestHeaders headers;
  7498. headers.SetHeader(HttpRequestHeaders::kContentLength,
  7499. base::NumberToString(std::size(kData) - 1));
  7500. req->SetExtraRequestHeaders(headers);
  7501. std::unique_ptr<URLRequestRedirectJob> job =
  7502. std::make_unique<URLRequestRedirectJob>(
  7503. req.get(), http_test_server()->GetURL("/echo"),
  7504. RedirectUtil::ResponseCode::REDIRECT_302_FOUND, "Very Good Reason");
  7505. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  7506. req->Start();
  7507. d.RunUntilComplete();
  7508. EXPECT_EQ("GET", req->method());
  7509. }
  7510. TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
  7511. ASSERT_TRUE(http_test_server()->Start());
  7512. const char kData[] = "hello world";
  7513. TestDelegate d;
  7514. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7515. http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  7516. TRAFFIC_ANNOTATION_FOR_TESTS));
  7517. req->set_method("POST");
  7518. req->set_upload(CreateSimpleUploadData(kData));
  7519. HttpRequestHeaders headers;
  7520. headers.SetHeader(HttpRequestHeaders::kContentLength,
  7521. base::NumberToString(std::size(kData) - 1));
  7522. req->SetExtraRequestHeaders(headers);
  7523. std::unique_ptr<URLRequestRedirectJob> job =
  7524. std::make_unique<URLRequestRedirectJob>(
  7525. req.get(), http_test_server()->GetURL("/echo"),
  7526. RedirectUtil::ResponseCode::REDIRECT_307_TEMPORARY_REDIRECT,
  7527. "Very Good Reason");
  7528. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  7529. req->Start();
  7530. d.RunUntilComplete();
  7531. EXPECT_EQ("POST", req->method());
  7532. EXPECT_EQ(kData, d.data_received());
  7533. }
  7534. // Check that default A-L header is sent.
  7535. TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
  7536. ASSERT_TRUE(http_test_server()->Start());
  7537. auto context_builder = CreateTestURLRequestContextBuilder();
  7538. context_builder->set_http_user_agent_settings(
  7539. std::make_unique<StaticHttpUserAgentSettings>("en", std::string()));
  7540. auto context = context_builder->Build();
  7541. TestDelegate d;
  7542. std::unique_ptr<URLRequest> req(context->CreateRequest(
  7543. http_test_server()->GetURL("/echoheader?Accept-Language"),
  7544. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7545. req->Start();
  7546. d.RunUntilComplete();
  7547. EXPECT_EQ("en", d.data_received());
  7548. }
  7549. // Check that an empty A-L header is not sent. http://crbug.com/77365.
  7550. TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
  7551. ASSERT_TRUE(http_test_server()->Start());
  7552. auto context_builder = CreateTestURLRequestContextBuilder();
  7553. context_builder->set_http_user_agent_settings(
  7554. std::make_unique<StaticHttpUserAgentSettings>(std::string(),
  7555. std::string()));
  7556. auto context = context_builder->Build();
  7557. TestDelegate d;
  7558. std::unique_ptr<URLRequest> req(context->CreateRequest(
  7559. http_test_server()->GetURL("/echoheader?Accept-Language"),
  7560. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7561. req->Start();
  7562. d.RunUntilComplete();
  7563. EXPECT_EQ("None", d.data_received());
  7564. }
  7565. // Check that if request overrides the A-L header, the default is not appended.
  7566. // See http://crbug.com/20894
  7567. TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
  7568. ASSERT_TRUE(http_test_server()->Start());
  7569. TestDelegate d;
  7570. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7571. http_test_server()->GetURL("/echoheader?Accept-Language"),
  7572. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7573. HttpRequestHeaders headers;
  7574. headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
  7575. req->SetExtraRequestHeaders(headers);
  7576. req->Start();
  7577. d.RunUntilComplete();
  7578. EXPECT_EQ(std::string("ru"), d.data_received());
  7579. }
  7580. // Check that default A-E header is sent.
  7581. TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
  7582. ASSERT_TRUE(http_test_server()->Start());
  7583. TestDelegate d;
  7584. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7585. http_test_server()->GetURL("/echoheader?Accept-Encoding"),
  7586. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7587. HttpRequestHeaders headers;
  7588. req->SetExtraRequestHeaders(headers);
  7589. req->Start();
  7590. d.RunUntilComplete();
  7591. EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
  7592. }
  7593. // Check that it's possible to override the default A-E header.
  7594. TEST_F(URLRequestTestHTTP, DefaultAcceptEncodingOverriden) {
  7595. ASSERT_TRUE(http_test_server()->Start());
  7596. struct {
  7597. base::flat_set<net::SourceStream::SourceType> accepted_types;
  7598. const char* expected_accept_encoding;
  7599. } tests[] = {{{net::SourceStream::SourceType::TYPE_DEFLATE}, "deflate"},
  7600. {{}, "None"},
  7601. {{net::SourceStream::SourceType::TYPE_GZIP}, "gzip"},
  7602. {{net::SourceStream::SourceType::TYPE_GZIP,
  7603. net::SourceStream::SourceType::TYPE_DEFLATE},
  7604. "gzip, deflate"}};
  7605. for (auto test : tests) {
  7606. TestDelegate d;
  7607. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7608. http_test_server()->GetURL("/echoheader?Accept-Encoding"),
  7609. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7610. req->set_accepted_stream_types(test.accepted_types);
  7611. req->Start();
  7612. d.RunUntilComplete();
  7613. EXPECT_STRCASEEQ(d.data_received().c_str(), test.expected_accept_encoding);
  7614. }
  7615. }
  7616. // Check that if request overrides the A-E header, the default is not appended.
  7617. // See http://crbug.com/47381
  7618. TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
  7619. ASSERT_TRUE(http_test_server()->Start());
  7620. TestDelegate d;
  7621. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7622. http_test_server()->GetURL("/echoheader?Accept-Encoding"),
  7623. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7624. HttpRequestHeaders headers;
  7625. headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
  7626. req->SetExtraRequestHeaders(headers);
  7627. req->Start();
  7628. d.RunUntilComplete();
  7629. EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
  7630. EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
  7631. }
  7632. // Check that setting the A-C header sends the proper header.
  7633. TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
  7634. ASSERT_TRUE(http_test_server()->Start());
  7635. TestDelegate d;
  7636. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7637. http_test_server()->GetURL("/echoheader?Accept-Charset"),
  7638. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7639. HttpRequestHeaders headers;
  7640. headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
  7641. req->SetExtraRequestHeaders(headers);
  7642. req->Start();
  7643. d.RunUntilComplete();
  7644. EXPECT_EQ(std::string("koi-8r"), d.data_received());
  7645. }
  7646. // Check that default User-Agent header is sent.
  7647. TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
  7648. ASSERT_TRUE(http_test_server()->Start());
  7649. TestDelegate d;
  7650. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7651. http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
  7652. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7653. req->Start();
  7654. d.RunUntilComplete();
  7655. EXPECT_EQ(default_context().http_user_agent_settings()->GetUserAgent(),
  7656. d.data_received());
  7657. }
  7658. // Check that if request overrides the User-Agent header,
  7659. // the default is not appended.
  7660. // TODO(crbug.com/564656) This test is flaky on iOS.
  7661. #if BUILDFLAG(IS_IOS)
  7662. #define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
  7663. #else
  7664. #define MAYBE_OverrideUserAgent OverrideUserAgent
  7665. #endif
  7666. TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
  7667. ASSERT_TRUE(http_test_server()->Start());
  7668. TestDelegate d;
  7669. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7670. http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
  7671. &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7672. HttpRequestHeaders headers;
  7673. headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
  7674. req->SetExtraRequestHeaders(headers);
  7675. req->Start();
  7676. d.RunUntilComplete();
  7677. EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
  7678. }
  7679. // Check that a NULL HttpUserAgentSettings causes the corresponding empty
  7680. // User-Agent header to be sent but does not send the Accept-Language and
  7681. // Accept-Charset headers.
  7682. TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
  7683. ASSERT_TRUE(http_test_server()->Start());
  7684. auto context_builder = CreateTestURLRequestContextBuilder();
  7685. context_builder->set_http_user_agent_settings(nullptr);
  7686. auto context = context_builder->Build();
  7687. struct {
  7688. const char* request;
  7689. const char* expected_response;
  7690. } tests[] = {{"/echoheader?Accept-Language", "None"},
  7691. {"/echoheader?Accept-Charset", "None"},
  7692. {"/echoheader?User-Agent", ""}};
  7693. for (const auto& test : tests) {
  7694. TestDelegate d;
  7695. std::unique_ptr<URLRequest> req(context->CreateRequest(
  7696. http_test_server()->GetURL(test.request), DEFAULT_PRIORITY, &d,
  7697. TRAFFIC_ANNOTATION_FOR_TESTS));
  7698. req->Start();
  7699. d.RunUntilComplete();
  7700. EXPECT_EQ(test.expected_response, d.data_received())
  7701. << " Request = \"" << test.request << "\"";
  7702. }
  7703. }
  7704. // Make sure that URLRequest passes on its priority updates to
  7705. // newly-created jobs after the first one.
  7706. TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
  7707. GURL initial_url("http://foo.test/");
  7708. GURL redirect_url("http://bar.test/");
  7709. TestDelegate d;
  7710. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7711. initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7712. EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
  7713. std::unique_ptr<URLRequestRedirectJob> redirect_job =
  7714. std::make_unique<URLRequestRedirectJob>(
  7715. req.get(), redirect_url,
  7716. RedirectUtil::ResponseCode::REDIRECT_302_FOUND, "Very Good Reason");
  7717. auto interceptor = std::make_unique<TestScopedURLInterceptor>(
  7718. initial_url, std::move(redirect_job));
  7719. req->SetPriority(LOW);
  7720. req->Start();
  7721. EXPECT_TRUE(req->is_pending());
  7722. d.RunUntilRedirect();
  7723. interceptor.reset();
  7724. RequestPriority job_priority;
  7725. std::unique_ptr<URLRequestJob> job =
  7726. std::make_unique<PriorityMonitoringURLRequestJob>(req.get(),
  7727. &job_priority);
  7728. interceptor =
  7729. std::make_unique<TestScopedURLInterceptor>(redirect_url, std::move(job));
  7730. // Should trigger |job| to be started.
  7731. req->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  7732. absl::nullopt /* modified_headers */);
  7733. d.RunUntilComplete();
  7734. EXPECT_EQ(LOW, job_priority);
  7735. }
  7736. // Check that creating a network request while entering/exiting suspend mode
  7737. // fails as it should. This is the only case where an HttpTransactionFactory
  7738. // does not return an HttpTransaction.
  7739. TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
  7740. auto context_builder = CreateTestURLRequestContextBuilder();
  7741. context_builder->SetCreateHttpTransactionFactoryCallback(
  7742. base::BindOnce([](HttpNetworkSession* session) {
  7743. // Create a new HttpNetworkLayer that thinks it's suspended.
  7744. auto network_layer = std::make_unique<HttpNetworkLayer>(session);
  7745. network_layer->OnSuspend();
  7746. std::unique_ptr<HttpTransactionFactory> factory =
  7747. std::make_unique<HttpCache>(std::move(network_layer),
  7748. HttpCache::DefaultBackend::InMemory(0));
  7749. return factory;
  7750. }));
  7751. auto context = context_builder->Build();
  7752. TestDelegate d;
  7753. std::unique_ptr<URLRequest> req(
  7754. context->CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
  7755. TRAFFIC_ANNOTATION_FOR_TESTS));
  7756. req->Start();
  7757. d.RunUntilComplete();
  7758. EXPECT_TRUE(d.request_failed());
  7759. EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
  7760. }
  7761. namespace {
  7762. // HttpTransactionFactory that synchronously fails to create transactions.
  7763. class FailingHttpTransactionFactory : public HttpTransactionFactory {
  7764. public:
  7765. explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
  7766. : network_session_(network_session) {}
  7767. FailingHttpTransactionFactory(const FailingHttpTransactionFactory&) = delete;
  7768. FailingHttpTransactionFactory& operator=(
  7769. const FailingHttpTransactionFactory&) = delete;
  7770. ~FailingHttpTransactionFactory() override = default;
  7771. // HttpTransactionFactory methods:
  7772. int CreateTransaction(RequestPriority priority,
  7773. std::unique_ptr<HttpTransaction>* trans) override {
  7774. return ERR_FAILED;
  7775. }
  7776. HttpCache* GetCache() override { return nullptr; }
  7777. HttpNetworkSession* GetSession() override { return network_session_; }
  7778. private:
  7779. raw_ptr<HttpNetworkSession> network_session_;
  7780. };
  7781. } // namespace
  7782. // Check that when a request that fails to create an HttpTransaction can be
  7783. // cancelled while the failure notification is pending, and doesn't send two
  7784. // failure notifications.
  7785. //
  7786. // This currently only happens when in suspend mode and there's no cache, but
  7787. // just use a special HttpTransactionFactory, to avoid depending on those
  7788. // behaviors.
  7789. //
  7790. // Flaky crash: https://crbug.com/1348418
  7791. #if BUILDFLAG(IS_CHROMEOS)
  7792. #define MAYBE_NetworkCancelAfterCreateTransactionFailsTest \
  7793. DISABLED_NetworkCancelAfterCreateTransactionFailsTest
  7794. #else
  7795. #define MAYBE_NetworkCancelAfterCreateTransactionFailsTest \
  7796. NetworkCancelAfterCreateTransactionFailsTest
  7797. #endif
  7798. TEST_F(URLRequestTestHTTP, MAYBE_NetworkCancelAfterCreateTransactionFailsTest) {
  7799. auto context_builder = CreateTestURLRequestContextBuilder();
  7800. context_builder->SetCreateHttpTransactionFactoryCallback(
  7801. base::BindOnce([](HttpNetworkSession* session) {
  7802. std::unique_ptr<HttpTransactionFactory> factory =
  7803. std::make_unique<FailingHttpTransactionFactory>(session);
  7804. return factory;
  7805. }));
  7806. auto& network_delegate = *context_builder->set_network_delegate(
  7807. std::make_unique<TestNetworkDelegate>());
  7808. auto context = context_builder->Build();
  7809. TestDelegate d;
  7810. std::unique_ptr<URLRequest> req(
  7811. context->CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
  7812. TRAFFIC_ANNOTATION_FOR_TESTS));
  7813. // Don't send cookies (Collecting cookies is asynchronous, and need request to
  7814. // try to create an HttpNetworkTransaction synchronously on start).
  7815. req->set_allow_credentials(false);
  7816. req->Start();
  7817. req->Cancel();
  7818. d.RunUntilComplete();
  7819. // Run pending error task, if there is one.
  7820. base::RunLoop().RunUntilIdle();
  7821. EXPECT_TRUE(d.request_failed());
  7822. EXPECT_EQ(1, d.response_started_count());
  7823. EXPECT_EQ(ERR_ABORTED, d.request_status());
  7824. // NetworkDelegate should see the cancellation, but not the error.
  7825. EXPECT_EQ(1, network_delegate.canceled_requests());
  7826. EXPECT_EQ(0, network_delegate.error_count());
  7827. }
  7828. TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
  7829. ASSERT_TRUE(http_test_server()->Start());
  7830. TestDelegate d;
  7831. GURL test_url(http_test_server()->GetURL("/"));
  7832. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7833. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7834. req->Start();
  7835. d.RunUntilComplete();
  7836. EXPECT_TRUE(req->response_info().network_accessed);
  7837. }
  7838. TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
  7839. ASSERT_TRUE(http_test_server()->Start());
  7840. // Populate the cache.
  7841. TestDelegate d;
  7842. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7843. http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
  7844. TRAFFIC_ANNOTATION_FOR_TESTS));
  7845. req->set_isolation_info(isolation_info1_);
  7846. req->Start();
  7847. d.RunUntilComplete();
  7848. EXPECT_EQ(OK, d.request_status());
  7849. EXPECT_TRUE(req->response_info().network_accessed);
  7850. EXPECT_FALSE(req->response_info().was_cached);
  7851. req = default_context().CreateRequest(
  7852. http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
  7853. TRAFFIC_ANNOTATION_FOR_TESTS);
  7854. req->set_isolation_info(isolation_info1_);
  7855. req->Start();
  7856. d.RunUntilComplete();
  7857. EXPECT_EQ(OK, d.request_status());
  7858. EXPECT_FALSE(req->response_info().network_accessed);
  7859. EXPECT_TRUE(req->response_info().was_cached);
  7860. }
  7861. TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
  7862. ASSERT_TRUE(http_test_server()->Start());
  7863. TestDelegate d;
  7864. GURL test_url(http_test_server()->GetURL("/"));
  7865. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7866. test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7867. req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
  7868. req->Start();
  7869. d.RunUntilComplete();
  7870. EXPECT_FALSE(req->response_info().network_accessed);
  7871. }
  7872. // Test that a single job with a THROTTLED priority completes
  7873. // correctly in the absence of contention.
  7874. TEST_F(URLRequestTestHTTP, ThrottledPriority) {
  7875. ASSERT_TRUE(http_test_server()->Start());
  7876. TestDelegate d;
  7877. GURL test_url(http_test_server()->GetURL("/"));
  7878. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7879. test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7880. req->Start();
  7881. d.RunUntilComplete();
  7882. EXPECT_EQ(OK, d.request_status());
  7883. }
  7884. TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
  7885. ASSERT_TRUE(http_test_server()->Start());
  7886. TestDelegate d;
  7887. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7888. http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
  7889. TRAFFIC_ANNOTATION_FOR_TESTS));
  7890. req->Start();
  7891. d.RunUntilComplete();
  7892. EXPECT_EQ(5, req->GetRawBodyBytes());
  7893. }
  7894. TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
  7895. ASSERT_TRUE(http_test_server()->Start());
  7896. TestDelegate d;
  7897. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7898. http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
  7899. TRAFFIC_ANNOTATION_FOR_TESTS));
  7900. req->Start();
  7901. d.RunUntilComplete();
  7902. EXPECT_EQ(30, req->GetRawBodyBytes());
  7903. }
  7904. // Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
  7905. // the delegate isn't called back synchronously.
  7906. TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
  7907. ASSERT_TRUE(http_test_server()->Start());
  7908. default_network_delegate().set_before_start_transaction_fails();
  7909. TestDelegate d;
  7910. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7911. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
  7912. TRAFFIC_ANNOTATION_FOR_TESTS));
  7913. req->Start();
  7914. DCHECK(!d.response_completed());
  7915. d.RunUntilComplete();
  7916. DCHECK(d.response_completed());
  7917. EXPECT_EQ(ERR_FAILED, d.request_status());
  7918. }
  7919. class URLRequestTestReferrerPolicy : public URLRequestTest {
  7920. public:
  7921. URLRequestTestReferrerPolicy() = default;
  7922. void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
  7923. origin_server_ = std::make_unique<EmbeddedTestServer>(type);
  7924. RegisterDefaultHandlers(origin_server_.get());
  7925. ASSERT_TRUE(origin_server_->Start());
  7926. }
  7927. void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
  7928. net::EmbeddedTestServer::Type dest_type) {
  7929. origin_server_ = std::make_unique<EmbeddedTestServer>(origin_type);
  7930. RegisterDefaultHandlers(origin_server_.get());
  7931. ASSERT_TRUE(origin_server_->Start());
  7932. destination_server_ = std::make_unique<EmbeddedTestServer>(dest_type);
  7933. RegisterDefaultHandlers(destination_server_.get());
  7934. ASSERT_TRUE(destination_server_->Start());
  7935. }
  7936. void VerifyReferrerAfterRedirect(ReferrerPolicy policy,
  7937. const GURL& referrer,
  7938. const GURL& expected) {
  7939. // Create and execute the request: we'll only have a |destination_server_|
  7940. // if the origins are meant to be distinct. Otherwise, we'll use the
  7941. // |origin_server_| for both endpoints.
  7942. GURL destination_url =
  7943. destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
  7944. : origin_server_->GetURL("/echoheader?Referer");
  7945. GURL origin_url =
  7946. origin_server_->GetURL("/server-redirect?" + destination_url.spec());
  7947. TestDelegate d;
  7948. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  7949. origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  7950. req->set_referrer_policy(policy);
  7951. req->SetReferrer(referrer.spec());
  7952. req->Start();
  7953. d.RunUntilComplete();
  7954. EXPECT_EQ(1, d.response_started_count());
  7955. EXPECT_EQ(1, d.received_redirect_count());
  7956. EXPECT_EQ(destination_url, req->url());
  7957. EXPECT_EQ(OK, d.request_status());
  7958. EXPECT_EQ(200, req->response_headers()->response_code());
  7959. EXPECT_EQ(expected.spec(), req->referrer());
  7960. if (expected.is_empty())
  7961. EXPECT_EQ("None", d.data_received());
  7962. else
  7963. EXPECT_EQ(expected.spec(), d.data_received());
  7964. }
  7965. EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
  7966. private:
  7967. std::unique_ptr<EmbeddedTestServer> origin_server_;
  7968. std::unique_ptr<EmbeddedTestServer> destination_server_;
  7969. };
  7970. TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
  7971. InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
  7972. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  7973. VerifyReferrerAfterRedirect(
  7974. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  7975. referrer);
  7976. VerifyReferrerAfterRedirect(
  7977. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  7978. referrer);
  7979. VerifyReferrerAfterRedirect(
  7980. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  7981. referrer);
  7982. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  7983. // The original referrer set on the request is expected to obey the referrer
  7984. // policy and already be stripped to the origin; thus this test case just
  7985. // checks that this policy doesn't cause the referrer to change when following
  7986. // a redirect.
  7987. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  7988. referrer.DeprecatedGetOriginAsURL(),
  7989. referrer.DeprecatedGetOriginAsURL());
  7990. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  7991. referrer, referrer);
  7992. // The original referrer set on the request is expected to obey the referrer
  7993. // policy and already be stripped to the origin; thus this test case just
  7994. // checks that this policy doesn't cause the referrer to change when following
  7995. // a redirect.
  7996. VerifyReferrerAfterRedirect(
  7997. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  7998. referrer.DeprecatedGetOriginAsURL(), referrer.DeprecatedGetOriginAsURL());
  7999. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8000. }
  8001. TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
  8002. InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
  8003. net::EmbeddedTestServer::TYPE_HTTP);
  8004. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  8005. VerifyReferrerAfterRedirect(
  8006. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  8007. referrer);
  8008. VerifyReferrerAfterRedirect(
  8009. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8010. referrer.DeprecatedGetOriginAsURL());
  8011. VerifyReferrerAfterRedirect(
  8012. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8013. referrer.DeprecatedGetOriginAsURL());
  8014. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  8015. // The original referrer set on the request is expected to obey the referrer
  8016. // policy and already be stripped to the origin; thus this test case just
  8017. // checks that this policy doesn't cause the referrer to change when following
  8018. // a redirect.
  8019. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  8020. referrer.DeprecatedGetOriginAsURL(),
  8021. referrer.DeprecatedGetOriginAsURL());
  8022. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  8023. referrer, GURL());
  8024. // The original referrer set on the request is expected to obey the referrer
  8025. // policy and already be stripped to the origin; thus this test case just
  8026. // checks that this policy doesn't cause the referrer to change when following
  8027. // a redirect.
  8028. VerifyReferrerAfterRedirect(
  8029. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  8030. referrer.DeprecatedGetOriginAsURL(), referrer.DeprecatedGetOriginAsURL());
  8031. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8032. }
  8033. TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
  8034. InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
  8035. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  8036. VerifyReferrerAfterRedirect(
  8037. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  8038. referrer);
  8039. VerifyReferrerAfterRedirect(
  8040. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8041. referrer);
  8042. VerifyReferrerAfterRedirect(
  8043. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8044. referrer);
  8045. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  8046. // The original referrer set on the request is expected to obey the referrer
  8047. // policy and already be stripped to the origin; thus this test case just
  8048. // checks that this policy doesn't cause the referrer to change when following
  8049. // a redirect.
  8050. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  8051. referrer.DeprecatedGetOriginAsURL(),
  8052. referrer.DeprecatedGetOriginAsURL());
  8053. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  8054. referrer, referrer);
  8055. // The original referrer set on the request is expected to obey the referrer
  8056. // policy and already be stripped to the origin; thus this test case just
  8057. // checks that this policy doesn't cause the referrer to change when following
  8058. // a redirect.
  8059. VerifyReferrerAfterRedirect(
  8060. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  8061. referrer.DeprecatedGetOriginAsURL(), referrer.DeprecatedGetOriginAsURL());
  8062. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8063. }
  8064. TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
  8065. InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
  8066. net::EmbeddedTestServer::TYPE_HTTPS);
  8067. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  8068. VerifyReferrerAfterRedirect(
  8069. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  8070. referrer);
  8071. VerifyReferrerAfterRedirect(
  8072. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8073. origin_server()->GetURL("/"));
  8074. VerifyReferrerAfterRedirect(
  8075. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8076. origin_server()->GetURL("/"));
  8077. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  8078. // The original referrer set on the request is expected to obey the referrer
  8079. // policy and already be stripped to the origin; thus this test case just
  8080. // checks that this policy doesn't cause the referrer to change when following
  8081. // a redirect.
  8082. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  8083. referrer.DeprecatedGetOriginAsURL(),
  8084. referrer.DeprecatedGetOriginAsURL());
  8085. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  8086. referrer, GURL());
  8087. // The original referrer set on the request is expected to obey the referrer
  8088. // policy and already be stripped to the origin; thus this test case just
  8089. // checks that this policy doesn't cause the referrer to change when following
  8090. // a redirect.
  8091. VerifyReferrerAfterRedirect(
  8092. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  8093. referrer.DeprecatedGetOriginAsURL(), referrer.DeprecatedGetOriginAsURL());
  8094. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8095. }
  8096. TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
  8097. InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
  8098. net::EmbeddedTestServer::TYPE_HTTPS);
  8099. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  8100. VerifyReferrerAfterRedirect(
  8101. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  8102. referrer);
  8103. VerifyReferrerAfterRedirect(
  8104. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8105. origin_server()->GetURL("/"));
  8106. VerifyReferrerAfterRedirect(
  8107. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8108. origin_server()->GetURL("/"));
  8109. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  8110. // The original referrer set on the request is expected to obey the referrer
  8111. // policy and already be stripped to the origin; thus this test case just
  8112. // checks that this policy doesn't cause the referrer to change when following
  8113. // a redirect.
  8114. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  8115. referrer.DeprecatedGetOriginAsURL(),
  8116. referrer.DeprecatedGetOriginAsURL());
  8117. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  8118. referrer, GURL());
  8119. // The original referrer set on the request is expected to obey the referrer
  8120. // policy and already be stripped to the origin; thus this test case just
  8121. // checks that this policy doesn't cause the referrer to change when following
  8122. // a redirect.
  8123. VerifyReferrerAfterRedirect(
  8124. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  8125. referrer.DeprecatedGetOriginAsURL(), referrer.DeprecatedGetOriginAsURL());
  8126. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8127. }
  8128. TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
  8129. InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
  8130. net::EmbeddedTestServer::TYPE_HTTP);
  8131. GURL referrer = origin_server()->GetURL("/path/to/file.html");
  8132. VerifyReferrerAfterRedirect(
  8133. ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE, referrer,
  8134. GURL());
  8135. VerifyReferrerAfterRedirect(
  8136. ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8137. GURL());
  8138. VerifyReferrerAfterRedirect(
  8139. ReferrerPolicy::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
  8140. origin_server()->GetURL("/"));
  8141. VerifyReferrerAfterRedirect(ReferrerPolicy::NEVER_CLEAR, referrer, referrer);
  8142. // The original referrer set on the request is expected to obey the referrer
  8143. // policy and already be stripped to the origin; thus this test case just
  8144. // checks that this policy doesn't cause the referrer to change when following
  8145. // a redirect.
  8146. VerifyReferrerAfterRedirect(ReferrerPolicy::ORIGIN,
  8147. referrer.DeprecatedGetOriginAsURL(),
  8148. referrer.DeprecatedGetOriginAsURL());
  8149. VerifyReferrerAfterRedirect(ReferrerPolicy::CLEAR_ON_TRANSITION_CROSS_ORIGIN,
  8150. referrer, GURL());
  8151. // The original referrer set on the request is expected to obey the referrer
  8152. // policy and already be stripped to the origin, though it should be
  8153. // subsequently cleared during the downgrading redirect.
  8154. VerifyReferrerAfterRedirect(
  8155. ReferrerPolicy::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
  8156. referrer.DeprecatedGetOriginAsURL(), GURL());
  8157. VerifyReferrerAfterRedirect(ReferrerPolicy::NO_REFERRER, GURL(), GURL());
  8158. }
  8159. class HTTPSRequestTest : public TestWithTaskEnvironment {
  8160. public:
  8161. HTTPSRequestTest() {
  8162. auto context_builder = CreateTestURLRequestContextBuilder();
  8163. default_context_ = context_builder->Build();
  8164. }
  8165. ~HTTPSRequestTest() override {
  8166. SetTransportSecurityStateSourceForTesting(nullptr);
  8167. }
  8168. URLRequestContext& default_context() { return *default_context_; }
  8169. private:
  8170. std::unique_ptr<URLRequestContext> default_context_;
  8171. };
  8172. TEST_F(HTTPSRequestTest, HTTPSGetTest) {
  8173. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8174. RegisterDefaultHandlers(&test_server);
  8175. ASSERT_TRUE(test_server.Start());
  8176. TestDelegate d;
  8177. {
  8178. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8179. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8180. TRAFFIC_ANNOTATION_FOR_TESTS));
  8181. r->Start();
  8182. EXPECT_TRUE(r->is_pending());
  8183. d.RunUntilComplete();
  8184. EXPECT_EQ(1, d.response_started_count());
  8185. EXPECT_FALSE(d.received_data_before_response());
  8186. EXPECT_NE(0, d.bytes_received());
  8187. CheckSSLInfo(r->ssl_info());
  8188. EXPECT_EQ(test_server.host_port_pair().host(),
  8189. r->GetResponseRemoteEndpoint().ToStringWithoutPort());
  8190. EXPECT_EQ(test_server.host_port_pair().port(),
  8191. r->GetResponseRemoteEndpoint().port());
  8192. }
  8193. }
  8194. TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
  8195. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8196. test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
  8197. RegisterDefaultHandlers(&test_server);
  8198. ASSERT_TRUE(test_server.Start());
  8199. bool err_allowed = true;
  8200. for (int i = 0; i < 2; i++, err_allowed = !err_allowed) {
  8201. TestDelegate d;
  8202. {
  8203. d.set_allow_certificate_errors(err_allowed);
  8204. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8205. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8206. TRAFFIC_ANNOTATION_FOR_TESTS));
  8207. r->Start();
  8208. EXPECT_TRUE(r->is_pending());
  8209. d.RunUntilComplete();
  8210. EXPECT_EQ(1, d.response_started_count());
  8211. EXPECT_FALSE(d.received_data_before_response());
  8212. EXPECT_TRUE(d.have_certificate_errors());
  8213. if (err_allowed) {
  8214. EXPECT_NE(0, d.bytes_received());
  8215. CheckSSLInfo(r->ssl_info());
  8216. } else {
  8217. EXPECT_EQ(0, d.bytes_received());
  8218. }
  8219. }
  8220. }
  8221. }
  8222. TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
  8223. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8224. test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
  8225. RegisterDefaultHandlers(&test_server);
  8226. ASSERT_TRUE(test_server.Start());
  8227. // Iterate from false to true, just so that we do the opposite of the
  8228. // previous test in order to increase test coverage.
  8229. bool err_allowed = false;
  8230. for (int i = 0; i < 2; i++, err_allowed = !err_allowed) {
  8231. TestDelegate d;
  8232. {
  8233. d.set_allow_certificate_errors(err_allowed);
  8234. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8235. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8236. TRAFFIC_ANNOTATION_FOR_TESTS));
  8237. r->Start();
  8238. EXPECT_TRUE(r->is_pending());
  8239. d.RunUntilComplete();
  8240. EXPECT_EQ(1, d.response_started_count());
  8241. EXPECT_FALSE(d.received_data_before_response());
  8242. EXPECT_TRUE(d.have_certificate_errors());
  8243. if (err_allowed) {
  8244. EXPECT_NE(0, d.bytes_received());
  8245. CheckSSLInfo(r->ssl_info());
  8246. } else {
  8247. EXPECT_EQ(0, d.bytes_received());
  8248. }
  8249. }
  8250. }
  8251. }
  8252. // A TestDelegate used to test that an appropriate net error code is provided
  8253. // when an SSL certificate error occurs.
  8254. class SSLNetErrorTestDelegate : public TestDelegate {
  8255. public:
  8256. void OnSSLCertificateError(URLRequest* request,
  8257. int net_error,
  8258. const SSLInfo& ssl_info,
  8259. bool fatal) override {
  8260. net_error_ = net_error;
  8261. on_ssl_certificate_error_called_ = true;
  8262. TestDelegate::OnSSLCertificateError(request, net_error, ssl_info, fatal);
  8263. }
  8264. bool on_ssl_certificate_error_called() {
  8265. return on_ssl_certificate_error_called_;
  8266. }
  8267. int net_error() { return net_error_; }
  8268. private:
  8269. bool on_ssl_certificate_error_called_ = false;
  8270. int net_error_ = net::OK;
  8271. };
  8272. // Tests that the URLRequest::Delegate receives an appropriate net error code
  8273. // when an SSL certificate error occurs.
  8274. TEST_F(HTTPSRequestTest, SSLNetErrorReportedToDelegate) {
  8275. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8276. test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
  8277. RegisterDefaultHandlers(&test_server);
  8278. ASSERT_TRUE(test_server.Start());
  8279. SSLNetErrorTestDelegate d;
  8280. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8281. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8282. TRAFFIC_ANNOTATION_FOR_TESTS));
  8283. r->Start();
  8284. EXPECT_TRUE(r->is_pending());
  8285. d.RunUntilComplete();
  8286. EXPECT_TRUE(d.on_ssl_certificate_error_called());
  8287. EXPECT_EQ(net::ERR_CERT_DATE_INVALID, d.net_error());
  8288. }
  8289. // TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
  8290. // security state. (see http://crbug.com/550977).
  8291. #if !BUILDFLAG(IS_IOS)
  8292. // This tests that a load of a domain with preloaded HSTS and HPKP with a
  8293. // certificate error sets the |certificate_errors_are_fatal| flag correctly.
  8294. // This flag will cause the interstitial to be fatal.
  8295. TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
  8296. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  8297. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8298. test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
  8299. test_server.ServeFilesFromSourceDirectory("net/data/ssl");
  8300. ASSERT_TRUE(test_server.Start());
  8301. // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
  8302. // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
  8303. // means that we have to use a MockHostResolver in order to direct
  8304. // hsts-hpkp-preloaded.test to the testserver.
  8305. auto host_resolver = std::make_unique<MockHostResolver>();
  8306. host_resolver->rules()->AddRule("hsts-hpkp-preloaded.test",
  8307. test_server.GetIPLiteralString());
  8308. auto context_builder = CreateTestURLRequestContextBuilder();
  8309. context_builder->set_host_resolver(std::move(host_resolver));
  8310. auto context = context_builder->Build();
  8311. TestDelegate d;
  8312. std::unique_ptr<URLRequest> r(context->CreateRequest(
  8313. GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
  8314. test_server.host_port_pair().port())),
  8315. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8316. r->Start();
  8317. EXPECT_TRUE(r->is_pending());
  8318. d.RunUntilComplete();
  8319. EXPECT_EQ(1, d.response_started_count());
  8320. EXPECT_FALSE(d.received_data_before_response());
  8321. EXPECT_TRUE(d.have_certificate_errors());
  8322. EXPECT_TRUE(d.certificate_errors_are_fatal());
  8323. }
  8324. // This tests that cached HTTPS page loads do not cause any updates to the
  8325. // TransportSecurityState.
  8326. TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
  8327. base::test::ScopedFeatureList scoped_feature_list_;
  8328. scoped_feature_list_.InitAndEnableFeature(
  8329. net::features::kStaticKeyPinningEnforcement);
  8330. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  8331. // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
  8332. // matter. It just has to be any error.
  8333. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8334. test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
  8335. test_server.ServeFilesFromSourceDirectory("net/data/ssl");
  8336. ASSERT_TRUE(test_server.Start());
  8337. // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
  8338. // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
  8339. // means that we have to use a MockHostResolver in order to direct
  8340. // hsts-hpkp-preloaded.test to the testserver.
  8341. auto host_resolver = std::make_unique<MockHostResolver>();
  8342. host_resolver->rules()->AddRule("hsts-hpkp-preloaded.test",
  8343. test_server.GetIPLiteralString());
  8344. auto context_builder = CreateTestURLRequestContextBuilder();
  8345. context_builder->set_host_resolver(std::move(host_resolver));
  8346. auto context = context_builder->Build();
  8347. ASSERT_TRUE(context->transport_security_state());
  8348. TransportSecurityState& transport_security_state =
  8349. *context->transport_security_state();
  8350. transport_security_state.EnableStaticPinsForTesting();
  8351. transport_security_state.SetPinningListAlwaysTimelyForTesting(true);
  8352. TransportSecurityState::STSState static_sts_state;
  8353. TransportSecurityState::PKPState static_pkp_state;
  8354. EXPECT_TRUE(transport_security_state.GetStaticSTSState(
  8355. "hsts-hpkp-preloaded.test", &static_sts_state));
  8356. EXPECT_TRUE(transport_security_state.GetStaticPKPState(
  8357. "hsts-hpkp-preloaded.test", &static_pkp_state));
  8358. TransportSecurityState::STSState dynamic_sts_state;
  8359. TransportSecurityState::PKPState dynamic_pkp_state;
  8360. EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
  8361. "hsts-hpkp-preloaded.test", &dynamic_sts_state));
  8362. EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
  8363. "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
  8364. TestDelegate d;
  8365. std::unique_ptr<URLRequest> r(context->CreateRequest(
  8366. GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
  8367. test_server.host_port_pair().port())),
  8368. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8369. r->Start();
  8370. EXPECT_TRUE(r->is_pending());
  8371. d.RunUntilComplete();
  8372. EXPECT_EQ(1, d.response_started_count());
  8373. EXPECT_FALSE(d.received_data_before_response());
  8374. EXPECT_TRUE(d.have_certificate_errors());
  8375. EXPECT_TRUE(d.certificate_errors_are_fatal());
  8376. // Get a fresh copy of the states, and check that they haven't changed.
  8377. TransportSecurityState::STSState new_static_sts_state;
  8378. TransportSecurityState::PKPState new_static_pkp_state;
  8379. EXPECT_TRUE(transport_security_state.GetStaticSTSState(
  8380. "hsts-hpkp-preloaded.test", &new_static_sts_state));
  8381. EXPECT_TRUE(transport_security_state.GetStaticPKPState(
  8382. "hsts-hpkp-preloaded.test", &new_static_pkp_state));
  8383. TransportSecurityState::STSState new_dynamic_sts_state;
  8384. TransportSecurityState::PKPState new_dynamic_pkp_state;
  8385. EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
  8386. "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
  8387. EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
  8388. "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
  8389. EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
  8390. EXPECT_EQ(new_static_sts_state.include_subdomains,
  8391. static_sts_state.include_subdomains);
  8392. EXPECT_EQ(new_static_pkp_state.include_subdomains,
  8393. static_pkp_state.include_subdomains);
  8394. EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
  8395. EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
  8396. static_pkp_state.bad_spki_hashes);
  8397. }
  8398. // Make sure HSTS preserves a POST request's method and body.
  8399. TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
  8400. static const char kData[] = "hello world";
  8401. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8402. RegisterDefaultHandlers(&test_server);
  8403. ASSERT_TRUE(test_server.Start());
  8404. // Per spec, TransportSecurityState expects a domain name, rather than an IP
  8405. // address, so a MockHostResolver is needed to redirect www.somewhere.com to
  8406. // the EmbeddedTestServer.
  8407. auto host_resolver = std::make_unique<MockHostResolver>();
  8408. host_resolver->rules()->AddRule("www.somewhere.com",
  8409. test_server.GetIPLiteralString());
  8410. auto context_builder = CreateTestURLRequestContextBuilder();
  8411. context_builder->set_host_resolver(std::move(host_resolver));
  8412. auto& network_delegate = *context_builder->set_network_delegate(
  8413. std::make_unique<TestNetworkDelegate>());
  8414. auto context = context_builder->Build();
  8415. ASSERT_TRUE(context->transport_security_state());
  8416. TransportSecurityState& transport_security_state =
  8417. *context->transport_security_state();
  8418. // Force https for www.somewhere.com.
  8419. base::Time expiry = base::Time::Now() + base::Days(1000);
  8420. bool include_subdomains = false;
  8421. transport_security_state.AddHSTS("www.somewhere.com", expiry,
  8422. include_subdomains);
  8423. TestDelegate d;
  8424. // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
  8425. // cause a certificate error. Ignore the error.
  8426. d.set_allow_certificate_errors(true);
  8427. std::unique_ptr<URLRequest> req(context->CreateRequest(
  8428. GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
  8429. test_server.host_port_pair().port())),
  8430. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8431. req->set_method("POST");
  8432. req->set_upload(CreateSimpleUploadData(kData));
  8433. req->Start();
  8434. d.RunUntilComplete();
  8435. EXPECT_EQ("https", req->url().scheme());
  8436. EXPECT_EQ("POST", req->method());
  8437. EXPECT_EQ(kData, d.data_received());
  8438. LoadTimingInfo load_timing_info;
  8439. network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
  8440. // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
  8441. TestLoadTimingCacheHitNoNetwork(load_timing_info);
  8442. }
  8443. // Make sure that the CORS headers are added to cross-origin HSTS redirects.
  8444. TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
  8445. static const char kOriginHeaderValue[] = "http://www.example.com";
  8446. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8447. test_server.ServeFilesFromSourceDirectory("net/data/ssl");
  8448. ASSERT_TRUE(test_server.Start());
  8449. auto cert_verifier = std::make_unique<MockCertVerifier>();
  8450. cert_verifier->set_default_result(OK);
  8451. auto context_builder = CreateTestURLRequestContextBuilder();
  8452. context_builder->SetCertVerifier(std::move(cert_verifier));
  8453. auto context = context_builder->Build();
  8454. ASSERT_TRUE(context->transport_security_state());
  8455. TransportSecurityState& transport_security_state =
  8456. *context->transport_security_state();
  8457. base::Time expiry = base::Time::Now() + base::Days(1);
  8458. bool include_subdomains = false;
  8459. transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
  8460. GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
  8461. test_server.host_port_pair().port()));
  8462. GURL::Replacements replacements;
  8463. replacements.SetSchemeStr("https");
  8464. GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
  8465. TestDelegate d;
  8466. std::unique_ptr<URLRequest> req(context->CreateRequest(
  8467. hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8468. // Set Origin header to simulate a cross-origin request.
  8469. HttpRequestHeaders request_headers;
  8470. request_headers.SetHeader("Origin", kOriginHeaderValue);
  8471. req->SetExtraRequestHeaders(request_headers);
  8472. req->Start();
  8473. d.RunUntilRedirect();
  8474. EXPECT_EQ(1, d.received_redirect_count());
  8475. const HttpResponseHeaders* headers = req->response_headers();
  8476. std::string redirect_location;
  8477. EXPECT_TRUE(
  8478. headers->EnumerateHeader(nullptr, "Location", &redirect_location));
  8479. EXPECT_EQ(hsts_https_url.spec(), redirect_location);
  8480. std::string received_cors_header;
  8481. EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Access-Control-Allow-Origin",
  8482. &received_cors_header));
  8483. EXPECT_EQ(kOriginHeaderValue, received_cors_header);
  8484. std::string received_corp_header;
  8485. EXPECT_TRUE(headers->EnumerateHeader(nullptr, "Cross-Origin-Resource-Policy",
  8486. &received_corp_header));
  8487. EXPECT_EQ("Cross-Origin", received_corp_header);
  8488. }
  8489. namespace {
  8490. class SSLClientAuthTestDelegate : public TestDelegate {
  8491. public:
  8492. SSLClientAuthTestDelegate() { set_on_complete(base::DoNothing()); }
  8493. void OnCertificateRequested(URLRequest* request,
  8494. SSLCertRequestInfo* cert_request_info) override {
  8495. on_certificate_requested_count_++;
  8496. std::move(on_certificate_requested_).Run();
  8497. }
  8498. void RunUntilCertificateRequested() {
  8499. base::RunLoop run_loop;
  8500. on_certificate_requested_ = run_loop.QuitClosure();
  8501. run_loop.Run();
  8502. }
  8503. int on_certificate_requested_count() {
  8504. return on_certificate_requested_count_;
  8505. }
  8506. private:
  8507. int on_certificate_requested_count_ = 0;
  8508. base::OnceClosure on_certificate_requested_;
  8509. };
  8510. class TestSSLPrivateKey : public SSLPrivateKey {
  8511. public:
  8512. explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
  8513. : key_(std::move(key)) {}
  8514. void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
  8515. int sign_count() const { return sign_count_; }
  8516. std::string GetProviderName() override { return key_->GetProviderName(); }
  8517. std::vector<uint16_t> GetAlgorithmPreferences() override {
  8518. return key_->GetAlgorithmPreferences();
  8519. }
  8520. void Sign(uint16_t algorithm,
  8521. base::span<const uint8_t> input,
  8522. SignCallback callback) override {
  8523. sign_count_++;
  8524. if (fail_signing_) {
  8525. base::ThreadTaskRunnerHandle::Get()->PostTask(
  8526. FROM_HERE, base::BindOnce(std::move(callback),
  8527. ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
  8528. std::vector<uint8_t>()));
  8529. } else {
  8530. key_->Sign(algorithm, input, std::move(callback));
  8531. }
  8532. }
  8533. private:
  8534. ~TestSSLPrivateKey() override = default;
  8535. scoped_refptr<SSLPrivateKey> key_;
  8536. bool fail_signing_ = false;
  8537. int sign_count_ = 0;
  8538. };
  8539. } // namespace
  8540. // TODO(davidben): Test the rest of the code. Specifically,
  8541. // - Filtering which certificates to select.
  8542. // - Getting a certificate request in an SSL renegotiation sending the
  8543. // HTTP request.
  8544. TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
  8545. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8546. net::SSLServerConfig ssl_config;
  8547. ssl_config.client_cert_type =
  8548. SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
  8549. test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
  8550. RegisterDefaultHandlers(&test_server);
  8551. ASSERT_TRUE(test_server.Start());
  8552. SSLClientAuthTestDelegate d;
  8553. {
  8554. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8555. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8556. TRAFFIC_ANNOTATION_FOR_TESTS));
  8557. r->Start();
  8558. EXPECT_TRUE(r->is_pending());
  8559. d.RunUntilCertificateRequested();
  8560. EXPECT_TRUE(r->is_pending());
  8561. EXPECT_EQ(1, d.on_certificate_requested_count());
  8562. EXPECT_FALSE(d.received_data_before_response());
  8563. EXPECT_EQ(0, d.bytes_received());
  8564. // Send no certificate.
  8565. // TODO(davidben): Get temporary client cert import (with keys) working on
  8566. // all platforms so we can test sending a cert as well.
  8567. r->ContinueWithCertificate(nullptr, nullptr);
  8568. d.RunUntilComplete();
  8569. EXPECT_EQ(OK, d.request_status());
  8570. EXPECT_EQ(1, d.response_started_count());
  8571. EXPECT_FALSE(d.received_data_before_response());
  8572. EXPECT_NE(0, d.bytes_received());
  8573. }
  8574. }
  8575. TEST_F(HTTPSRequestTest, ClientAuth) {
  8576. std::unique_ptr<FakeClientCertIdentity> identity =
  8577. FakeClientCertIdentity::CreateFromCertAndKeyFiles(
  8578. GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
  8579. ASSERT_TRUE(identity);
  8580. scoped_refptr<TestSSLPrivateKey> private_key =
  8581. base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
  8582. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8583. net::SSLServerConfig ssl_config;
  8584. ssl_config.client_cert_type =
  8585. SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
  8586. test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
  8587. RegisterDefaultHandlers(&test_server);
  8588. ASSERT_TRUE(test_server.Start());
  8589. {
  8590. SSLClientAuthTestDelegate d;
  8591. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8592. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8593. TRAFFIC_ANNOTATION_FOR_TESTS));
  8594. r->Start();
  8595. EXPECT_TRUE(r->is_pending());
  8596. d.RunUntilCertificateRequested();
  8597. EXPECT_TRUE(r->is_pending());
  8598. EXPECT_EQ(1, d.on_certificate_requested_count());
  8599. EXPECT_FALSE(d.received_data_before_response());
  8600. EXPECT_EQ(0, d.bytes_received());
  8601. // Send a certificate.
  8602. r->ContinueWithCertificate(identity->certificate(), private_key);
  8603. d.RunUntilComplete();
  8604. EXPECT_EQ(OK, d.request_status());
  8605. EXPECT_EQ(1, d.response_started_count());
  8606. EXPECT_FALSE(d.received_data_before_response());
  8607. EXPECT_NE(0, d.bytes_received());
  8608. // The private key should have been used.
  8609. EXPECT_EQ(1, private_key->sign_count());
  8610. }
  8611. // Close all connections and clear the session cache to force a new handshake.
  8612. default_context()
  8613. .http_transaction_factory()
  8614. ->GetSession()
  8615. ->CloseAllConnections(ERR_FAILED, "Very good reason");
  8616. default_context()
  8617. .http_transaction_factory()
  8618. ->GetSession()
  8619. ->ClearSSLSessionCache();
  8620. // Connecting again should not call OnCertificateRequested. The identity is
  8621. // taken from the client auth cache.
  8622. {
  8623. SSLClientAuthTestDelegate d;
  8624. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8625. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8626. TRAFFIC_ANNOTATION_FOR_TESTS));
  8627. r->Start();
  8628. EXPECT_TRUE(r->is_pending());
  8629. d.RunUntilComplete();
  8630. EXPECT_EQ(OK, d.request_status());
  8631. EXPECT_EQ(0, d.on_certificate_requested_count());
  8632. EXPECT_FALSE(d.received_data_before_response());
  8633. EXPECT_EQ(1, d.response_started_count());
  8634. EXPECT_FALSE(d.received_data_before_response());
  8635. EXPECT_NE(0, d.bytes_received());
  8636. // The private key should have been used.
  8637. EXPECT_EQ(2, private_key->sign_count());
  8638. }
  8639. }
  8640. // Test that private keys that fail to sign anything get evicted from the cache.
  8641. TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
  8642. std::unique_ptr<FakeClientCertIdentity> identity =
  8643. FakeClientCertIdentity::CreateFromCertAndKeyFiles(
  8644. GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
  8645. ASSERT_TRUE(identity);
  8646. scoped_refptr<TestSSLPrivateKey> private_key =
  8647. base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
  8648. private_key->set_fail_signing(true);
  8649. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8650. net::SSLServerConfig ssl_config;
  8651. ssl_config.client_cert_type =
  8652. SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
  8653. test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
  8654. RegisterDefaultHandlers(&test_server);
  8655. ASSERT_TRUE(test_server.Start());
  8656. {
  8657. SSLClientAuthTestDelegate d;
  8658. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8659. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8660. TRAFFIC_ANNOTATION_FOR_TESTS));
  8661. r->Start();
  8662. EXPECT_TRUE(r->is_pending());
  8663. d.RunUntilCertificateRequested();
  8664. EXPECT_TRUE(r->is_pending());
  8665. EXPECT_EQ(1, d.on_certificate_requested_count());
  8666. EXPECT_FALSE(d.received_data_before_response());
  8667. EXPECT_EQ(0, d.bytes_received());
  8668. // Send a certificate.
  8669. r->ContinueWithCertificate(identity->certificate(), private_key);
  8670. d.RunUntilComplete();
  8671. // The private key cannot sign anything, so we report an error.
  8672. EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
  8673. EXPECT_EQ(1, d.response_started_count());
  8674. EXPECT_FALSE(d.received_data_before_response());
  8675. EXPECT_EQ(0, d.bytes_received());
  8676. // The private key should have been used.
  8677. EXPECT_EQ(1, private_key->sign_count());
  8678. }
  8679. // Close all connections and clear the session cache to force a new handshake.
  8680. default_context()
  8681. .http_transaction_factory()
  8682. ->GetSession()
  8683. ->CloseAllConnections(ERR_FAILED, "Very good reason");
  8684. default_context()
  8685. .http_transaction_factory()
  8686. ->GetSession()
  8687. ->ClearSSLSessionCache();
  8688. // The bad identity should have been evicted from the cache, so connecting
  8689. // again should call OnCertificateRequested again.
  8690. {
  8691. SSLClientAuthTestDelegate d;
  8692. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8693. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8694. TRAFFIC_ANNOTATION_FOR_TESTS));
  8695. r->Start();
  8696. EXPECT_TRUE(r->is_pending());
  8697. d.RunUntilCertificateRequested();
  8698. EXPECT_TRUE(r->is_pending());
  8699. EXPECT_EQ(1, d.on_certificate_requested_count());
  8700. EXPECT_FALSE(d.received_data_before_response());
  8701. EXPECT_EQ(0, d.bytes_received());
  8702. // There should have been no additional uses of the private key.
  8703. EXPECT_EQ(1, private_key->sign_count());
  8704. }
  8705. }
  8706. // Test that cached private keys that fail to sign anything trigger a
  8707. // retry. This is so we handle unplugged smartcards
  8708. // gracefully. https://crbug.com/813022.
  8709. TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
  8710. std::unique_ptr<FakeClientCertIdentity> identity =
  8711. FakeClientCertIdentity::CreateFromCertAndKeyFiles(
  8712. GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
  8713. ASSERT_TRUE(identity);
  8714. scoped_refptr<TestSSLPrivateKey> private_key =
  8715. base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
  8716. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
  8717. net::SSLServerConfig ssl_config;
  8718. ssl_config.client_cert_type =
  8719. SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
  8720. test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
  8721. RegisterDefaultHandlers(&test_server);
  8722. ASSERT_TRUE(test_server.Start());
  8723. // Connect with a client certificate to put it in the client auth cache.
  8724. {
  8725. SSLClientAuthTestDelegate d;
  8726. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8727. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8728. TRAFFIC_ANNOTATION_FOR_TESTS));
  8729. r->Start();
  8730. EXPECT_TRUE(r->is_pending());
  8731. d.RunUntilCertificateRequested();
  8732. EXPECT_TRUE(r->is_pending());
  8733. EXPECT_EQ(1, d.on_certificate_requested_count());
  8734. EXPECT_FALSE(d.received_data_before_response());
  8735. EXPECT_EQ(0, d.bytes_received());
  8736. r->ContinueWithCertificate(identity->certificate(), private_key);
  8737. d.RunUntilComplete();
  8738. EXPECT_EQ(OK, d.request_status());
  8739. EXPECT_EQ(1, d.response_started_count());
  8740. EXPECT_FALSE(d.received_data_before_response());
  8741. EXPECT_NE(0, d.bytes_received());
  8742. // The private key should have been used.
  8743. EXPECT_EQ(1, private_key->sign_count());
  8744. }
  8745. // Close all connections and clear the session cache to force a new handshake.
  8746. default_context()
  8747. .http_transaction_factory()
  8748. ->GetSession()
  8749. ->CloseAllConnections(ERR_FAILED, "Very good reason");
  8750. default_context()
  8751. .http_transaction_factory()
  8752. ->GetSession()
  8753. ->ClearSSLSessionCache();
  8754. // Cause the private key to fail. Connecting again should attempt to use it,
  8755. // notice the failure, and then request a new identity via
  8756. // OnCertificateRequested.
  8757. private_key->set_fail_signing(true);
  8758. {
  8759. SSLClientAuthTestDelegate d;
  8760. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8761. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  8762. TRAFFIC_ANNOTATION_FOR_TESTS));
  8763. r->Start();
  8764. EXPECT_TRUE(r->is_pending());
  8765. d.RunUntilCertificateRequested();
  8766. EXPECT_TRUE(r->is_pending());
  8767. // There was an additional signing call on the private key (the one which
  8768. // failed).
  8769. EXPECT_EQ(2, private_key->sign_count());
  8770. // That caused another OnCertificateRequested call.
  8771. EXPECT_EQ(1, d.on_certificate_requested_count());
  8772. EXPECT_FALSE(d.received_data_before_response());
  8773. EXPECT_EQ(0, d.bytes_received());
  8774. }
  8775. }
  8776. TEST_F(HTTPSRequestTest, ResumeTest) {
  8777. // Test that we attempt resume sessions when making two connections to the
  8778. // same host.
  8779. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  8780. RegisterDefaultHandlers(&test_server);
  8781. ASSERT_TRUE(test_server.Start());
  8782. const auto url = test_server.GetURL("/");
  8783. default_context()
  8784. .http_transaction_factory()
  8785. ->GetSession()
  8786. ->ClearSSLSessionCache();
  8787. {
  8788. TestDelegate d;
  8789. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8790. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8791. r->Start();
  8792. EXPECT_TRUE(r->is_pending());
  8793. d.RunUntilComplete();
  8794. EXPECT_EQ(1, d.response_started_count());
  8795. EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
  8796. }
  8797. reinterpret_cast<HttpCache*>(default_context().http_transaction_factory())
  8798. ->CloseAllConnections(ERR_FAILED, "Very good reason");
  8799. {
  8800. TestDelegate d;
  8801. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8802. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8803. r->Start();
  8804. EXPECT_TRUE(r->is_pending());
  8805. d.RunUntilComplete();
  8806. EXPECT_EQ(1, d.response_started_count());
  8807. EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, r->ssl_info().handshake_type);
  8808. }
  8809. }
  8810. // Test that sessions aren't resumed across URLRequestContexts.
  8811. TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
  8812. // Start a server.
  8813. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  8814. RegisterDefaultHandlers(&test_server);
  8815. ASSERT_TRUE(test_server.Start());
  8816. const auto url = test_server.GetURL("/");
  8817. // Connect to the server once. This will add an entry to the session cache.
  8818. {
  8819. TestDelegate d;
  8820. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8821. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8822. r->Start();
  8823. EXPECT_TRUE(r->is_pending());
  8824. d.RunUntilComplete();
  8825. EXPECT_EQ(1, d.response_started_count());
  8826. EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
  8827. }
  8828. // Clear the socket pools and connect again. This should resume the previous
  8829. // session.
  8830. default_context()
  8831. .http_transaction_factory()
  8832. ->GetSession()
  8833. ->CloseAllConnections(ERR_FAILED, /*net_log_reason_utf8=*/"");
  8834. {
  8835. TestDelegate d;
  8836. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8837. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8838. r->Start();
  8839. EXPECT_TRUE(r->is_pending());
  8840. d.RunUntilComplete();
  8841. EXPECT_EQ(1, d.response_started_count());
  8842. EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, r->ssl_info().handshake_type);
  8843. }
  8844. // Now fetch on a new URLRequestContext. This should not resume the session.
  8845. auto context_builder = CreateTestURLRequestContextBuilder();
  8846. auto other_context = context_builder->Build();
  8847. {
  8848. TestDelegate d;
  8849. std::unique_ptr<URLRequest> r(other_context->CreateRequest(
  8850. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8851. r->Start();
  8852. EXPECT_TRUE(r->is_pending());
  8853. d.RunUntilComplete();
  8854. EXPECT_EQ(1, d.response_started_count());
  8855. EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
  8856. }
  8857. }
  8858. // Test that sessions started with privacy mode enabled cannot be resumed when
  8859. // it is disabled, and vice versa.
  8860. TEST_F(HTTPSRequestTest, NoSessionResumptionBetweenPrivacyModes) {
  8861. // Start a server.
  8862. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  8863. RegisterDefaultHandlers(&test_server);
  8864. ASSERT_TRUE(test_server.Start());
  8865. const auto url = test_server.GetURL("/");
  8866. auto ConnectAndCheckHandshake = [this, url](bool allow_credentials,
  8867. auto expected_handshake) {
  8868. // Construct request and indirectly set the privacy mode.
  8869. TestDelegate d;
  8870. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  8871. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  8872. r->set_allow_credentials(allow_credentials);
  8873. // Start the request and check the SSL handshake type.
  8874. r->Start();
  8875. EXPECT_TRUE(r->is_pending());
  8876. d.RunUntilComplete();
  8877. EXPECT_EQ(1, d.response_started_count());
  8878. EXPECT_EQ(expected_handshake, r->ssl_info().handshake_type);
  8879. };
  8880. // Exhaustively check all pairs of privacy mode values. Note that we are using
  8881. // allow_credentials to indirectly enable/disable privacy mode.
  8882. const bool kAllowCredentialsValues[] = {false, true};
  8883. for (const auto allow_creds_1 : kAllowCredentialsValues) {
  8884. for (const auto allow_creds_2 : kAllowCredentialsValues) {
  8885. SCOPED_TRACE(base::StringPrintf("allow_creds_1=%d, allow_creds_2=%d",
  8886. allow_creds_1, allow_creds_2));
  8887. // The session cache starts off empty, so we expect a full handshake.
  8888. ConnectAndCheckHandshake(allow_creds_1, SSLInfo::HANDSHAKE_FULL);
  8889. // The second handshake depends on whether we are using the same session
  8890. // cache as the first request.
  8891. ConnectAndCheckHandshake(allow_creds_2, allow_creds_1 == allow_creds_2
  8892. ? SSLInfo::HANDSHAKE_RESUME
  8893. : SSLInfo::HANDSHAKE_FULL);
  8894. // Flush both session caches.
  8895. auto* network_session =
  8896. default_context().http_transaction_factory()->GetSession();
  8897. network_session->ClearSSLSessionCache();
  8898. }
  8899. }
  8900. }
  8901. class HTTPSFallbackTest : public TestWithTaskEnvironment {
  8902. public:
  8903. HTTPSFallbackTest() {
  8904. auto context_builder = CreateTestURLRequestContextBuilder();
  8905. context_builder->set_ssl_config_service(
  8906. std::make_unique<TestSSLConfigService>(SSLContextConfig()));
  8907. context_ = context_builder->Build();
  8908. }
  8909. ~HTTPSFallbackTest() override = default;
  8910. protected:
  8911. void DoFallbackTest(const SSLServerConfig& ssl_config) {
  8912. DCHECK(!request_);
  8913. delegate_.set_allow_certificate_errors(true);
  8914. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  8915. test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
  8916. ASSERT_TRUE(test_server.Start());
  8917. request_ =
  8918. context_->CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
  8919. &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
  8920. request_->Start();
  8921. delegate_.RunUntilComplete();
  8922. }
  8923. void ExpectConnection(int version) {
  8924. EXPECT_EQ(1, delegate_.response_started_count());
  8925. EXPECT_NE(0, delegate_.bytes_received());
  8926. EXPECT_EQ(version, SSLConnectionStatusToVersion(
  8927. request_->ssl_info().connection_status));
  8928. }
  8929. void ExpectFailure(int error) {
  8930. EXPECT_EQ(1, delegate_.response_started_count());
  8931. EXPECT_EQ(error, delegate_.request_status());
  8932. }
  8933. private:
  8934. TestDelegate delegate_;
  8935. std::unique_ptr<URLRequestContext> context_;
  8936. std::unique_ptr<URLRequest> request_;
  8937. };
  8938. // Tests the TLS 1.0 fallback doesn't happen.
  8939. TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
  8940. net::SSLServerConfig ssl_config;
  8941. ssl_config.client_hello_callback_for_testing =
  8942. base::BindRepeating([](const SSL_CLIENT_HELLO* client_hello) {
  8943. // Reject ClientHellos with version >= TLS 1.1.
  8944. return client_hello->version <= TLS1_VERSION;
  8945. });
  8946. ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_config));
  8947. ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
  8948. }
  8949. // Tests the TLS 1.1 fallback doesn't happen.
  8950. TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
  8951. net::SSLServerConfig ssl_config;
  8952. ssl_config.client_hello_callback_for_testing =
  8953. base::BindRepeating([](const SSL_CLIENT_HELLO* client_hello) {
  8954. // Reject ClientHellos with version >= TLS 1.2.
  8955. return client_hello->version <= TLS1_1_VERSION;
  8956. });
  8957. ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_config));
  8958. ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
  8959. }
  8960. // Tests the TLS 1.2 fallback doesn't happen.
  8961. TEST_F(HTTPSFallbackTest, TLSv1_2NoFallback) {
  8962. net::SSLServerConfig ssl_config;
  8963. ssl_config.client_hello_callback_for_testing =
  8964. base::BindRepeating([](const SSL_CLIENT_HELLO* client_hello) {
  8965. // Reject ClientHellos with a supported_versions extension. TLS 1.3 is
  8966. // signaled via an extension rather than the legacy version field.
  8967. const uint8_t* data;
  8968. size_t len;
  8969. return !SSL_early_callback_ctx_extension_get(
  8970. client_hello, TLSEXT_TYPE_supported_versions, &data, &len);
  8971. });
  8972. ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_config));
  8973. ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
  8974. }
  8975. class HTTPSSessionTest : public TestWithTaskEnvironment {
  8976. public:
  8977. HTTPSSessionTest() {
  8978. auto context_builder = CreateTestURLRequestContextBuilder();
  8979. context_builder->SetCertVerifier(std::make_unique<MockCertVerifier>());
  8980. default_context_ = context_builder->Build();
  8981. default_cert_verifier().set_default_result(OK);
  8982. }
  8983. ~HTTPSSessionTest() override = default;
  8984. URLRequestContext& default_context() { return *default_context_; }
  8985. MockCertVerifier& default_cert_verifier() {
  8986. // This cast is safe because we provided a MockCertVerifier in the ctor.
  8987. return *static_cast<MockCertVerifier*>(default_context_->cert_verifier());
  8988. }
  8989. private:
  8990. std::unique_ptr<URLRequestContext> default_context_;
  8991. };
  8992. // Tests that session resumption is not attempted if an invalid certificate
  8993. // is presented.
  8994. TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
  8995. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  8996. RegisterDefaultHandlers(&test_server);
  8997. ASSERT_TRUE(test_server.Start());
  8998. const auto url = test_server.GetURL("/");
  8999. default_context()
  9000. .http_transaction_factory()
  9001. ->GetSession()
  9002. ->ClearSSLSessionCache();
  9003. // Simulate the certificate being expired and attempt a connection.
  9004. default_cert_verifier().set_default_result(ERR_CERT_DATE_INVALID);
  9005. {
  9006. TestDelegate d;
  9007. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  9008. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  9009. r->Start();
  9010. EXPECT_TRUE(r->is_pending());
  9011. d.RunUntilComplete();
  9012. EXPECT_EQ(1, d.response_started_count());
  9013. }
  9014. reinterpret_cast<HttpCache*>(default_context().http_transaction_factory())
  9015. ->CloseAllConnections(ERR_FAILED, "Very good reason");
  9016. // Now change the certificate to be acceptable (so that the response is
  9017. // loaded), and ensure that no session id is presented to the peer.
  9018. default_cert_verifier().set_default_result(OK);
  9019. {
  9020. TestDelegate d;
  9021. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  9022. url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  9023. r->Start();
  9024. EXPECT_TRUE(r->is_pending());
  9025. d.RunUntilComplete();
  9026. EXPECT_EQ(1, d.response_started_count());
  9027. EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, r->ssl_info().handshake_type);
  9028. }
  9029. }
  9030. // Interceptor to check that secure DNS has been disabled. Secure DNS should be
  9031. // disabled for any network fetch triggered during certificate verification as
  9032. // it could cause a deadlock.
  9033. class SecureDnsInterceptor : public net::URLRequestInterceptor {
  9034. public:
  9035. SecureDnsInterceptor() = default;
  9036. ~SecureDnsInterceptor() override = default;
  9037. private:
  9038. // URLRequestInterceptor implementation:
  9039. std::unique_ptr<net::URLRequestJob> MaybeInterceptRequest(
  9040. net::URLRequest* request) const override {
  9041. EXPECT_EQ(SecureDnsPolicy::kDisable, request->secure_dns_policy());
  9042. return nullptr;
  9043. }
  9044. };
  9045. class HTTPSCertNetFetchingTest : public HTTPSRequestTest {
  9046. public:
  9047. HTTPSCertNetFetchingTest() = default;
  9048. void SetUp() override {
  9049. auto context_builder = CreateTestURLRequestContextBuilder();
  9050. cert_net_fetcher_ = base::MakeRefCounted<CertNetFetcherURLRequest>();
  9051. context_builder->SetCertVerifier(
  9052. CertVerifier::CreateDefault(cert_net_fetcher_));
  9053. context_ = context_builder->Build();
  9054. net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
  9055. "http", "127.0.0.1", std::make_unique<SecureDnsInterceptor>());
  9056. cert_net_fetcher_->SetURLRequestContext(context_.get());
  9057. context_->cert_verifier()->SetConfig(GetCertVerifierConfig());
  9058. }
  9059. void TearDown() override {
  9060. cert_net_fetcher_->Shutdown();
  9061. net::URLRequestFilter::GetInstance()->ClearHandlers();
  9062. }
  9063. void DoConnectionWithDelegate(
  9064. const EmbeddedTestServer::ServerCertificateConfig& cert_config,
  9065. TestDelegate* delegate,
  9066. SSLInfo* out_ssl_info) {
  9067. // Always overwrite |out_ssl_info|.
  9068. out_ssl_info->Reset();
  9069. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  9070. test_server.SetSSLConfig(cert_config);
  9071. RegisterDefaultHandlers(&test_server);
  9072. ASSERT_TRUE(test_server.Start());
  9073. delegate->set_allow_certificate_errors(true);
  9074. std::unique_ptr<URLRequest> r(
  9075. context_->CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
  9076. delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  9077. r->Start();
  9078. delegate->RunUntilComplete();
  9079. EXPECT_EQ(1, delegate->response_started_count());
  9080. *out_ssl_info = r->ssl_info();
  9081. }
  9082. void DoConnection(
  9083. const EmbeddedTestServer::ServerCertificateConfig& cert_config,
  9084. CertStatus* out_cert_status) {
  9085. // Always overwrite |out_cert_status|.
  9086. *out_cert_status = 0;
  9087. TestDelegate d;
  9088. SSLInfo ssl_info;
  9089. ASSERT_NO_FATAL_FAILURE(
  9090. DoConnectionWithDelegate(cert_config, &d, &ssl_info));
  9091. *out_cert_status = ssl_info.cert_status;
  9092. }
  9093. protected:
  9094. // GetCertVerifierConfig() configures the URLRequestContext that will be used
  9095. // for making connections to the testserver. This can be overridden in test
  9096. // subclasses for different behaviour.
  9097. virtual CertVerifier::Config GetCertVerifierConfig() {
  9098. CertVerifier::Config config;
  9099. return config;
  9100. }
  9101. scoped_refptr<CertNetFetcherURLRequest> cert_net_fetcher_;
  9102. std::unique_ptr<CertVerifier> cert_verifier_;
  9103. std::unique_ptr<URLRequestContext> context_;
  9104. };
  9105. // The test EV policy OID used for generated certs.
  9106. static const char kEVTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
  9107. class HTTPSEVTest : public HTTPSCertNetFetchingTest {
  9108. public:
  9109. void SetUp() override {
  9110. HTTPSCertNetFetchingTest::SetUp();
  9111. scoped_refptr<X509Certificate> root_cert =
  9112. ImportCertFromFile(GetTestCertsDirectory(), "root_ca_cert.pem");
  9113. ASSERT_TRUE(root_cert);
  9114. ev_test_policy_ = std::make_unique<ScopedTestEVPolicy>(
  9115. EVRootCAMetadata::GetInstance(),
  9116. X509Certificate::CalculateFingerprint256(root_cert->cert_buffer()),
  9117. kEVTestCertPolicy);
  9118. }
  9119. void TearDown() override { HTTPSCertNetFetchingTest::TearDown(); }
  9120. private:
  9121. std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
  9122. };
  9123. class HTTPSOCSPTest : public HTTPSCertNetFetchingTest {
  9124. public:
  9125. CertVerifier::Config GetCertVerifierConfig() override {
  9126. CertVerifier::Config config;
  9127. config.enable_rev_checking = true;
  9128. return config;
  9129. }
  9130. };
  9131. static bool UsingBuiltinCertVerifier() {
  9132. #if BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  9133. return true;
  9134. #else
  9135. #if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
  9136. if (base::FeatureList::IsEnabled(features::kCertVerifierBuiltinFeature))
  9137. return true;
  9138. #endif
  9139. #if BUILDFLAG(CHROME_ROOT_STORE_SUPPORTED)
  9140. if (base::FeatureList::IsEnabled(features::kChromeRootStoreUsed))
  9141. return true;
  9142. #endif
  9143. return false;
  9144. #endif
  9145. }
  9146. // SystemSupportsHardFailRevocationChecking returns true iff the current
  9147. // operating system supports revocation checking and can distinguish between
  9148. // situations where a given certificate lacks any revocation information (eg:
  9149. // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
  9150. // revocation information cannot be obtained (eg: the CRL was unreachable).
  9151. // If it does not, then tests which rely on 'hard fail' behaviour should be
  9152. // skipped.
  9153. static bool SystemSupportsHardFailRevocationChecking() {
  9154. if (UsingBuiltinCertVerifier())
  9155. return true;
  9156. #if BUILDFLAG(IS_WIN)
  9157. return true;
  9158. #else
  9159. return false;
  9160. #endif
  9161. }
  9162. // SystemUsesChromiumEVMetadata returns true iff the current operating system
  9163. // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
  9164. // several tests are effected because our testing EV certificate won't be
  9165. // recognised as EV.
  9166. static bool SystemUsesChromiumEVMetadata() {
  9167. if (UsingBuiltinCertVerifier())
  9168. return true;
  9169. #if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
  9170. return true;
  9171. #else
  9172. return false;
  9173. #endif
  9174. }
  9175. static bool SystemSupportsOCSP() {
  9176. #if BUILDFLAG(IS_ANDROID)
  9177. // Unsupported, see http://crbug.com/117478.
  9178. return false;
  9179. #else
  9180. return true;
  9181. #endif
  9182. }
  9183. static bool SystemSupportsOCSPStapling() {
  9184. if (UsingBuiltinCertVerifier())
  9185. return true;
  9186. #if BUILDFLAG(IS_ANDROID)
  9187. return false;
  9188. #else
  9189. return true;
  9190. #endif
  9191. }
  9192. static bool SystemSupportsCRLSets() {
  9193. if (UsingBuiltinCertVerifier())
  9194. return true;
  9195. #if BUILDFLAG(IS_ANDROID)
  9196. return false;
  9197. #else
  9198. return true;
  9199. #endif
  9200. }
  9201. TEST_F(HTTPSEVTest, EVCheckNoOCSP) {
  9202. if (!SystemUsesChromiumEVMetadata()) {
  9203. LOG(WARNING) << "Skipping test because system doesn't support EV";
  9204. return;
  9205. }
  9206. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9207. cert_config.policy_oids = {kEVTestCertPolicy};
  9208. CertStatus cert_status;
  9209. DoConnection(cert_config, &cert_status);
  9210. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9211. EXPECT_EQ(SystemUsesChromiumEVMetadata(),
  9212. static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
  9213. EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9214. }
  9215. TEST_F(HTTPSOCSPTest, Valid) {
  9216. if (!SystemSupportsOCSP()) {
  9217. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9218. return;
  9219. }
  9220. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9221. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9222. {{OCSPRevocationStatus::GOOD,
  9223. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9224. CertStatus cert_status;
  9225. DoConnection(cert_config, &cert_status);
  9226. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9227. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9228. }
  9229. TEST_F(HTTPSOCSPTest, Revoked) {
  9230. if (!SystemSupportsOCSP()) {
  9231. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9232. return;
  9233. }
  9234. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9235. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9236. {{OCSPRevocationStatus::REVOKED,
  9237. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9238. CertStatus cert_status;
  9239. DoConnection(cert_config, &cert_status);
  9240. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9241. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9242. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9243. }
  9244. TEST_F(HTTPSOCSPTest, Invalid) {
  9245. if (!SystemSupportsOCSP()) {
  9246. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9247. return;
  9248. }
  9249. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9250. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9251. EmbeddedTestServer::OCSPConfig::ResponseType::kInvalidResponse);
  9252. CertStatus cert_status;
  9253. DoConnection(cert_config, &cert_status);
  9254. // Without a positive OCSP response, we shouldn't show the EV status, but also
  9255. // should not show any revocation checking errors.
  9256. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9257. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9258. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9259. }
  9260. TEST_F(HTTPSOCSPTest, IntermediateValid) {
  9261. if (!SystemSupportsOCSP()) {
  9262. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9263. return;
  9264. }
  9265. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9266. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9267. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9268. {{OCSPRevocationStatus::GOOD,
  9269. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9270. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9271. {{OCSPRevocationStatus::GOOD,
  9272. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9273. CertStatus cert_status;
  9274. DoConnection(cert_config, &cert_status);
  9275. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9276. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9277. }
  9278. TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
  9279. if (!SystemSupportsOCSP()) {
  9280. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9281. return;
  9282. }
  9283. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9284. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9285. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9286. {{OCSPRevocationStatus::GOOD,
  9287. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9288. // Use an OCSP response for the intermediate that would be too old for a leaf
  9289. // cert, but is still valid for an intermediate.
  9290. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9291. {{OCSPRevocationStatus::REVOKED,
  9292. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong}});
  9293. CertStatus cert_status;
  9294. DoConnection(cert_config, &cert_status);
  9295. if (UsingBuiltinCertVerifier()) {
  9296. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9297. } else {
  9298. #if BUILDFLAG(IS_WIN)
  9299. // TODO(mattm): Seems to be flaky on Windows. Either returns
  9300. // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION (which gets masked off due to
  9301. // soft-fail), or CERT_STATUS_REVOKED.
  9302. EXPECT_THAT(cert_status & CERT_STATUS_ALL_ERRORS,
  9303. AnyOf(0u, CERT_STATUS_REVOKED));
  9304. #else
  9305. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9306. #endif
  9307. }
  9308. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9309. }
  9310. TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
  9311. if (!SystemSupportsOCSP()) {
  9312. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9313. return;
  9314. }
  9315. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9316. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9317. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9318. {{OCSPRevocationStatus::GOOD,
  9319. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9320. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9321. {{OCSPRevocationStatus::REVOKED,
  9322. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLonger}});
  9323. CertStatus cert_status;
  9324. DoConnection(cert_config, &cert_status);
  9325. if (UsingBuiltinCertVerifier()) {
  9326. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9327. } else {
  9328. #if BUILDFLAG(IS_WIN)
  9329. // TODO(mattm): Seems to be flaky on Windows. Either returns
  9330. // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION (which gets masked off due to
  9331. // soft-fail), or CERT_STATUS_REVOKED.
  9332. EXPECT_THAT(cert_status & CERT_STATUS_ALL_ERRORS,
  9333. AnyOf(0u, CERT_STATUS_REVOKED));
  9334. #else
  9335. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9336. #endif
  9337. }
  9338. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9339. }
  9340. TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
  9341. if (!SystemSupportsOCSP()) {
  9342. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9343. return;
  9344. }
  9345. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9346. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9347. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9348. {{OCSPRevocationStatus::GOOD,
  9349. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9350. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9351. {{OCSPRevocationStatus::REVOKED,
  9352. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9353. CertStatus cert_status;
  9354. DoConnection(cert_config, &cert_status);
  9355. if (UsingBuiltinCertVerifier()) {
  9356. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9357. } else {
  9358. #if BUILDFLAG(IS_WIN)
  9359. // TODO(mattm): Seems to be flaky on Windows. Either returns
  9360. // CERT_STATUS_UNABLE_TO_CHECK_REVOCATION (which gets masked off due to
  9361. // soft-fail), or CERT_STATUS_REVOKED.
  9362. EXPECT_THAT(cert_status & CERT_STATUS_ALL_ERRORS,
  9363. AnyOf(0u, CERT_STATUS_REVOKED));
  9364. #else
  9365. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9366. #endif
  9367. }
  9368. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9369. }
  9370. TEST_F(HTTPSOCSPTest, ValidStapled) {
  9371. if (!SystemSupportsOCSPStapling()) {
  9372. LOG(WARNING)
  9373. << "Skipping test because system doesn't support OCSP stapling";
  9374. return;
  9375. }
  9376. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9377. // AIA OCSP url is included, but does not return a successful ocsp response.
  9378. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9379. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9380. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9381. {{OCSPRevocationStatus::GOOD,
  9382. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9383. CertStatus cert_status;
  9384. DoConnection(cert_config, &cert_status);
  9385. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9386. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9387. }
  9388. TEST_F(HTTPSOCSPTest, RevokedStapled) {
  9389. if (!SystemSupportsOCSPStapling()) {
  9390. LOG(WARNING)
  9391. << "Skipping test because system doesn't support OCSP stapling";
  9392. return;
  9393. }
  9394. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9395. // AIA OCSP url is included, but does not return a successful ocsp response.
  9396. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9397. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9398. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9399. {{OCSPRevocationStatus::REVOKED,
  9400. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9401. CertStatus cert_status;
  9402. DoConnection(cert_config, &cert_status);
  9403. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9404. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9405. }
  9406. TEST_F(HTTPSOCSPTest, OldStapledAndInvalidAIA) {
  9407. if (!SystemSupportsOCSPStapling()) {
  9408. LOG(WARNING)
  9409. << "Skipping test because system doesn't support OCSP stapling";
  9410. return;
  9411. }
  9412. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9413. // Stapled response indicates good, but is too old.
  9414. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9415. {{OCSPRevocationStatus::GOOD,
  9416. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}});
  9417. // AIA OCSP url is included, but does not return a successful ocsp response.
  9418. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9419. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9420. CertStatus cert_status;
  9421. DoConnection(cert_config, &cert_status);
  9422. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9423. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9424. }
  9425. TEST_F(HTTPSOCSPTest, OldStapledButValidAIA) {
  9426. if (!SystemSupportsOCSPStapling()) {
  9427. LOG(WARNING)
  9428. << "Skipping test because system doesn't support OCSP stapling";
  9429. return;
  9430. }
  9431. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9432. // Stapled response indicates good, but response is too old.
  9433. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9434. {{OCSPRevocationStatus::GOOD,
  9435. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}});
  9436. // AIA OCSP url is included, and returns a successful ocsp response.
  9437. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9438. {{OCSPRevocationStatus::GOOD,
  9439. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9440. CertStatus cert_status;
  9441. DoConnection(cert_config, &cert_status);
  9442. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9443. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9444. }
  9445. static const struct OCSPVerifyTestData {
  9446. EmbeddedTestServer::OCSPConfig ocsp_config;
  9447. OCSPVerifyResult::ResponseStatus expected_response_status;
  9448. // |expected_cert_status| is only used if |expected_response_status| is
  9449. // PROVIDED.
  9450. OCSPRevocationStatus expected_cert_status;
  9451. } kOCSPVerifyData[] = {
  9452. // 0
  9453. {EmbeddedTestServer::OCSPConfig(
  9454. {{OCSPRevocationStatus::GOOD,
  9455. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9456. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9457. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::GOOD},
  9458. // 1
  9459. {EmbeddedTestServer::OCSPConfig(
  9460. {{OCSPRevocationStatus::GOOD,
  9461. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}},
  9462. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9463. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9464. // 2
  9465. {EmbeddedTestServer::OCSPConfig(
  9466. {{OCSPRevocationStatus::GOOD,
  9467. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly}},
  9468. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9469. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9470. // 3
  9471. {EmbeddedTestServer::OCSPConfig(
  9472. {{OCSPRevocationStatus::GOOD,
  9473. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong}},
  9474. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9475. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9476. // 4
  9477. {EmbeddedTestServer::OCSPConfig(
  9478. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater),
  9479. OCSPVerifyResult::ERROR_RESPONSE, OCSPRevocationStatus::UNKNOWN},
  9480. // 5
  9481. {EmbeddedTestServer::OCSPConfig(
  9482. EmbeddedTestServer::OCSPConfig::ResponseType::kInvalidResponse),
  9483. OCSPVerifyResult::PARSE_RESPONSE_ERROR, OCSPRevocationStatus::UNKNOWN},
  9484. // 6
  9485. {EmbeddedTestServer::OCSPConfig(
  9486. EmbeddedTestServer::OCSPConfig::ResponseType::kInvalidResponseData),
  9487. OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
  9488. OCSPRevocationStatus::UNKNOWN},
  9489. // 7
  9490. {EmbeddedTestServer::OCSPConfig(
  9491. {{OCSPRevocationStatus::REVOKED,
  9492. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly}},
  9493. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9494. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9495. // 8
  9496. {EmbeddedTestServer::OCSPConfig(
  9497. {{OCSPRevocationStatus::UNKNOWN,
  9498. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9499. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9500. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::UNKNOWN},
  9501. // 9
  9502. {EmbeddedTestServer::OCSPConfig(
  9503. {{OCSPRevocationStatus::UNKNOWN,
  9504. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}},
  9505. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9506. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9507. // 10
  9508. {EmbeddedTestServer::OCSPConfig(
  9509. {{OCSPRevocationStatus::UNKNOWN,
  9510. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly}},
  9511. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9512. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9513. // 11
  9514. {EmbeddedTestServer::OCSPConfig(
  9515. {{OCSPRevocationStatus::GOOD,
  9516. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9517. EmbeddedTestServer::OCSPConfig::Produced::kBeforeCert),
  9518. OCSPVerifyResult::BAD_PRODUCED_AT, OCSPRevocationStatus::UNKNOWN},
  9519. // 12
  9520. {EmbeddedTestServer::OCSPConfig(
  9521. {{OCSPRevocationStatus::GOOD,
  9522. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9523. EmbeddedTestServer::OCSPConfig::Produced::kAfterCert),
  9524. OCSPVerifyResult::BAD_PRODUCED_AT, OCSPRevocationStatus::UNKNOWN},
  9525. // 13
  9526. {EmbeddedTestServer::OCSPConfig(
  9527. {{OCSPRevocationStatus::GOOD,
  9528. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld},
  9529. {OCSPRevocationStatus::GOOD,
  9530. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9531. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9532. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::GOOD},
  9533. // 14
  9534. {EmbeddedTestServer::OCSPConfig(
  9535. {{OCSPRevocationStatus::GOOD,
  9536. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly},
  9537. {OCSPRevocationStatus::GOOD,
  9538. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9539. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9540. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::GOOD},
  9541. // 15
  9542. {EmbeddedTestServer::OCSPConfig(
  9543. {{OCSPRevocationStatus::GOOD,
  9544. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong},
  9545. {OCSPRevocationStatus::GOOD,
  9546. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9547. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9548. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::GOOD},
  9549. // 16
  9550. {EmbeddedTestServer::OCSPConfig(
  9551. {{OCSPRevocationStatus::GOOD,
  9552. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly},
  9553. {OCSPRevocationStatus::GOOD,
  9554. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld},
  9555. {OCSPRevocationStatus::GOOD,
  9556. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong}},
  9557. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9558. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9559. // 17
  9560. {EmbeddedTestServer::OCSPConfig(
  9561. {{OCSPRevocationStatus::UNKNOWN,
  9562. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid},
  9563. {OCSPRevocationStatus::REVOKED,
  9564. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid},
  9565. {OCSPRevocationStatus::GOOD,
  9566. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9567. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9568. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::REVOKED},
  9569. // 18
  9570. {EmbeddedTestServer::OCSPConfig(
  9571. {{OCSPRevocationStatus::UNKNOWN,
  9572. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid},
  9573. {OCSPRevocationStatus::GOOD,
  9574. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9575. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9576. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::UNKNOWN},
  9577. // 19
  9578. {EmbeddedTestServer::OCSPConfig(
  9579. {{OCSPRevocationStatus::UNKNOWN,
  9580. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid},
  9581. {OCSPRevocationStatus::REVOKED,
  9582. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong},
  9583. {OCSPRevocationStatus::GOOD,
  9584. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9585. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9586. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::UNKNOWN},
  9587. // 20
  9588. {EmbeddedTestServer::OCSPConfig(
  9589. {{OCSPRevocationStatus::GOOD,
  9590. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid,
  9591. EmbeddedTestServer::OCSPConfig::SingleResponse::Serial::kMismatch}},
  9592. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9593. OCSPVerifyResult::NO_MATCHING_RESPONSE, OCSPRevocationStatus::UNKNOWN},
  9594. // 21
  9595. {EmbeddedTestServer::OCSPConfig(
  9596. {{OCSPRevocationStatus::GOOD,
  9597. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kEarly,
  9598. EmbeddedTestServer::OCSPConfig::SingleResponse::Serial::kMismatch}},
  9599. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9600. OCSPVerifyResult::NO_MATCHING_RESPONSE, OCSPRevocationStatus::UNKNOWN},
  9601. // 22
  9602. {EmbeddedTestServer::OCSPConfig(
  9603. {{OCSPRevocationStatus::REVOKED,
  9604. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}},
  9605. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9606. OCSPVerifyResult::PROVIDED, OCSPRevocationStatus::REVOKED},
  9607. // 23
  9608. {EmbeddedTestServer::OCSPConfig(
  9609. {{OCSPRevocationStatus::REVOKED,
  9610. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}},
  9611. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9612. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9613. // 24
  9614. {EmbeddedTestServer::OCSPConfig(
  9615. {{OCSPRevocationStatus::REVOKED,
  9616. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong}},
  9617. EmbeddedTestServer::OCSPConfig::Produced::kValid),
  9618. OCSPVerifyResult::INVALID_DATE, OCSPRevocationStatus::UNKNOWN},
  9619. };
  9620. class HTTPSOCSPVerifyTest
  9621. : public HTTPSOCSPTest,
  9622. public testing::WithParamInterface<OCSPVerifyTestData> {};
  9623. TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
  9624. OCSPVerifyTestData test = GetParam();
  9625. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9626. cert_config.stapled_ocsp_config = test.ocsp_config;
  9627. SSLInfo ssl_info;
  9628. OCSPErrorTestDelegate delegate;
  9629. ASSERT_NO_FATAL_FAILURE(
  9630. DoConnectionWithDelegate(cert_config, &delegate, &ssl_info));
  9631. // The SSLInfo must be extracted from |delegate| on error, due to how
  9632. // URLRequest caches certificate errors.
  9633. if (delegate.have_certificate_errors()) {
  9634. ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
  9635. ssl_info = delegate.ssl_info();
  9636. }
  9637. EXPECT_EQ(test.expected_response_status,
  9638. ssl_info.ocsp_result.response_status);
  9639. if (test.expected_response_status == OCSPVerifyResult::PROVIDED) {
  9640. EXPECT_EQ(test.expected_cert_status,
  9641. ssl_info.ocsp_result.revocation_status);
  9642. }
  9643. }
  9644. INSTANTIATE_TEST_SUITE_P(OCSPVerify,
  9645. HTTPSOCSPVerifyTest,
  9646. testing::ValuesIn(kOCSPVerifyData));
  9647. class HTTPSAIATest : public HTTPSCertNetFetchingTest {};
  9648. TEST_F(HTTPSAIATest, AIAFetching) {
  9649. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  9650. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9651. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kByAIA;
  9652. test_server.SetSSLConfig(cert_config);
  9653. RegisterDefaultHandlers(&test_server);
  9654. ASSERT_TRUE(test_server.Start());
  9655. TestDelegate d;
  9656. d.set_allow_certificate_errors(true);
  9657. std::unique_ptr<URLRequest> r(context_->CreateRequest(
  9658. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  9659. TRAFFIC_ANNOTATION_FOR_TESTS));
  9660. r->Start();
  9661. EXPECT_TRUE(r->is_pending());
  9662. d.RunUntilComplete();
  9663. EXPECT_EQ(1, d.response_started_count());
  9664. CertStatus cert_status = r->ssl_info().cert_status;
  9665. EXPECT_EQ(OK, d.request_status());
  9666. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9667. ASSERT_TRUE(r->ssl_info().cert);
  9668. EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
  9669. ASSERT_TRUE(r->ssl_info().unverified_cert);
  9670. EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
  9671. }
  9672. class HTTPSHardFailTest : public HTTPSOCSPTest {
  9673. protected:
  9674. CertVerifier::Config GetCertVerifierConfig() override {
  9675. CertVerifier::Config config;
  9676. config.require_rev_checking_local_anchors = true;
  9677. return config;
  9678. }
  9679. };
  9680. TEST_F(HTTPSHardFailTest, Valid) {
  9681. if (!SystemSupportsOCSP()) {
  9682. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9683. return;
  9684. }
  9685. if (!SystemSupportsHardFailRevocationChecking()) {
  9686. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9687. << "revocation checking";
  9688. return;
  9689. }
  9690. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9691. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9692. {{OCSPRevocationStatus::GOOD,
  9693. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9694. CertStatus cert_status;
  9695. DoConnection(cert_config, &cert_status);
  9696. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9697. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9698. }
  9699. TEST_F(HTTPSHardFailTest, Revoked) {
  9700. if (!SystemSupportsOCSP()) {
  9701. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9702. return;
  9703. }
  9704. if (!SystemSupportsHardFailRevocationChecking()) {
  9705. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9706. << "revocation checking";
  9707. return;
  9708. }
  9709. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9710. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9711. {{OCSPRevocationStatus::REVOKED,
  9712. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9713. CertStatus cert_status;
  9714. DoConnection(cert_config, &cert_status);
  9715. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9716. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9717. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9718. }
  9719. TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
  9720. if (!SystemSupportsOCSP()) {
  9721. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9722. return;
  9723. }
  9724. if (!SystemSupportsHardFailRevocationChecking()) {
  9725. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9726. << "revocation checking";
  9727. return;
  9728. }
  9729. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9730. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9731. EmbeddedTestServer::OCSPConfig::ResponseType::kInvalidResponse);
  9732. CertStatus cert_status;
  9733. DoConnection(cert_config, &cert_status);
  9734. EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
  9735. cert_status & CERT_STATUS_ALL_ERRORS);
  9736. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9737. }
  9738. TEST_F(HTTPSHardFailTest, IntermediateResponseOldButStillValid) {
  9739. if (!SystemSupportsOCSP()) {
  9740. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9741. return;
  9742. }
  9743. if (!SystemSupportsHardFailRevocationChecking()) {
  9744. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9745. << "revocation checking";
  9746. return;
  9747. }
  9748. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9749. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9750. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9751. {{OCSPRevocationStatus::GOOD,
  9752. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9753. // Use an OCSP response for the intermediate that would be too old for a leaf
  9754. // cert, but is still valid for an intermediate.
  9755. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9756. {{OCSPRevocationStatus::GOOD,
  9757. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLong}});
  9758. CertStatus cert_status;
  9759. DoConnection(cert_config, &cert_status);
  9760. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9761. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9762. }
  9763. TEST_F(HTTPSHardFailTest, IntermediateResponseTooOld) {
  9764. if (!SystemSupportsOCSP()) {
  9765. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9766. return;
  9767. }
  9768. if (!SystemSupportsHardFailRevocationChecking()) {
  9769. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9770. << "revocation checking";
  9771. return;
  9772. }
  9773. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9774. cert_config.intermediate = EmbeddedTestServer::IntermediateType::kInHandshake;
  9775. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9776. {{OCSPRevocationStatus::GOOD,
  9777. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9778. // Use an OCSP response for the intermediate that is too old.
  9779. cert_config.intermediate_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9780. {{OCSPRevocationStatus::GOOD,
  9781. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kLonger}});
  9782. CertStatus cert_status;
  9783. DoConnection(cert_config, &cert_status);
  9784. if (UsingBuiltinCertVerifier()) {
  9785. EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
  9786. cert_status & CERT_STATUS_ALL_ERRORS);
  9787. } else {
  9788. // Platform verifier are more lenient.
  9789. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9790. }
  9791. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9792. }
  9793. TEST_F(HTTPSHardFailTest, ValidStapled) {
  9794. if (!SystemSupportsOCSPStapling()) {
  9795. LOG(WARNING)
  9796. << "Skipping test because system doesn't support OCSP stapling";
  9797. return;
  9798. }
  9799. if (!SystemSupportsHardFailRevocationChecking()) {
  9800. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9801. << "revocation checking";
  9802. return;
  9803. }
  9804. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9805. // AIA OCSP url is included, but does not return a successful ocsp response.
  9806. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9807. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9808. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9809. {{OCSPRevocationStatus::GOOD,
  9810. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9811. CertStatus cert_status;
  9812. DoConnection(cert_config, &cert_status);
  9813. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9814. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9815. }
  9816. TEST_F(HTTPSHardFailTest, RevokedStapled) {
  9817. if (!SystemSupportsOCSPStapling()) {
  9818. LOG(WARNING)
  9819. << "Skipping test because system doesn't support OCSP stapling";
  9820. return;
  9821. }
  9822. if (!SystemSupportsHardFailRevocationChecking()) {
  9823. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9824. << "revocation checking";
  9825. return;
  9826. }
  9827. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9828. // AIA OCSP url is included, but does not return a successful ocsp response.
  9829. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9830. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9831. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9832. {{OCSPRevocationStatus::REVOKED,
  9833. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9834. CertStatus cert_status;
  9835. DoConnection(cert_config, &cert_status);
  9836. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9837. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9838. }
  9839. TEST_F(HTTPSHardFailTest, OldStapledAndInvalidAIA) {
  9840. if (!SystemSupportsOCSPStapling()) {
  9841. LOG(WARNING)
  9842. << "Skipping test because system doesn't support OCSP stapling";
  9843. return;
  9844. }
  9845. if (!SystemSupportsHardFailRevocationChecking()) {
  9846. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9847. << "revocation checking";
  9848. return;
  9849. }
  9850. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9851. // Stapled response indicates good, but is too old.
  9852. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9853. {{OCSPRevocationStatus::GOOD,
  9854. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}});
  9855. // AIA OCSP url is included, but does not return a successful ocsp response.
  9856. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9857. EmbeddedTestServer::OCSPConfig::ResponseType::kTryLater);
  9858. CertStatus cert_status;
  9859. DoConnection(cert_config, &cert_status);
  9860. EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
  9861. cert_status & CERT_STATUS_ALL_ERRORS);
  9862. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9863. }
  9864. TEST_F(HTTPSHardFailTest, OldStapledButValidAIA) {
  9865. if (!SystemSupportsOCSPStapling()) {
  9866. LOG(WARNING)
  9867. << "Skipping test because system doesn't support OCSP stapling";
  9868. return;
  9869. }
  9870. if (!SystemSupportsHardFailRevocationChecking()) {
  9871. LOG(WARNING) << "Skipping test because system doesn't support hard fail "
  9872. << "revocation checking";
  9873. return;
  9874. }
  9875. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9876. // Stapled response indicates good, but response is too old.
  9877. cert_config.stapled_ocsp_config = EmbeddedTestServer::OCSPConfig(
  9878. {{OCSPRevocationStatus::GOOD,
  9879. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kOld}});
  9880. // AIA OCSP url is included, and returns a successful ocsp response.
  9881. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9882. {{OCSPRevocationStatus::GOOD,
  9883. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9884. CertStatus cert_status;
  9885. DoConnection(cert_config, &cert_status);
  9886. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9887. EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9888. }
  9889. class HTTPSCRLSetTest : public HTTPSCertNetFetchingTest {};
  9890. TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
  9891. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9892. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9893. EmbeddedTestServer::OCSPConfig::ResponseType::kInvalidResponse);
  9894. CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
  9895. cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
  9896. context_->cert_verifier()->SetConfig(cert_verifier_config);
  9897. CertStatus cert_status;
  9898. DoConnection(cert_config, &cert_status);
  9899. // If we're not trying EV verification then, even if the CRLSet has expired,
  9900. // we don't fall back to online revocation checks.
  9901. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9902. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9903. EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9904. }
  9905. TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
  9906. // Test that when online revocation checking is disabled, and the leaf
  9907. // certificate is not EV, that no revocation checking actually happens.
  9908. if (!SystemSupportsOCSP()) {
  9909. LOG(WARNING) << "Skipping test because system doesn't support OCSP";
  9910. return;
  9911. }
  9912. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9913. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9914. {{OCSPRevocationStatus::REVOKED,
  9915. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9916. CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
  9917. cert_verifier_config.crl_set = CRLSet::ExpiredCRLSetForTesting();
  9918. context_->cert_verifier()->SetConfig(cert_verifier_config);
  9919. CertStatus cert_status;
  9920. DoConnection(cert_config, &cert_status);
  9921. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  9922. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9923. EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9924. }
  9925. TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
  9926. if (!SystemSupportsCRLSets()) {
  9927. LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
  9928. return;
  9929. }
  9930. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  9931. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9932. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9933. {{OCSPRevocationStatus::GOOD,
  9934. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9935. test_server.SetSSLConfig(cert_config);
  9936. RegisterDefaultHandlers(&test_server);
  9937. ASSERT_TRUE(test_server.Start());
  9938. CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
  9939. SHA256HashValue root_cert_spki_hash;
  9940. ASSERT_TRUE(GetTestRootCertSPKIHash(&root_cert_spki_hash));
  9941. cert_verifier_config.crl_set =
  9942. CRLSet::ForTesting(false, &root_cert_spki_hash,
  9943. test_server.GetCertificate()->serial_number(), "", {});
  9944. context_->cert_verifier()->SetConfig(cert_verifier_config);
  9945. TestDelegate d;
  9946. d.set_allow_certificate_errors(true);
  9947. std::unique_ptr<URLRequest> r(context_->CreateRequest(
  9948. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  9949. TRAFFIC_ANNOTATION_FOR_TESTS));
  9950. r->Start();
  9951. EXPECT_TRUE(r->is_pending());
  9952. d.RunUntilComplete();
  9953. EXPECT_EQ(1, d.response_started_count());
  9954. CertStatus cert_status = r->ssl_info().cert_status;
  9955. // If the certificate is recorded as revoked in the CRLSet, that should be
  9956. // reflected without online revocation checking.
  9957. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9958. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9959. EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9960. }
  9961. TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
  9962. if (!SystemSupportsCRLSets()) {
  9963. LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
  9964. return;
  9965. }
  9966. EmbeddedTestServer test_server(EmbeddedTestServer::TYPE_HTTPS);
  9967. EmbeddedTestServer::ServerCertificateConfig cert_config;
  9968. cert_config.ocsp_config = EmbeddedTestServer::OCSPConfig(
  9969. {{OCSPRevocationStatus::GOOD,
  9970. EmbeddedTestServer::OCSPConfig::SingleResponse::Date::kValid}});
  9971. test_server.SetSSLConfig(cert_config);
  9972. RegisterDefaultHandlers(&test_server);
  9973. ASSERT_TRUE(test_server.Start());
  9974. std::string common_name = test_server.GetCertificate()->subject().common_name;
  9975. {
  9976. CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
  9977. cert_verifier_config.crl_set =
  9978. CRLSet::ForTesting(false, nullptr, "", common_name, {});
  9979. ASSERT_TRUE(cert_verifier_config.crl_set);
  9980. context_->cert_verifier()->SetConfig(cert_verifier_config);
  9981. TestDelegate d;
  9982. d.set_allow_certificate_errors(true);
  9983. std::unique_ptr<URLRequest> r(context_->CreateRequest(
  9984. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  9985. TRAFFIC_ANNOTATION_FOR_TESTS));
  9986. r->Start();
  9987. EXPECT_TRUE(r->is_pending());
  9988. d.RunUntilComplete();
  9989. EXPECT_EQ(1, d.response_started_count());
  9990. CertStatus cert_status = r->ssl_info().cert_status;
  9991. // If the certificate is recorded as revoked in the CRLSet, that should be
  9992. // reflected without online revocation checking.
  9993. EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
  9994. EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
  9995. EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
  9996. }
  9997. HashValue spki_hash_value;
  9998. ASSERT_TRUE(x509_util::CalculateSha256SpkiHash(
  9999. test_server.GetCertificate()->cert_buffer(), &spki_hash_value));
  10000. std::string spki_hash(spki_hash_value.data(),
  10001. spki_hash_value.data() + spki_hash_value.size());
  10002. {
  10003. CertVerifier::Config cert_verifier_config = GetCertVerifierConfig();
  10004. cert_verifier_config.crl_set =
  10005. CRLSet::ForTesting(false, nullptr, "", common_name, {spki_hash});
  10006. context_->cert_verifier()->SetConfig(cert_verifier_config);
  10007. TestDelegate d;
  10008. d.set_allow_certificate_errors(true);
  10009. std::unique_ptr<URLRequest> r(context_->CreateRequest(
  10010. test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
  10011. TRAFFIC_ANNOTATION_FOR_TESTS));
  10012. r->Start();
  10013. EXPECT_TRUE(r->is_pending());
  10014. d.RunUntilComplete();
  10015. EXPECT_EQ(1, d.response_started_count());
  10016. CertStatus cert_status = r->ssl_info().cert_status;
  10017. // When the correct SPKI hash is specified in
  10018. // |acceptable_spki_hashes_for_cn|, the connection should succeed even
  10019. // though the subject is listed in the CRLSet.
  10020. EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
  10021. }
  10022. }
  10023. using HTTPSLocalCRLSetTest = TestWithTaskEnvironment;
  10024. // Use a real CertVerifier to attempt to connect to the TestServer, and ensure
  10025. // that when a CRLSet is provided that marks a given SPKI (the TestServer's
  10026. // root SPKI) as known for interception, that it's adequately flagged.
  10027. TEST_F(HTTPSLocalCRLSetTest, KnownInterceptionBlocked) {
  10028. auto context_builder = CreateTestURLRequestContextBuilder();
  10029. context_builder->SetCertVerifier(
  10030. CertVerifier::CreateDefault(/*cert_net_fetcher=*/nullptr));
  10031. auto context = context_builder->Build();
  10032. // Verify the connection succeeds without being flagged.
  10033. EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
  10034. RegisterDefaultHandlers(&https_server);
  10035. https_server.SetSSLConfig(EmbeddedTestServer::CERT_OK_BY_INTERMEDIATE);
  10036. ASSERT_TRUE(https_server.Start());
  10037. {
  10038. TestDelegate d;
  10039. std::unique_ptr<URLRequest> req(
  10040. context->CreateRequest(https_server.GetURL("/"), DEFAULT_PRIORITY, &d,
  10041. TRAFFIC_ANNOTATION_FOR_TESTS));
  10042. req->Start();
  10043. d.RunUntilComplete();
  10044. EXPECT_EQ(1, d.response_started_count());
  10045. EXPECT_FALSE(d.request_failed());
  10046. EXPECT_FALSE(d.have_certificate_errors());
  10047. EXPECT_FALSE(req->ssl_info().cert_status &
  10048. CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
  10049. }
  10050. // Configure a CRL that will mark |root_ca_cert| as a blocked interception
  10051. // root.
  10052. std::string crl_set_bytes;
  10053. scoped_refptr<CRLSet> crl_set;
  10054. ASSERT_TRUE(
  10055. base::ReadFileToString(GetTestCertsDirectory().AppendASCII(
  10056. "crlset_blocked_interception_by_root.raw"),
  10057. &crl_set_bytes));
  10058. ASSERT_TRUE(CRLSet::Parse(crl_set_bytes, &crl_set));
  10059. CertVerifier::Config config_with_crlset;
  10060. config_with_crlset.crl_set = crl_set;
  10061. context->cert_verifier()->SetConfig(config_with_crlset);
  10062. // Verify the connection fails as being a known interception root.
  10063. {
  10064. TestDelegate d;
  10065. d.set_allow_certificate_errors(true);
  10066. std::unique_ptr<URLRequest> req(
  10067. context->CreateRequest(https_server.GetURL("/"), DEFAULT_PRIORITY, &d,
  10068. TRAFFIC_ANNOTATION_FOR_TESTS));
  10069. req->Start();
  10070. d.RunUntilComplete();
  10071. EXPECT_EQ(1, d.response_started_count());
  10072. EXPECT_FALSE(d.request_failed());
  10073. if (SystemSupportsCRLSets()) {
  10074. EXPECT_TRUE(d.have_certificate_errors());
  10075. EXPECT_FALSE(d.certificate_errors_are_fatal());
  10076. EXPECT_EQ(ERR_CERT_KNOWN_INTERCEPTION_BLOCKED, d.certificate_net_error());
  10077. EXPECT_TRUE(req->ssl_info().cert_status &
  10078. CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
  10079. } else {
  10080. EXPECT_FALSE(d.have_certificate_errors());
  10081. EXPECT_TRUE(req->ssl_info().cert_status &
  10082. CERT_STATUS_KNOWN_INTERCEPTION_DETECTED);
  10083. }
  10084. }
  10085. }
  10086. TEST_F(HTTPSLocalCRLSetTest, InterceptionBlockedAllowOverrideOnHSTS) {
  10087. constexpr char kHSTSHost[] = "include-subdomains-hsts-preloaded.test";
  10088. constexpr char kHSTSSubdomainWithKnownInterception[] =
  10089. "www.include-subdomains-hsts-preloaded.test";
  10090. EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
  10091. https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK_BY_INTERMEDIATE);
  10092. https_server.ServeFilesFromSourceDirectory(base::FilePath(kTestFilePath));
  10093. ASSERT_TRUE(https_server.Start());
  10094. // Configure the CertVerifier to simulate:
  10095. // - For the test server host, that the certificate is issued by an
  10096. // unknown authority; this SHOULD NOT be a fatal error when signaled
  10097. // to the delegate.
  10098. // - For |kHSTSHost|, that the certificate is issued by an unknown
  10099. // authority; this SHOULD be a fatal error.
  10100. // Combined, these two states represent the baseline: non-fatal for non-HSTS
  10101. // hosts, fatal for HSTS host.
  10102. // - For |kHSTSSubdomainWithKnownInterception|, that the certificate is
  10103. // issued by a known interception cert. This SHOULD be an error, but
  10104. // SHOULD NOT be a fatal error
  10105. auto cert_verifier = std::make_unique<MockCertVerifier>();
  10106. scoped_refptr<X509Certificate> cert = https_server.GetCertificate();
  10107. ASSERT_TRUE(cert);
  10108. HashValue filler_hash;
  10109. ASSERT_TRUE(filler_hash.FromString(
  10110. "sha256/3333333333333333333333333333333333333333333="));
  10111. CertVerifyResult fake_result;
  10112. fake_result.verified_cert = cert;
  10113. fake_result.is_issued_by_known_root = false;
  10114. // Configure for the test server's default host.
  10115. CertVerifyResult test_result = fake_result;
  10116. test_result.public_key_hashes.push_back(filler_hash);
  10117. test_result.cert_status |= CERT_STATUS_AUTHORITY_INVALID;
  10118. cert_verifier->AddResultForCertAndHost(
  10119. cert.get(), https_server.host_port_pair().host(), test_result,
  10120. ERR_CERT_AUTHORITY_INVALID);
  10121. // Configure for kHSTSHost.
  10122. CertVerifyResult sts_base_result = fake_result;
  10123. sts_base_result.public_key_hashes.push_back(filler_hash);
  10124. sts_base_result.cert_status |= CERT_STATUS_AUTHORITY_INVALID;
  10125. cert_verifier->AddResultForCertAndHost(cert.get(), kHSTSHost, sts_base_result,
  10126. ERR_CERT_AUTHORITY_INVALID);
  10127. // Configure for kHSTSSubdomainWithKnownInterception
  10128. CertVerifyResult sts_sub_result = fake_result;
  10129. SHA256HashValue root_hash;
  10130. ASSERT_TRUE(GetTestRootCertSPKIHash(&root_hash));
  10131. sts_sub_result.public_key_hashes.push_back(HashValue(root_hash));
  10132. sts_sub_result.cert_status |=
  10133. CERT_STATUS_REVOKED | CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED;
  10134. cert_verifier->AddResultForCertAndHost(
  10135. cert.get(), kHSTSSubdomainWithKnownInterception, sts_sub_result,
  10136. ERR_CERT_KNOWN_INTERCEPTION_BLOCKED);
  10137. // Configure the initial context.
  10138. auto context_builder = CreateTestURLRequestContextBuilder();
  10139. context_builder->SetCertVerifier(std::move(cert_verifier));
  10140. auto context = context_builder->Build();
  10141. // Enable preloaded HSTS for |kHSTSHost|.
  10142. ASSERT_TRUE(context->transport_security_state());
  10143. TransportSecurityState& security_state = *context->transport_security_state();
  10144. security_state.EnableStaticPinsForTesting();
  10145. security_state.SetPinningListAlwaysTimelyForTesting(true);
  10146. SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
  10147. // Connect to the test server and see the certificate error flagged, but
  10148. // not fatal.
  10149. {
  10150. TestDelegate d;
  10151. std::unique_ptr<URLRequest> req(
  10152. context->CreateRequest(https_server.GetURL("/"), DEFAULT_PRIORITY, &d,
  10153. TRAFFIC_ANNOTATION_FOR_TESTS));
  10154. req->Start();
  10155. d.RunUntilComplete();
  10156. EXPECT_EQ(1, d.response_started_count());
  10157. EXPECT_TRUE(d.request_failed());
  10158. EXPECT_TRUE(d.have_certificate_errors());
  10159. EXPECT_FALSE(d.certificate_errors_are_fatal());
  10160. EXPECT_FALSE(req->ssl_info().cert_status &
  10161. CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
  10162. }
  10163. // Connect to kHSTSHost and see the certificate errors are flagged, and are
  10164. // fatal.
  10165. {
  10166. TestDelegate d;
  10167. std::unique_ptr<URLRequest> req(context->CreateRequest(
  10168. https_server.GetURL(kHSTSHost, "/"), DEFAULT_PRIORITY, &d,
  10169. TRAFFIC_ANNOTATION_FOR_TESTS));
  10170. req->Start();
  10171. d.RunUntilComplete();
  10172. EXPECT_EQ(1, d.response_started_count());
  10173. EXPECT_TRUE(d.request_failed());
  10174. EXPECT_TRUE(d.have_certificate_errors());
  10175. EXPECT_TRUE(d.certificate_errors_are_fatal());
  10176. EXPECT_FALSE(req->ssl_info().cert_status &
  10177. CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
  10178. }
  10179. // Verify the connection fails as being a known interception root.
  10180. {
  10181. TestDelegate d;
  10182. d.set_allow_certificate_errors(true);
  10183. std::unique_ptr<URLRequest> req(context->CreateRequest(
  10184. https_server.GetURL(kHSTSSubdomainWithKnownInterception, "/"),
  10185. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10186. req->Start();
  10187. d.RunUntilComplete();
  10188. EXPECT_EQ(1, d.response_started_count());
  10189. EXPECT_FALSE(d.request_failed());
  10190. EXPECT_TRUE(d.have_certificate_errors());
  10191. EXPECT_FALSE(d.certificate_errors_are_fatal());
  10192. EXPECT_EQ(ERR_CERT_KNOWN_INTERCEPTION_BLOCKED, d.certificate_net_error());
  10193. EXPECT_TRUE(req->ssl_info().cert_status &
  10194. CERT_STATUS_KNOWN_INTERCEPTION_BLOCKED);
  10195. }
  10196. }
  10197. #endif // !BUILDFLAG(IS_IOS)
  10198. TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
  10199. auto context_builder = CreateTestURLRequestContextBuilder();
  10200. auto host_resolver = std::make_unique<MockHostResolver>();
  10201. host_resolver->rules()->AddSimulatedTimeoutFailure("*");
  10202. context_builder->set_host_resolver(std::move(host_resolver));
  10203. auto context = context_builder->Build();
  10204. TestDelegate d;
  10205. std::unique_ptr<URLRequest> req(context->CreateRequest(
  10206. GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
  10207. TRAFFIC_ANNOTATION_FOR_TESTS));
  10208. EXPECT_FALSE(req->response_info().network_accessed);
  10209. req->Start();
  10210. d.RunUntilComplete();
  10211. EXPECT_TRUE(req->response_info().network_accessed);
  10212. EXPECT_THAT(req->response_info().resolve_error_info.error,
  10213. IsError(ERR_DNS_TIMED_OUT));
  10214. }
  10215. // Test that URLRequest is canceled correctly.
  10216. // See http://crbug.com/508900
  10217. TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
  10218. TestDelegate d;
  10219. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  10220. GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
  10221. TRAFFIC_ANNOTATION_FOR_TESTS));
  10222. std::unique_ptr<URLRequestRedirectJob> job =
  10223. std::make_unique<URLRequestRedirectJob>(
  10224. req.get(), GURL("http://this-should-never-be-navigated-to/"),
  10225. RedirectUtil::ResponseCode::REDIRECT_307_TEMPORARY_REDIRECT,
  10226. "Jumbo shrimp");
  10227. TestScopedURLInterceptor interceptor(req->url(), std::move(job));
  10228. req->Start();
  10229. req->Cancel();
  10230. base::RunLoop().RunUntilIdle();
  10231. EXPECT_EQ(ERR_ABORTED, d.request_status());
  10232. EXPECT_EQ(0, d.received_redirect_count());
  10233. }
  10234. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
  10235. #define MAYBE_HeadersCallbacks DISABLED_HeadersCallbacks
  10236. #else
  10237. #define MAYBE_HeadersCallbacks HeadersCallbacks
  10238. #endif
  10239. TEST_F(URLRequestTestHTTP, MAYBE_HeadersCallbacks) {
  10240. ASSERT_TRUE(http_test_server()->Start());
  10241. GURL url(http_test_server()->GetURL("/cachetime"));
  10242. TestDelegate delegate;
  10243. HttpRequestHeaders extra_headers;
  10244. extra_headers.SetHeader("X-Foo", "bar");
  10245. {
  10246. HttpRawRequestHeaders raw_req_headers;
  10247. scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
  10248. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  10249. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  10250. r->SetExtraRequestHeaders(extra_headers);
  10251. r->SetRequestHeadersCallback(base::BindRepeating(
  10252. &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
  10253. r->SetResponseHeadersCallback(base::BindRepeating(
  10254. [](scoped_refptr<const HttpResponseHeaders>* left,
  10255. scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
  10256. base::Unretained(&raw_resp_headers)));
  10257. r->set_isolation_info(isolation_info1_);
  10258. r->Start();
  10259. while (!delegate.response_started_count())
  10260. base::RunLoop().RunUntilIdle();
  10261. EXPECT_FALSE(raw_req_headers.headers().empty());
  10262. std::string value;
  10263. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
  10264. EXPECT_EQ("bar", value);
  10265. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
  10266. EXPECT_EQ("gzip, deflate", value);
  10267. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
  10268. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
  10269. EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
  10270. EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
  10271. }
  10272. {
  10273. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  10274. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  10275. r->SetExtraRequestHeaders(extra_headers);
  10276. r->SetRequestHeadersCallback(base::BindRepeating([](HttpRawRequestHeaders) {
  10277. FAIL() << "Callback should not be called unless request is sent";
  10278. }));
  10279. r->SetResponseHeadersCallback(
  10280. base::BindRepeating([](scoped_refptr<const HttpResponseHeaders>) {
  10281. FAIL() << "Callback should not be called unless request is sent";
  10282. }));
  10283. r->set_isolation_info(isolation_info1_);
  10284. r->Start();
  10285. delegate.RunUntilComplete();
  10286. EXPECT_TRUE(r->was_cached());
  10287. }
  10288. }
  10289. TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
  10290. ASSERT_TRUE(http_test_server()->Start());
  10291. HttpRawRequestHeaders raw_req_headers;
  10292. scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
  10293. TestDelegate delegate;
  10294. HttpRequestHeaders extra_headers;
  10295. extra_headers.SetHeader("X-Foo", "bar");
  10296. GURL url(http_test_server()->GetURL("/redirect-test.html"));
  10297. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  10298. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  10299. r->SetExtraRequestHeaders(extra_headers);
  10300. r->SetRequestHeadersCallback(base::BindRepeating(
  10301. &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
  10302. r->SetResponseHeadersCallback(base::BindRepeating(
  10303. [](scoped_refptr<const HttpResponseHeaders>* left,
  10304. scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
  10305. base::Unretained(&raw_resp_headers)));
  10306. r->Start();
  10307. delegate.RunUntilRedirect();
  10308. ASSERT_EQ(1, delegate.received_redirect_count());
  10309. std::string value;
  10310. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
  10311. EXPECT_EQ("bar", value);
  10312. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
  10313. EXPECT_EQ("gzip, deflate", value);
  10314. EXPECT_EQ(1, delegate.received_redirect_count());
  10315. EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
  10316. raw_req_headers.request_line());
  10317. EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
  10318. EXPECT_EQ(302, raw_resp_headers->response_code());
  10319. EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
  10320. raw_req_headers = HttpRawRequestHeaders();
  10321. raw_resp_headers = nullptr;
  10322. r->FollowDeferredRedirect(absl::nullopt /* removed_headers */,
  10323. absl::nullopt /* modified_headers */);
  10324. delegate.RunUntilComplete();
  10325. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
  10326. EXPECT_EQ("bar", value);
  10327. EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
  10328. EXPECT_EQ("gzip, deflate", value);
  10329. EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
  10330. raw_req_headers.request_line());
  10331. EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
  10332. }
  10333. TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
  10334. TestDelegate request_delegate;
  10335. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  10336. GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
  10337. TRAFFIC_ANNOTATION_FOR_TESTS));
  10338. r->SetRequestHeadersCallback(
  10339. base::BindRepeating([](net::HttpRawRequestHeaders) {
  10340. FAIL() << "Callback should not be called unless request is sent";
  10341. }));
  10342. r->SetResponseHeadersCallback(
  10343. base::BindRepeating([](scoped_refptr<const net::HttpResponseHeaders>) {
  10344. FAIL() << "Callback should not be called unless request is sent";
  10345. }));
  10346. r->Start();
  10347. request_delegate.RunUntilComplete();
  10348. EXPECT_FALSE(r->is_pending());
  10349. }
  10350. TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
  10351. ASSERT_TRUE(http_test_server()->Start());
  10352. GURL url(http_test_server()->GetURL("/auth-basic"));
  10353. TestDelegate delegate;
  10354. delegate.set_credentials(AuthCredentials(kUser, kSecret));
  10355. HttpRequestHeaders extra_headers;
  10356. extra_headers.SetHeader("X-Foo", "bar");
  10357. using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
  10358. ReqHeadersVector raw_req_headers;
  10359. using RespHeadersVector =
  10360. std::vector<scoped_refptr<const HttpResponseHeaders>>;
  10361. RespHeadersVector raw_resp_headers;
  10362. auto req_headers_callback = base::BindRepeating(
  10363. [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
  10364. vec->emplace_back(
  10365. std::make_unique<HttpRawRequestHeaders>(std::move(headers)));
  10366. },
  10367. &raw_req_headers);
  10368. auto resp_headers_callback = base::BindRepeating(
  10369. [](RespHeadersVector* vec,
  10370. scoped_refptr<const HttpResponseHeaders> headers) {
  10371. vec->push_back(headers);
  10372. },
  10373. &raw_resp_headers);
  10374. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  10375. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  10376. r->SetExtraRequestHeaders(extra_headers);
  10377. r->SetRequestHeadersCallback(req_headers_callback);
  10378. r->SetResponseHeadersCallback(resp_headers_callback);
  10379. r->set_isolation_info(isolation_info1_);
  10380. r->Start();
  10381. delegate.RunUntilComplete();
  10382. EXPECT_FALSE(r->is_pending());
  10383. ASSERT_EQ(raw_req_headers.size(), 2u);
  10384. ASSERT_EQ(raw_resp_headers.size(), 2u);
  10385. std::string value;
  10386. EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
  10387. EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
  10388. EXPECT_EQ("bar", value);
  10389. EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
  10390. EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
  10391. EXPECT_EQ("bar", value);
  10392. EXPECT_EQ(raw_resp_headers[1], r->response_headers());
  10393. EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
  10394. EXPECT_EQ(401, raw_resp_headers[0]->response_code());
  10395. EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
  10396. std::unique_ptr<URLRequest> r2(default_context().CreateRequest(
  10397. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  10398. r2->SetExtraRequestHeaders(extra_headers);
  10399. r2->SetRequestHeadersCallback(req_headers_callback);
  10400. r2->SetResponseHeadersCallback(resp_headers_callback);
  10401. r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
  10402. r2->set_isolation_info(isolation_info1_);
  10403. r2->Start();
  10404. delegate.RunUntilComplete();
  10405. EXPECT_FALSE(r2->is_pending());
  10406. ASSERT_EQ(raw_req_headers.size(), 3u);
  10407. ASSERT_EQ(raw_resp_headers.size(), 3u);
  10408. EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
  10409. EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
  10410. EXPECT_EQ(304, raw_resp_headers[2]->response_code());
  10411. EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
  10412. }
  10413. TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
  10414. TestDelegate d;
  10415. const GURL kOriginalUrl("https://original.test");
  10416. const GURL kRedirectUrl("http://redirect.test");
  10417. auto context_builder = CreateTestURLRequestContextBuilder();
  10418. auto& network_delegate = *context_builder->set_network_delegate(
  10419. std::make_unique<BlockingNetworkDelegate>(
  10420. BlockingNetworkDelegate::SYNCHRONOUS));
  10421. network_delegate.set_redirect_url(kRedirectUrl);
  10422. auto context = context_builder->Build();
  10423. std::unique_ptr<URLRequest> r(context->CreateRequest(
  10424. kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10425. r->set_upgrade_if_insecure(true);
  10426. r->Start();
  10427. d.RunUntilRedirect();
  10428. GURL::Replacements replacements;
  10429. // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
  10430. // was set.
  10431. replacements.SetSchemeStr("https");
  10432. EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
  10433. d.redirect_info().new_url);
  10434. EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
  10435. }
  10436. TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
  10437. TestDelegate d;
  10438. const GURL kOriginalUrl("https://original.test");
  10439. const GURL kRedirectUrl("http://redirect.test:80");
  10440. auto context_builder = CreateTestURLRequestContextBuilder();
  10441. auto& network_delegate = *context_builder->set_network_delegate(
  10442. std::make_unique<BlockingNetworkDelegate>(
  10443. BlockingNetworkDelegate::SYNCHRONOUS));
  10444. network_delegate.set_redirect_url(kRedirectUrl);
  10445. auto context = context_builder->Build();
  10446. std::unique_ptr<URLRequest> r(context->CreateRequest(
  10447. kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10448. r->set_upgrade_if_insecure(true);
  10449. r->Start();
  10450. d.RunUntilRedirect();
  10451. GURL::Replacements replacements;
  10452. // The URL host should have not been changed.
  10453. EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
  10454. // The scheme should now be https, and the effective port should now be 443.
  10455. EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
  10456. EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
  10457. EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
  10458. }
  10459. TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
  10460. TestDelegate d;
  10461. const GURL kOriginalUrl("https://original.test");
  10462. const GURL kRedirectUrl("http://redirect.test:1234");
  10463. auto context_builder = CreateTestURLRequestContextBuilder();
  10464. auto& network_delegate = *context_builder->set_network_delegate(
  10465. std::make_unique<BlockingNetworkDelegate>(
  10466. BlockingNetworkDelegate::SYNCHRONOUS));
  10467. network_delegate.set_redirect_url(kRedirectUrl);
  10468. auto context = context_builder->Build();
  10469. std::unique_ptr<URLRequest> r(context->CreateRequest(
  10470. kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10471. r->set_upgrade_if_insecure(true);
  10472. r->Start();
  10473. d.RunUntilRedirect();
  10474. GURL::Replacements replacements;
  10475. // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
  10476. // was set, nonstandard port should not have been modified.
  10477. replacements.SetSchemeStr("https");
  10478. EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
  10479. d.redirect_info().new_url);
  10480. EXPECT_TRUE(d.redirect_info().insecure_scheme_was_upgraded);
  10481. }
  10482. TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
  10483. TestDelegate d;
  10484. const GURL kOriginalUrl("https://original.test");
  10485. const GURL kRedirectUrl("http://redirect.test");
  10486. auto context_builder = CreateTestURLRequestContextBuilder();
  10487. auto& network_delegate = *context_builder->set_network_delegate(
  10488. std::make_unique<BlockingNetworkDelegate>(
  10489. BlockingNetworkDelegate::SYNCHRONOUS));
  10490. network_delegate.set_redirect_url(kRedirectUrl);
  10491. auto context = context_builder->Build();
  10492. std::unique_ptr<URLRequest> r(context->CreateRequest(
  10493. kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10494. r->set_upgrade_if_insecure(false);
  10495. r->Start();
  10496. d.RunUntilRedirect();
  10497. // The redirect URL should not be changed if the upgrade_if_insecure flag is
  10498. // not set.
  10499. EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
  10500. EXPECT_FALSE(d.redirect_info().insecure_scheme_was_upgraded);
  10501. }
  10502. // Test that URLRequests get properly tagged.
  10503. #if BUILDFLAG(IS_ANDROID)
  10504. TEST_F(URLRequestTestHTTP, TestTagging) {
  10505. if (!CanGetTaggedBytes()) {
  10506. DVLOG(0) << "Skipping test - GetTaggedBytes unsupported.";
  10507. return;
  10508. }
  10509. ASSERT_TRUE(http_test_server()->Start());
  10510. // The tag under which the system reports untagged traffic.
  10511. static const int32_t UNTAGGED_TAG = 0;
  10512. uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
  10513. // Untagged traffic should be tagged with tag UNTAGGED_TAG.
  10514. TestDelegate delegate;
  10515. std::unique_ptr<URLRequest> req(default_context().CreateRequest(
  10516. http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
  10517. TRAFFIC_ANNOTATION_FOR_TESTS));
  10518. EXPECT_EQ(SocketTag(), req->socket_tag());
  10519. req->Start();
  10520. delegate.RunUntilComplete();
  10521. EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
  10522. int32_t tag_val1 = 0x12345678;
  10523. SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
  10524. old_traffic = GetTaggedBytes(tag_val1);
  10525. // Test specific tag value.
  10526. req = default_context().CreateRequest(http_test_server()->GetURL("/"),
  10527. DEFAULT_PRIORITY, &delegate,
  10528. TRAFFIC_ANNOTATION_FOR_TESTS);
  10529. req->set_socket_tag(tag1);
  10530. EXPECT_EQ(tag1, req->socket_tag());
  10531. req->Start();
  10532. delegate.RunUntilComplete();
  10533. EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
  10534. }
  10535. #endif
  10536. namespace {
  10537. class ReadBufferingListener
  10538. : public test_server::EmbeddedTestServerConnectionListener {
  10539. public:
  10540. ReadBufferingListener() = default;
  10541. ~ReadBufferingListener() override = default;
  10542. void BufferNextConnection(int buffer_size) { buffer_size_ = buffer_size; }
  10543. std::unique_ptr<StreamSocket> AcceptedSocket(
  10544. std::unique_ptr<StreamSocket> socket) override {
  10545. if (!buffer_size_) {
  10546. return socket;
  10547. }
  10548. auto wrapped =
  10549. std::make_unique<ReadBufferingStreamSocket>(std::move(socket));
  10550. wrapped->BufferNextRead(buffer_size_);
  10551. // Do not buffer subsequent connections, which may be a 0-RTT retry.
  10552. buffer_size_ = 0;
  10553. return wrapped;
  10554. }
  10555. void ReadFromSocket(const StreamSocket& socket, int rv) override {}
  10556. private:
  10557. int buffer_size_ = 0;
  10558. };
  10559. // Provides a response to the 0RTT request indicating whether it was received
  10560. // as early data, sending HTTP_TOO_EARLY if enabled.
  10561. class ZeroRTTResponse : public test_server::BasicHttpResponse {
  10562. public:
  10563. ZeroRTTResponse(bool zero_rtt, bool send_too_early)
  10564. : zero_rtt_(zero_rtt), send_too_early_(send_too_early) {}
  10565. ZeroRTTResponse(const ZeroRTTResponse&) = delete;
  10566. ZeroRTTResponse& operator=(const ZeroRTTResponse&) = delete;
  10567. ~ZeroRTTResponse() override = default;
  10568. void SendResponse(
  10569. base::WeakPtr<test_server::HttpResponseDelegate> delegate) override {
  10570. AddCustomHeader("Vary", "Early-Data");
  10571. set_content_type("text/plain");
  10572. AddCustomHeader("Cache-Control", "no-cache");
  10573. if (zero_rtt_) {
  10574. if (send_too_early_)
  10575. set_code(HTTP_TOO_EARLY);
  10576. set_content("1");
  10577. } else {
  10578. set_content("0");
  10579. }
  10580. // Since the EmbeddedTestServer doesn't keep the socket open by default,
  10581. // it is explicitly kept alive to allow the remaining leg of the 0RTT
  10582. // handshake to be received after the early data.
  10583. delegate->SendResponseHeaders(code(), GetHttpReasonPhrase(code()),
  10584. BuildHeaders());
  10585. delegate->SendContents(content(), base::DoNothing());
  10586. }
  10587. private:
  10588. bool zero_rtt_;
  10589. bool send_too_early_;
  10590. };
  10591. std::unique_ptr<test_server::HttpResponse> HandleZeroRTTRequest(
  10592. const test_server::HttpRequest& request) {
  10593. DCHECK(request.ssl_info);
  10594. if (request.GetURL().path() != "/zerortt")
  10595. return nullptr;
  10596. return std::make_unique<ZeroRTTResponse>(
  10597. request.ssl_info->early_data_received, false);
  10598. }
  10599. } // namespace
  10600. class HTTPSEarlyDataTest : public TestWithTaskEnvironment {
  10601. public:
  10602. HTTPSEarlyDataTest() : test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
  10603. HttpNetworkSessionParams params;
  10604. params.enable_early_data = true;
  10605. auto cert_verifier = std::make_unique<MockCertVerifier>();
  10606. cert_verifier->set_default_result(OK);
  10607. SSLContextConfig config;
  10608. config.version_max = SSL_PROTOCOL_VERSION_TLS1_3;
  10609. auto context_builder = CreateTestURLRequestContextBuilder();
  10610. context_builder->set_http_network_session_params(params);
  10611. context_builder->SetCertVerifier(std::move(cert_verifier));
  10612. context_builder->set_ssl_config_service(
  10613. std::make_unique<TestSSLConfigService>(config));
  10614. context_ = context_builder->Build();
  10615. test_server_.SetSSLConfig(
  10616. net::EmbeddedTestServer::CERT_OK,
  10617. CreateSSLServerConfig(SSL_PROTOCOL_VERSION_TLS1_3));
  10618. RegisterDefaultHandlers(&test_server_);
  10619. test_server_.RegisterRequestHandler(
  10620. base::BindRepeating(&HandleZeroRTTRequest));
  10621. test_server_.SetConnectionListener(&listener_);
  10622. }
  10623. ~HTTPSEarlyDataTest() override = default;
  10624. URLRequestContext& context() { return *context_; }
  10625. static SSLServerConfig CreateSSLServerConfig(uint16_t version) {
  10626. SSLServerConfig ssl_config;
  10627. ssl_config.version_max = version;
  10628. ssl_config.early_data_enabled = true;
  10629. return ssl_config;
  10630. }
  10631. void ResetSSLConfig(net::EmbeddedTestServer::ServerCertificate cert,
  10632. uint16_t version) {
  10633. SSLServerConfig ssl_config = CreateSSLServerConfig(version);
  10634. test_server_.ResetSSLConfig(cert, ssl_config);
  10635. }
  10636. protected:
  10637. std::unique_ptr<URLRequestContext> context_;
  10638. ReadBufferingListener listener_;
  10639. EmbeddedTestServer test_server_;
  10640. };
  10641. // TLSEarlyDataTest tests that we handle early data correctly.
  10642. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTest) {
  10643. ASSERT_TRUE(test_server_.Start());
  10644. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10645. // kParamSize must be larger than any ClientHello sent by the client, but
  10646. // smaller than the maximum amount of early data allowed by the server.
  10647. const int kParamSize = 4 * 1024;
  10648. const GURL kUrl =
  10649. test_server_.GetURL("/zerortt?" + std::string(kParamSize, 'a'));
  10650. {
  10651. TestDelegate d;
  10652. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10653. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10654. r->Start();
  10655. EXPECT_TRUE(r->is_pending());
  10656. base::RunLoop().Run();
  10657. EXPECT_EQ(1, d.response_started_count());
  10658. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10659. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10660. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10661. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10662. r->ssl_info().cert.get()));
  10663. // The Early-Data header should be omitted in the initial request, and the
  10664. // handler should return "0".
  10665. EXPECT_EQ("0", d.data_received());
  10666. }
  10667. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10668. ERR_FAILED, "Very good reason");
  10669. // 0-RTT inherently involves a race condition: if the server responds with the
  10670. // ServerHello before the client sends the HTTP request (the client may be
  10671. // busy verifying a certificate), the client will send data over 1-RTT keys
  10672. // rather than 0-RTT.
  10673. //
  10674. // This test ensures 0-RTT is sent if relevant by making the test server wait
  10675. // for both the ClientHello and 0-RTT HTTP request before responding. We use
  10676. // a ReadBufferingStreamSocket and enable buffering for the 0-RTT request. The
  10677. // buffer size must be larger than the ClientHello but smaller than the
  10678. // ClientHello combined with the HTTP request.
  10679. listener_.BufferNextConnection(kParamSize);
  10680. {
  10681. TestDelegate d;
  10682. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10683. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10684. r->Start();
  10685. EXPECT_TRUE(r->is_pending());
  10686. base::RunLoop().Run();
  10687. EXPECT_EQ(1, d.response_started_count());
  10688. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10689. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10690. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10691. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10692. r->ssl_info().cert.get()));
  10693. // The Early-Data header should be a single '1' in the resumed request, and
  10694. // the handler should return "1".
  10695. EXPECT_EQ("1", d.data_received());
  10696. }
  10697. }
  10698. // TLSEarlyDataTest tests that we handle early data correctly for POST.
  10699. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataPOSTTest) {
  10700. ASSERT_TRUE(test_server_.Start());
  10701. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10702. {
  10703. TestDelegate d;
  10704. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10705. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10706. TRAFFIC_ANNOTATION_FOR_TESTS));
  10707. r->Start();
  10708. EXPECT_TRUE(r->is_pending());
  10709. base::RunLoop().Run();
  10710. EXPECT_EQ(1, d.response_started_count());
  10711. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10712. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10713. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10714. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10715. r->ssl_info().cert.get()));
  10716. // The Early-Data header should be omitted in the initial request, and the
  10717. // handler should return "0".
  10718. EXPECT_EQ("0", d.data_received());
  10719. }
  10720. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10721. ERR_FAILED, "Very good reason");
  10722. {
  10723. TestDelegate d;
  10724. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10725. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10726. TRAFFIC_ANNOTATION_FOR_TESTS));
  10727. r->set_method("POST");
  10728. r->Start();
  10729. EXPECT_TRUE(r->is_pending());
  10730. base::RunLoop().Run();
  10731. EXPECT_EQ(1, d.response_started_count());
  10732. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10733. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10734. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10735. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10736. r->ssl_info().cert.get()));
  10737. // The Early-Data header should be omitted in the request, since we don't
  10738. // send POSTs over early data, and the handler should return "0".
  10739. EXPECT_EQ("0", d.data_received());
  10740. }
  10741. }
  10742. // TLSEarlyDataTest tests that the 0-RTT is enabled for idempotent POST request.
  10743. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataIdempotentPOSTTest) {
  10744. ASSERT_TRUE(test_server_.Start());
  10745. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10746. const int kParamSize = 4 * 1024;
  10747. const GURL kUrl =
  10748. test_server_.GetURL("/zerortt?" + std::string(kParamSize, 'a'));
  10749. {
  10750. TestDelegate d;
  10751. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10752. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10753. r->Start();
  10754. EXPECT_TRUE(r->is_pending());
  10755. base::RunLoop().Run();
  10756. EXPECT_EQ(1, d.response_started_count());
  10757. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10758. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10759. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10760. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10761. r->ssl_info().cert.get()));
  10762. // The Early-Data header should be omitted in the initial request, and the
  10763. // handler should return "0".
  10764. EXPECT_EQ("0", d.data_received());
  10765. }
  10766. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10767. ERR_FAILED, "Very good reason");
  10768. listener_.BufferNextConnection(kParamSize);
  10769. {
  10770. TestDelegate d;
  10771. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10772. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10773. r->set_method("POST");
  10774. r->SetIdempotency(net::IDEMPOTENT);
  10775. r->Start();
  10776. EXPECT_TRUE(r->is_pending());
  10777. base::RunLoop().Run();
  10778. EXPECT_EQ(1, d.response_started_count());
  10779. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10780. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10781. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10782. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10783. r->ssl_info().cert.get()));
  10784. // The Early-Data header should be set since the request is set as an
  10785. // idempotent POST request.
  10786. EXPECT_EQ("1", d.data_received());
  10787. }
  10788. }
  10789. // TLSEarlyDataTest tests that the 0-RTT is disabled for non-idempotent request.
  10790. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataNonIdempotentRequestTest) {
  10791. ASSERT_TRUE(test_server_.Start());
  10792. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10793. {
  10794. TestDelegate d;
  10795. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10796. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10797. TRAFFIC_ANNOTATION_FOR_TESTS));
  10798. r->Start();
  10799. EXPECT_TRUE(r->is_pending());
  10800. base::RunLoop().Run();
  10801. EXPECT_EQ(1, d.response_started_count());
  10802. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10803. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10804. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10805. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10806. r->ssl_info().cert.get()));
  10807. // The Early-Data header should be omitted in the initial request, and the
  10808. // handler should return "0".
  10809. EXPECT_EQ("0", d.data_received());
  10810. }
  10811. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10812. ERR_FAILED, "Very good reason");
  10813. {
  10814. TestDelegate d;
  10815. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10816. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10817. TRAFFIC_ANNOTATION_FOR_TESTS));
  10818. // Sets the GET request as not idempotent.
  10819. r->SetIdempotency(net::NOT_IDEMPOTENT);
  10820. r->Start();
  10821. EXPECT_TRUE(r->is_pending());
  10822. base::RunLoop().Run();
  10823. EXPECT_EQ(1, d.response_started_count());
  10824. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10825. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10826. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10827. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10828. r->ssl_info().cert.get()));
  10829. // The Early-Data header should be omitted in the initial request even
  10830. // though it is a GET request, since the request is set as not idempotent.
  10831. EXPECT_EQ("0", d.data_received());
  10832. }
  10833. }
  10834. std::unique_ptr<test_server::HttpResponse> HandleTooEarly(
  10835. bool* sent_425,
  10836. const test_server::HttpRequest& request) {
  10837. DCHECK(request.ssl_info);
  10838. if (request.GetURL().path() != "/tooearly")
  10839. return nullptr;
  10840. if (request.ssl_info->early_data_received)
  10841. *sent_425 = true;
  10842. return std::make_unique<ZeroRTTResponse>(
  10843. request.ssl_info->early_data_received, true);
  10844. }
  10845. // Test that we handle 425 (Too Early) correctly.
  10846. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTooEarlyTest) {
  10847. bool sent_425 = false;
  10848. test_server_.RegisterRequestHandler(
  10849. base::BindRepeating(&HandleTooEarly, base::Unretained(&sent_425)));
  10850. ASSERT_TRUE(test_server_.Start());
  10851. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10852. // kParamSize must be larger than any ClientHello sent by the client, but
  10853. // smaller than the maximum amount of early data allowed by the server.
  10854. const int kParamSize = 4 * 1024;
  10855. const GURL kUrl =
  10856. test_server_.GetURL("/tooearly?" + std::string(kParamSize, 'a'));
  10857. {
  10858. TestDelegate d;
  10859. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10860. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10861. r->Start();
  10862. EXPECT_TRUE(r->is_pending());
  10863. d.RunUntilComplete();
  10864. EXPECT_EQ(1, d.response_started_count());
  10865. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10866. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10867. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10868. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10869. r->ssl_info().cert.get()));
  10870. // The Early-Data header should be omitted in the initial request, and the
  10871. // handler should return "0".
  10872. EXPECT_EQ("0", d.data_received());
  10873. EXPECT_FALSE(sent_425);
  10874. }
  10875. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10876. ERR_FAILED, "Very good reason");
  10877. // 0-RTT inherently involves a race condition: if the server responds with the
  10878. // ServerHello before the client sends the HTTP request (the client may be
  10879. // busy verifying a certificate), the client will send data over 1-RTT keys
  10880. // rather than 0-RTT.
  10881. //
  10882. // This test ensures 0-RTT is sent if relevant by making the test server wait
  10883. // for both the ClientHello and 0-RTT HTTP request before responding. We use
  10884. // a ReadBufferingStreamSocket and enable buffering for the 0-RTT request. The
  10885. // buffer size must be larger than the ClientHello but smaller than the
  10886. // ClientHello combined with the HTTP request.
  10887. //
  10888. // We must buffer exactly one connection because the HTTP 425 response will
  10889. // trigger a retry, potentially on a new connection.
  10890. listener_.BufferNextConnection(kParamSize);
  10891. {
  10892. TestDelegate d;
  10893. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10894. kUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  10895. r->Start();
  10896. EXPECT_TRUE(r->is_pending());
  10897. d.RunUntilComplete();
  10898. EXPECT_EQ(1, d.response_started_count());
  10899. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10900. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10901. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10902. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10903. r->ssl_info().cert.get()));
  10904. // The resumption request will encounter a 425 error and retry without early
  10905. // data, and the handler should return "0".
  10906. EXPECT_EQ("0", d.data_received());
  10907. EXPECT_TRUE(sent_425);
  10908. }
  10909. }
  10910. // TLSEarlyDataRejectTest tests that we gracefully handle an early data reject
  10911. // and retry without early data.
  10912. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataRejectTest) {
  10913. ASSERT_TRUE(test_server_.Start());
  10914. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10915. {
  10916. TestDelegate d;
  10917. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10918. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10919. TRAFFIC_ANNOTATION_FOR_TESTS));
  10920. r->Start();
  10921. EXPECT_TRUE(r->is_pending());
  10922. d.RunUntilComplete();
  10923. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10924. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10925. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10926. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10927. r->ssl_info().cert.get()));
  10928. // The Early-Data header should be omitted in the initial request, and the
  10929. // handler should return "0".
  10930. EXPECT_EQ("0", d.data_received());
  10931. }
  10932. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10933. ERR_FAILED, "Very good reason");
  10934. // The certificate in the resumption is changed to confirm that the
  10935. // certificate change is observed.
  10936. scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
  10937. ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
  10938. SSL_PROTOCOL_VERSION_TLS1_3);
  10939. {
  10940. TestDelegate d;
  10941. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10942. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10943. TRAFFIC_ANNOTATION_FOR_TESTS));
  10944. r->Start();
  10945. EXPECT_TRUE(r->is_pending());
  10946. d.RunUntilComplete();
  10947. EXPECT_EQ(1, d.response_started_count());
  10948. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10949. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10950. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10951. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10952. r->ssl_info().cert.get()));
  10953. EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
  10954. // The Early-Data header should be omitted in the rejected request, and the
  10955. // handler should return "0".
  10956. EXPECT_EQ("0", d.data_received());
  10957. }
  10958. }
  10959. // TLSEarlyDataTLS12RejectTest tests that we gracefully handle an early data
  10960. // reject from a TLS 1.2 server and retry without early data.
  10961. TEST_F(HTTPSEarlyDataTest, TLSEarlyDataTLS12RejectTest) {
  10962. ASSERT_TRUE(test_server_.Start());
  10963. context().http_transaction_factory()->GetSession()->ClearSSLSessionCache();
  10964. {
  10965. TestDelegate d;
  10966. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10967. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10968. TRAFFIC_ANNOTATION_FOR_TESTS));
  10969. r->Start();
  10970. EXPECT_TRUE(r->is_pending());
  10971. d.RunUntilComplete();
  10972. EXPECT_EQ(1, d.response_started_count());
  10973. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_3,
  10974. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  10975. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  10976. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  10977. r->ssl_info().cert.get()));
  10978. // The Early-Data header should be omitted in the initial request, and the
  10979. // handler should return "0".
  10980. EXPECT_EQ("0", d.data_received());
  10981. }
  10982. context().http_transaction_factory()->GetSession()->CloseAllConnections(
  10983. ERR_FAILED, "Very good reason");
  10984. // The certificate in the resumption is changed to confirm that the
  10985. // certificate change is observed.
  10986. scoped_refptr<X509Certificate> old_cert = test_server_.GetCertificate();
  10987. ResetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED,
  10988. SSL_PROTOCOL_VERSION_TLS1_2);
  10989. {
  10990. TestDelegate d;
  10991. std::unique_ptr<URLRequest> r(context().CreateRequest(
  10992. test_server_.GetURL("/zerortt"), DEFAULT_PRIORITY, &d,
  10993. TRAFFIC_ANNOTATION_FOR_TESTS));
  10994. r->Start();
  10995. EXPECT_TRUE(r->is_pending());
  10996. d.RunUntilComplete();
  10997. EXPECT_EQ(1, d.response_started_count());
  10998. EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1_2,
  10999. SSLConnectionStatusToVersion(r->ssl_info().connection_status));
  11000. EXPECT_TRUE(r->ssl_info().unverified_cert.get());
  11001. EXPECT_TRUE(test_server_.GetCertificate()->EqualsIncludingChain(
  11002. r->ssl_info().cert.get()));
  11003. EXPECT_FALSE(old_cert->EqualsIncludingChain(r->ssl_info().cert.get()));
  11004. // The Early-Data header should be omitted in the rejected request, and the
  11005. // handler should return "0".
  11006. EXPECT_EQ("0", d.data_received());
  11007. }
  11008. }
  11009. // Tests that AuthChallengeInfo is available on the request.
  11010. TEST_F(URLRequestTestHTTP, AuthChallengeInfo) {
  11011. ASSERT_TRUE(http_test_server()->Start());
  11012. GURL url(http_test_server()->GetURL("/auth-basic"));
  11013. TestDelegate delegate;
  11014. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  11015. url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
  11016. r->Start();
  11017. delegate.RunUntilComplete();
  11018. ASSERT_TRUE(r->auth_challenge_info().has_value());
  11019. EXPECT_FALSE(r->auth_challenge_info()->is_proxy);
  11020. EXPECT_EQ(url::SchemeHostPort(url), r->auth_challenge_info()->challenger);
  11021. EXPECT_EQ("basic", r->auth_challenge_info()->scheme);
  11022. EXPECT_EQ("testrealm", r->auth_challenge_info()->realm);
  11023. EXPECT_EQ("Basic realm=\"testrealm\"", r->auth_challenge_info()->challenge);
  11024. EXPECT_EQ("/auth-basic", r->auth_challenge_info()->path);
  11025. }
  11026. class URLRequestDnsAliasTest : public TestWithTaskEnvironment {
  11027. protected:
  11028. URLRequestDnsAliasTest() {
  11029. auto context_builder = CreateTestURLRequestContextBuilder();
  11030. context_builder->set_host_resolver(std::make_unique<MockHostResolver>());
  11031. context_ = context_builder->Build();
  11032. }
  11033. URLRequestContext& context() { return *context_; }
  11034. MockHostResolver& host_resolver() {
  11035. // This cast is safe because we provided a MockHostResolver in the ctor.
  11036. return *static_cast<MockHostResolver*>(context_->host_resolver());
  11037. }
  11038. void SetUp() override { ASSERT_TRUE(test_server_.Start()); }
  11039. std::unique_ptr<URLRequestContext> context_;
  11040. TestDelegate test_delegate_;
  11041. EmbeddedTestServer test_server_;
  11042. };
  11043. TEST_F(URLRequestDnsAliasTest, WithDnsAliases) {
  11044. GURL url(test_server_.GetURL("www.example.test", "/echo"));
  11045. std::vector<std::string> aliases({"alias1", "alias2", "host"});
  11046. host_resolver().rules()->AddIPLiteralRuleWithDnsAliases(
  11047. "www.example.test", "127.0.0.1", std::move(aliases));
  11048. std::unique_ptr<URLRequest> request(context().CreateRequest(
  11049. url, DEFAULT_PRIORITY, &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
  11050. request->Start();
  11051. test_delegate_.RunUntilComplete();
  11052. EXPECT_THAT(test_delegate_.request_status(), IsOk());
  11053. EXPECT_THAT(request->response_info().dns_aliases,
  11054. testing::ElementsAre("alias1", "alias2", "host"));
  11055. }
  11056. TEST_F(URLRequestDnsAliasTest, NoAdditionalDnsAliases) {
  11057. GURL url(test_server_.GetURL("www.example.test", "/echo"));
  11058. host_resolver().rules()->AddIPLiteralRuleWithDnsAliases(
  11059. "www.example.test", "127.0.0.1", /*dns_aliases=*/std::set<std::string>());
  11060. std::unique_ptr<URLRequest> request(context().CreateRequest(
  11061. url, DEFAULT_PRIORITY, &test_delegate_, TRAFFIC_ANNOTATION_FOR_TESTS));
  11062. request->Start();
  11063. test_delegate_.RunUntilComplete();
  11064. EXPECT_THAT(test_delegate_.request_status(), IsOk());
  11065. EXPECT_THAT(request->response_info().dns_aliases,
  11066. testing::ElementsAre("www.example.test"));
  11067. }
  11068. TEST_F(URLRequestTest, SetURLChain) {
  11069. TestDelegate d;
  11070. {
  11071. GURL original_url("http://localhost");
  11072. std::unique_ptr<URLRequest> r(default_context().CreateRequest(
  11073. original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  11074. EXPECT_EQ(r->url_chain().size(), 1u);
  11075. EXPECT_EQ(r->url_chain()[0], original_url);
  11076. const std::vector<GURL> url_chain = {
  11077. GURL("http://foo.test"),
  11078. GURL("http://bar.test"),
  11079. GURL("http://baz.test"),
  11080. };
  11081. r->SetURLChain(url_chain);
  11082. EXPECT_EQ(r->url_chain().size(), 3u);
  11083. EXPECT_EQ(r->url_chain()[0], url_chain[0]);
  11084. EXPECT_EQ(r->url_chain()[1], url_chain[1]);
  11085. EXPECT_EQ(r->url_chain()[2], original_url);
  11086. }
  11087. }
  11088. class URLRequestMaybeAsyncFirstPartySetsTest
  11089. : public URLRequestTest,
  11090. public testing::WithParamInterface<bool> {
  11091. public:
  11092. URLRequestMaybeAsyncFirstPartySetsTest() { CHECK(test_server_.Start()); }
  11093. std::unique_ptr<CookieStore> CreateCookieStore() {
  11094. auto cookie_monster =
  11095. std::make_unique<CookieMonster>(/*store=*/nullptr,
  11096. /*net_log=*/nullptr,
  11097. /*first_party_sets_enabled=*/true);
  11098. auto cookie_access_delegate = std::make_unique<TestCookieAccessDelegate>();
  11099. cookie_access_delegate->set_invoke_callbacks_asynchronously(
  11100. invoke_callbacks_asynchronously());
  11101. cookie_monster->SetCookieAccessDelegate(std::move(cookie_access_delegate));
  11102. return cookie_monster;
  11103. }
  11104. bool invoke_callbacks_asynchronously() { return GetParam(); }
  11105. HttpTestServer& test_server() { return test_server_; }
  11106. private:
  11107. HttpTestServer test_server_;
  11108. };
  11109. TEST_P(URLRequestMaybeAsyncFirstPartySetsTest, SimpleRequest) {
  11110. const std::string kHost = "example.test";
  11111. const url::Origin kOrigin =
  11112. url::Origin::Create(test_server().GetURL(kHost, "/"));
  11113. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  11114. auto context_builder = CreateTestURLRequestContextBuilder();
  11115. context_builder->SetCookieStore(CreateCookieStore());
  11116. auto context = context_builder->Build();
  11117. TestDelegate d;
  11118. std::unique_ptr<URLRequest> req(context->CreateRequest(
  11119. test_server().GetURL(kHost, "/echo"), DEFAULT_PRIORITY, &d,
  11120. TRAFFIC_ANNOTATION_FOR_TESTS));
  11121. req->set_isolation_info(
  11122. IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
  11123. kOrigin, kSiteForCookies, {} /* party_context */));
  11124. req->Start();
  11125. d.RunUntilComplete();
  11126. EXPECT_EQ(d.data_received(), "Echo");
  11127. EXPECT_THAT(d.request_status(), IsOk());
  11128. EXPECT_EQ(req->GetResponseCode(), 200);
  11129. }
  11130. TEST_P(URLRequestMaybeAsyncFirstPartySetsTest, SingleRedirect) {
  11131. const std::string kHost = "example.test";
  11132. const url::Origin kOrigin =
  11133. url::Origin::Create(test_server().GetURL(kHost, "/"));
  11134. const SiteForCookies kSiteForCookies = SiteForCookies::FromOrigin(kOrigin);
  11135. auto context_builder = CreateTestURLRequestContextBuilder();
  11136. context_builder->SetCookieStore(CreateCookieStore());
  11137. auto context = context_builder->Build();
  11138. TestDelegate d;
  11139. std::unique_ptr<URLRequest> req(context->CreateRequest(
  11140. test_server().GetURL(kHost,
  11141. base::StrCat({
  11142. "/server-redirect?",
  11143. test_server().GetURL(kHost, "/echo").spec(),
  11144. })),
  11145. DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
  11146. req->set_isolation_info(
  11147. IsolationInfo::Create(IsolationInfo::RequestType::kMainFrame, kOrigin,
  11148. kOrigin, kSiteForCookies, {} /* party_context */));
  11149. req->Start();
  11150. d.RunUntilComplete();
  11151. EXPECT_EQ(d.data_received(), "Echo");
  11152. EXPECT_THAT(d.request_status(), IsOk());
  11153. EXPECT_EQ(req->GetResponseCode(), 200);
  11154. }
  11155. INSTANTIATE_TEST_SUITE_P(,
  11156. URLRequestMaybeAsyncFirstPartySetsTest,
  11157. testing::Bool());
  11158. } // namespace net