sftpd_test.go 167 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312
  1. package sftpd_test
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/rand"
  6. "crypto/sha256"
  7. "crypto/sha512"
  8. "encoding/json"
  9. "fmt"
  10. "hash"
  11. "io"
  12. "io/ioutil"
  13. "math"
  14. "net"
  15. "net/http"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "path/filepath"
  20. "runtime"
  21. "strings"
  22. "testing"
  23. "time"
  24. _ "github.com/go-sql-driver/mysql"
  25. _ "github.com/lib/pq"
  26. _ "github.com/mattn/go-sqlite3"
  27. "golang.org/x/crypto/ssh"
  28. "github.com/drakkan/sftpgo/config"
  29. "github.com/drakkan/sftpgo/dataprovider"
  30. "github.com/drakkan/sftpgo/httpd"
  31. "github.com/drakkan/sftpgo/logger"
  32. "github.com/drakkan/sftpgo/sftpd"
  33. "github.com/drakkan/sftpgo/utils"
  34. "github.com/drakkan/sftpgo/vfs"
  35. "github.com/pkg/sftp"
  36. "github.com/rs/zerolog"
  37. )
  38. const (
  39. logSender = "sftpdTesting"
  40. sftpServerAddr = "127.0.0.1:2022"
  41. defaultUsername = "test_user_sftp"
  42. defaultPassword = "test_password"
  43. testPubKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC03jj0D+djk7pxIf/0OhrxrchJTRZklofJ1NoIu4752Sq02mdXmarMVsqJ1cAjV5LBVy3D1F5U6XW4rppkXeVtd04Pxb09ehtH0pRRPaoHHlALiJt8CoMpbKYMA8b3KXPPriGxgGomvtU2T2RMURSwOZbMtpsugfjYSWenyYX+VORYhylWnSXL961LTyC21ehd6d6QnW9G7E5hYMITMY9TuQZz3bROYzXiTsgN0+g6Hn7exFQp50p45StUMfV/SftCMdCxlxuyGny2CrN/vfjO7xxOo2uv7q1qm10Q46KPWJQv+pgZ/OfL+EDjy07n5QVSKHlbx+2nT4Q0EgOSQaCTYwn3YjtABfIxWwgAFdyj6YlPulCL22qU4MYhDcA6PSBwDdf8hvxBfvsiHdM+JcSHvv8/VeJhk6CmnZxGY0fxBupov27z3yEO8nAg8k+6PaUiW1MSUfuGMF/ktB8LOstXsEPXSszuyXiOv4DaryOXUiSn7bmRqKcEFlJusO6aZP0= nicola@p1"
  44. testPubKey1 = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCd60+/j+y8f0tLftihWV1YN9RSahMI9btQMDIMqts/jeNbD8jgoogM3nhF7KxfcaMKURuD47KC4Ey6iAJUJ0sWkSNNxOcIYuvA+5MlspfZDsa8Ag76Fe1vyz72WeHMHMeh/hwFo2TeIeIXg480T1VI6mzfDrVp2GzUx0SS0dMsQBjftXkuVR8YOiOwMCAH2a//M1OrvV7d/NBk6kBN0WnuIBb2jKm15PAA7+jQQG7tzwk2HedNH3jeL5GH31xkSRwlBczRK0xsCQXehAlx6cT/e/s44iJcJTHfpPKoSk6UAhPJYe7Z1QnuoawY9P9jQaxpyeImBZxxUEowhjpj2avBxKdRGBVK8R7EL8tSOeLbhdyWe5Mwc1+foEbq9Zz5j5Kd+hn3Wm1UnsGCrXUUUoZp1jnlNl0NakCto+5KmqnT9cHxaY+ix2RLUWAZyVFlRq71OYux1UHJnEJPiEI1/tr4jFBSL46qhQZv/TfpkfVW8FLz0lErfqu0gQEZnNHr3Fc= nicola@p1"
  45. testPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
  46. b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
  47. NhAAAAAwEAAQAAAYEAtN449A/nY5O6cSH/9Doa8a3ISU0WZJaHydTaCLuO+dkqtNpnV5mq
  48. zFbKidXAI1eSwVctw9ReVOl1uK6aZF3lbXdOD8W9PXobR9KUUT2qBx5QC4ibfAqDKWymDA
  49. PG9ylzz64hsYBqJr7VNk9kTFEUsDmWzLabLoH42Elnp8mF/lTkWIcpVp0ly/etS08gttXo
  50. XenekJ1vRuxOYWDCEzGPU7kGc920TmM14k7IDdPoOh5+3sRUKedKeOUrVDH1f0n7QjHQsZ
  51. cbshp8tgqzf734zu8cTqNrr+6taptdEOOij1iUL/qYGfzny/hA48tO5+UFUih5W8ftp0+E
  52. NBIDkkGgk2MJ92I7QAXyMVsIABXco+mJT7pQi9tqlODGIQ3AOj0gcA3X/Ib8QX77Ih3TPi
  53. XEh77/P1XiYZOgpp2cRmNH8QbqaL9u898hDvJwIPJPuj2lIltTElH7hjBf5LQfCzrLV7BD
  54. 10rM7sl4jr+A2q8jl1Ikp+25kainBBZSbrDummT9AAAFgDU/VLk1P1S5AAAAB3NzaC1yc2
  55. EAAAGBALTeOPQP52OTunEh//Q6GvGtyElNFmSWh8nU2gi7jvnZKrTaZ1eZqsxWyonVwCNX
  56. ksFXLcPUXlTpdbiummRd5W13Tg/FvT16G0fSlFE9qgceUAuIm3wKgylspgwDxvcpc8+uIb
  57. GAaia+1TZPZExRFLA5lsy2my6B+NhJZ6fJhf5U5FiHKVadJcv3rUtPILbV6F3p3pCdb0bs
  58. TmFgwhMxj1O5BnPdtE5jNeJOyA3T6Doeft7EVCnnSnjlK1Qx9X9J+0Ix0LGXG7IafLYKs3
  59. +9+M7vHE6ja6/urWqbXRDjoo9YlC/6mBn858v4QOPLTuflBVIoeVvH7adPhDQSA5JBoJNj
  60. CfdiO0AF8jFbCAAV3KPpiU+6UIvbapTgxiENwDo9IHAN1/yG/EF++yId0z4lxIe+/z9V4m
  61. GToKadnEZjR/EG6mi/bvPfIQ7ycCDyT7o9pSJbUxJR+4YwX+S0Hws6y1ewQ9dKzO7JeI6/
  62. gNqvI5dSJKftuZGopwQWUm6w7ppk/QAAAAMBAAEAAAGAHKnC+Nq0XtGAkIFE4N18e6SAwy
  63. 0WSWaZqmCzFQM0S2AhJnweOIG/0ZZHjsRzKKauOTmppQk40dgVsejpytIek9R+aH172gxJ
  64. 2n4Cx0UwduRU5x8FFQlNc/kl722B0JWfJuB/snOZXv6LJ4o5aObIkozt2w9tVFeAqjYn2S
  65. 1UsNOfRHBXGsTYwpRDwFWP56nKo2d2wBBTHDhCy6fb2dLW1fvSi/YspueOGIlHpvlYKi2/
  66. CWqvs9xVrwcScMtiDoQYq0khhO0efLCxvg/o+W9CLMVM2ms4G1zoSUQKN0oYWWQJyW4+VI
  67. YneWO8UpN0J3ElXKi7bhgAat7dBaM1g9IrAzk153DiEFZNsPxGOgL/+YdQN7zUBx/z7EkI
  68. jyv80RV7fpUXvcq2p+qNl6UVig3VSzRrnsaJkUWu/A0u59ha7ocv6NxDIXjxpIDJme16GF
  69. quiGVBQNnYJymS/vFEbGf6bgf7iRmMCRUMG4nqLA6fPYP9uAtch+CmDfVLZC/fIdC5AAAA
  70. wQCDissV4zH6bfqgxJSuYNk8Vbb+19cF3b7gH1rVlB3zxpCAgcRgMHC+dP1z2NRx7UW9MR
  71. nye6kjpkzZZ0OigLqo7TtEq8uTglD9o6W7mRXqhy5A/ySOmqPL3ernHHQhGuoNODYAHkOU
  72. u2Rh8HXi+VLwKZcLInPOYJvcuLG4DxN8WfeVvlMHwhAOaTNNOtL4XZDHQeIPc4qHmJymmv
  73. sV7GuyQ6yW5C10uoGdxRPd90Bh4z4h2bKfZFjvEBbSBVkqrlAAAADBAN/zNtNayd/dX7Cr
  74. Nb4sZuzCh+CW4BH8GOePZWNCATwBbNXBVb5cR+dmuTqYm+Ekz0VxVQRA1TvKncluJOQpoa
  75. Xj8r0xdIgqkehnfDPMKtYVor06B9Fl1jrXtXU0Vrr6QcBWruSVyK1ZxqcmcNK/+KolVepe
  76. A6vcl/iKaG4U7su166nxLST06M2EgcSVsFJHpKn5+WAXC+X0Gx8kNjWIIb3GpiChdc0xZD
  77. mq02xZthVJrTCVw/e7gfDoB2QRsNV8HwAAAMEAzsCghZVp+0YsYg9oOrw4tEqcbEXEMhwY
  78. 0jW8JNL8Spr1Ibp5Dw6bRSk5azARjmJtnMJhJ3oeHfF0eoISqcNuQXGndGQbVM9YzzAzc1
  79. NbbCNsVroqKlChT5wyPNGS+phi2bPARBno7WSDvshTZ7dAVEP2c9MJW0XwoSevwKlhgSdt
  80. RLFFQ/5nclJSdzPBOmQouC0OBcMFSrYtMeknJ4VvueVvve5HcHFaEsaMc7ABAGaLYaBQOm
  81. iixITGvaNZh/tjAAAACW5pY29sYUBwMQE=
  82. -----END OPENSSH PRIVATE KEY-----`
  83. configDir = ".."
  84. )
  85. var (
  86. allPerms = []string{dataprovider.PermAny}
  87. homeBasePath string
  88. scpPath string
  89. gitPath string
  90. sshPath string
  91. pubKeyPath string
  92. privateKeyPath string
  93. gitWrapPath string
  94. extAuthPath string
  95. keyIntAuthPath string
  96. preLoginPath string
  97. logFilePath string
  98. )
  99. func TestMain(m *testing.M) {
  100. logFilePath = filepath.Join(configDir, "sftpgo_sftpd_test.log")
  101. loginBannerFileName := "login_banner"
  102. loginBannerFile := filepath.Join(configDir, loginBannerFileName)
  103. ioutil.WriteFile(loginBannerFile, []byte("simple login banner\n"), 0777)
  104. logger.InitLogger(logFilePath, 5, 1, 28, false, zerolog.DebugLevel)
  105. config.LoadConfig(configDir, "")
  106. providerConf := config.GetProviderConf()
  107. err := dataprovider.Initialize(providerConf, configDir)
  108. if err != nil {
  109. logger.Warn(logSender, "", "error initializing data provider: %v", err)
  110. os.Exit(1)
  111. }
  112. dataProvider := dataprovider.GetProvider()
  113. sftpdConf := config.GetSFTPDConfig()
  114. httpdConf := config.GetHTTPDConfig()
  115. sftpdConf.BindPort = 2022
  116. sftpdConf.KexAlgorithms = []string{"[email protected]", "ecdh-sha2-nistp256",
  117. "ecdh-sha2-nistp384"}
  118. sftpdConf.Ciphers = []string{"[email protected]", "[email protected]",
  119. "aes256-ctr"}
  120. sftpdConf.MACs = []string{"[email protected]", "hmac-sha2-256"}
  121. sftpdConf.LoginBannerFile = loginBannerFileName
  122. // we need to test all supported ssh commands
  123. sftpdConf.EnabledSSHCommands = []string{"*"}
  124. // we run the test cases with UploadMode atomic and resume support. The non atomic code path
  125. // simply does not execute some code so if it works in atomic mode will
  126. // work in non atomic mode too
  127. sftpdConf.UploadMode = 2
  128. homeBasePath = os.TempDir()
  129. var scriptArgs string
  130. if runtime.GOOS == "windows" {
  131. scriptArgs = "%*"
  132. } else {
  133. sftpdConf.Actions.ExecuteOn = []string{"download", "upload", "rename", "delete", "ssh_cmd"}
  134. sftpdConf.Actions.Command = "/usr/bin/true"
  135. sftpdConf.Actions.HTTPNotificationURL = "http://127.0.0.1:8083/"
  136. scriptArgs = "$@"
  137. }
  138. keyIntAuthPath = filepath.Join(homeBasePath, "keyintauth.sh")
  139. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  140. sftpdConf.KeyboardInteractiveProgram = keyIntAuthPath
  141. scpPath, err = exec.LookPath("scp")
  142. if err != nil {
  143. logger.Warn(logSender, "", "unable to get scp command. SCP tests will be skipped, err: %v", err)
  144. logger.WarnToConsole("unable to get scp command. SCP tests will be skipped, err: %v", err)
  145. scpPath = ""
  146. }
  147. gitPath, err = exec.LookPath("git")
  148. if err != nil {
  149. logger.Warn(logSender, "", "unable to get git command. GIT tests will be skipped, err: %v", err)
  150. logger.WarnToConsole("unable to get git command. GIT tests will be skipped, err: %v", err)
  151. gitPath = ""
  152. }
  153. sshPath, err = exec.LookPath("ssh")
  154. if err != nil {
  155. logger.Warn(logSender, "", "unable to get ssh command. GIT tests will be skipped, err: %v", err)
  156. logger.WarnToConsole("unable to get ssh command. GIT tests will be skipped, err: %v", err)
  157. gitPath = ""
  158. }
  159. pubKeyPath = filepath.Join(homeBasePath, "ssh_key.pub")
  160. privateKeyPath = filepath.Join(homeBasePath, "ssh_key")
  161. gitWrapPath = filepath.Join(homeBasePath, "gitwrap.sh")
  162. extAuthPath = filepath.Join(homeBasePath, "extauth.sh")
  163. preLoginPath = filepath.Join(homeBasePath, "prelogin.sh")
  164. err = ioutil.WriteFile(pubKeyPath, []byte(testPubKey+"\n"), 0600)
  165. if err != nil {
  166. logger.WarnToConsole("unable to save public key to file: %v", err)
  167. }
  168. err = ioutil.WriteFile(privateKeyPath, []byte(testPrivateKey+"\n"), 0600)
  169. if err != nil {
  170. logger.WarnToConsole("unable to save private key to file: %v", err)
  171. }
  172. err = ioutil.WriteFile(gitWrapPath, []byte(fmt.Sprintf("%v -i %v -oStrictHostKeyChecking=no %v\n",
  173. sshPath, privateKeyPath, scriptArgs)), 0755)
  174. if err != nil {
  175. logger.WarnToConsole("unable to save gitwrap shell script: %v", err)
  176. }
  177. sftpd.SetDataProvider(dataProvider)
  178. httpd.SetDataProvider(dataProvider)
  179. go func() {
  180. logger.Debug(logSender, "", "initializing SFTP server with config %+v", sftpdConf)
  181. if err := sftpdConf.Initialize(configDir); err != nil {
  182. logger.Error(logSender, "", "could not start SFTP server: %v", err)
  183. }
  184. }()
  185. go func() {
  186. if err := httpdConf.Initialize(configDir); err != nil {
  187. logger.Error(logSender, "", "could not start HTTP server: %v", err)
  188. }
  189. }()
  190. waitTCPListening(fmt.Sprintf("%s:%d", sftpdConf.BindAddress, sftpdConf.BindPort))
  191. waitTCPListening(fmt.Sprintf("%s:%d", httpdConf.BindAddress, httpdConf.BindPort))
  192. sftpdConf.BindPort = 2222
  193. sftpdConf.ProxyProtocol = 1
  194. go func() {
  195. logger.Debug(logSender, "", "initializing SFTP server with config %+v", sftpdConf)
  196. if err := sftpdConf.Initialize(configDir); err != nil {
  197. logger.Error(logSender, "", "could not start SFTP server: %v", err)
  198. }
  199. }()
  200. waitTCPListening(fmt.Sprintf("%s:%d", sftpdConf.BindAddress, sftpdConf.BindPort))
  201. sftpdConf.BindPort = 2224
  202. sftpdConf.ProxyProtocol = 2
  203. go func() {
  204. logger.Debug(logSender, "", "initializing SFTP server with config %+v", sftpdConf)
  205. if err := sftpdConf.Initialize(configDir); err != nil {
  206. logger.Error(logSender, "", "could not start SFTP server: %v", err)
  207. }
  208. }()
  209. waitTCPListening(fmt.Sprintf("%s:%d", sftpdConf.BindAddress, sftpdConf.BindPort))
  210. exitCode := m.Run()
  211. os.Remove(logFilePath)
  212. os.Remove(loginBannerFile)
  213. os.Remove(pubKeyPath)
  214. os.Remove(privateKeyPath)
  215. os.Remove(gitWrapPath)
  216. os.Remove(extAuthPath)
  217. os.Remove(preLoginPath)
  218. os.Remove(keyIntAuthPath)
  219. os.Exit(exitCode)
  220. }
  221. func TestInitialization(t *testing.T) {
  222. config.LoadConfig(configDir, "")
  223. sftpdConf := config.GetSFTPDConfig()
  224. sftpdConf.Umask = "invalid umask"
  225. sftpdConf.BindPort = 2022
  226. sftpdConf.LoginBannerFile = "invalid_file"
  227. sftpdConf.IsSCPEnabled = true
  228. sftpdConf.EnabledSSHCommands = append(sftpdConf.EnabledSSHCommands, "ls")
  229. err := sftpdConf.Initialize(configDir)
  230. if err == nil {
  231. t.Error("Inizialize must fail, a SFTP server should be already running")
  232. }
  233. sftpdConf.KeyboardInteractiveProgram = "invalid_file"
  234. err = sftpdConf.Initialize(configDir)
  235. if err == nil {
  236. t.Error("Inizialize must fail, a SFTP server should be already running")
  237. }
  238. sftpdConf.KeyboardInteractiveProgram = filepath.Join(homeBasePath, "invalid_file")
  239. err = sftpdConf.Initialize(configDir)
  240. if err == nil {
  241. t.Error("Inizialize must fail, a SFTP server should be already running")
  242. }
  243. }
  244. func TestBasicSFTPHandling(t *testing.T) {
  245. usePubKey := false
  246. u := getTestUser(usePubKey)
  247. u.QuotaSize = 6553600
  248. user, _, err := httpd.AddUser(u, http.StatusOK)
  249. if err != nil {
  250. t.Errorf("unable to add user: %v", err)
  251. }
  252. os.RemoveAll(user.GetHomeDir())
  253. client, err := getSftpClient(user, usePubKey)
  254. if err != nil {
  255. t.Errorf("unable to create sftp client: %v", err)
  256. } else {
  257. defer client.Close()
  258. testFileName := "test_file.dat"
  259. testFilePath := filepath.Join(homeBasePath, testFileName)
  260. testFileSize := int64(65535)
  261. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  262. expectedQuotaFiles := user.UsedQuotaFiles + 1
  263. createTestFile(testFilePath, testFileSize)
  264. err = sftpUploadFile(testFilePath, path.Join("/missing_dir", testFileName), testFileSize, client)
  265. if err == nil {
  266. t.Errorf("upload a file to a missing dir must fail")
  267. }
  268. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  269. if err != nil {
  270. t.Errorf("file upload error: %v", err)
  271. }
  272. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  273. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  274. if err != nil {
  275. t.Errorf("file download error: %v", err)
  276. }
  277. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  278. if err != nil {
  279. t.Errorf("error getting user: %v", err)
  280. }
  281. if expectedQuotaFiles != user.UsedQuotaFiles {
  282. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  283. }
  284. if expectedQuotaSize != user.UsedQuotaSize {
  285. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  286. }
  287. err = client.Remove(testFileName)
  288. if err != nil {
  289. t.Errorf("error removing uploaded file: %v", err)
  290. }
  291. _, err = client.Lstat(testFileName)
  292. if err == nil {
  293. t.Errorf("stat for deleted file must not succeed")
  294. }
  295. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  296. if err != nil {
  297. t.Errorf("error getting user: %v", err)
  298. }
  299. if (expectedQuotaFiles - 1) != user.UsedQuotaFiles {
  300. t.Errorf("quota files does not match after delete, expected: %v, actual: %v", expectedQuotaFiles-1, user.UsedQuotaFiles)
  301. }
  302. if (expectedQuotaSize - testFileSize) != user.UsedQuotaSize {
  303. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize-testFileSize, user.UsedQuotaSize)
  304. }
  305. os.Remove(testFilePath)
  306. os.Remove(localDownloadPath)
  307. }
  308. _, err = httpd.RemoveUser(user, http.StatusOK)
  309. if err != nil {
  310. t.Errorf("unable to remove user: %v", err)
  311. }
  312. os.RemoveAll(user.GetHomeDir())
  313. }
  314. func TestProxyProtocol(t *testing.T) {
  315. usePubKey := false
  316. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  317. if err != nil {
  318. t.Errorf("unable to add user: %v", err)
  319. }
  320. // remove the home dir to test auto creation
  321. os.RemoveAll(user.HomeDir)
  322. client, err := getSftpClientWithAddr(user, usePubKey, "127.0.0.1:2222")
  323. if err != nil {
  324. t.Errorf("unable to create sftp client: %v", err)
  325. } else {
  326. defer client.Close()
  327. _, err = client.Getwd()
  328. if err != nil {
  329. t.Errorf("error mkdir: %v", err)
  330. }
  331. }
  332. client, err = getSftpClientWithAddr(user, usePubKey, "127.0.0.1:2224")
  333. if err == nil {
  334. t.Error("request without a proxy header must be rejected")
  335. }
  336. httpd.RemoveUser(user, http.StatusOK)
  337. os.RemoveAll(user.GetHomeDir())
  338. }
  339. func TestUploadResume(t *testing.T) {
  340. usePubKey := false
  341. u := getTestUser(usePubKey)
  342. user, _, err := httpd.AddUser(u, http.StatusOK)
  343. if err != nil {
  344. t.Errorf("unable to add user: %v", err)
  345. }
  346. os.RemoveAll(user.GetHomeDir())
  347. client, err := getSftpClient(user, usePubKey)
  348. if err != nil {
  349. t.Errorf("unable to create sftp client: %v", err)
  350. } else {
  351. defer client.Close()
  352. testFileName := "test_file.dat"
  353. testFilePath := filepath.Join(homeBasePath, testFileName)
  354. testFileSize := int64(65535)
  355. appendDataSize := int64(65535)
  356. err = createTestFile(testFilePath, testFileSize)
  357. if err != nil {
  358. t.Errorf("unable to create test file: %v", err)
  359. }
  360. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  361. if err != nil {
  362. t.Errorf("file upload error: %v", err)
  363. }
  364. err = appendToTestFile(testFilePath, appendDataSize)
  365. if err != nil {
  366. t.Errorf("unable to append to test file: %v", err)
  367. }
  368. err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, false, client)
  369. if err != nil {
  370. t.Errorf("file upload resume error: %v", err)
  371. }
  372. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  373. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize+appendDataSize, client)
  374. if err != nil {
  375. t.Errorf("file download error: %v", err)
  376. }
  377. initialHash, err := computeHashForFile(sha256.New(), testFilePath)
  378. if err != nil {
  379. t.Errorf("error computing file hash: %v", err)
  380. }
  381. donwloadedFileHash, err := computeHashForFile(sha256.New(), localDownloadPath)
  382. if err != nil {
  383. t.Errorf("error computing downloaded file hash: %v", err)
  384. }
  385. if donwloadedFileHash != initialHash {
  386. t.Errorf("resume failed: file hash does not match")
  387. }
  388. err = sftpUploadResumeFile(testFilePath, testFileName, testFileSize+appendDataSize, true, client)
  389. if err == nil {
  390. t.Errorf("file upload resume with invalid offset must fail")
  391. }
  392. os.Remove(testFilePath)
  393. os.Remove(localDownloadPath)
  394. }
  395. _, err = httpd.RemoveUser(user, http.StatusOK)
  396. if err != nil {
  397. t.Errorf("unable to remove user: %v", err)
  398. }
  399. os.RemoveAll(user.GetHomeDir())
  400. }
  401. func TestDirCommands(t *testing.T) {
  402. usePubKey := false
  403. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  404. if err != nil {
  405. t.Errorf("unable to add user: %v", err)
  406. }
  407. // remove the home dir to test auto creation
  408. os.RemoveAll(user.HomeDir)
  409. client, err := getSftpClient(user, usePubKey)
  410. if err != nil {
  411. t.Errorf("unable to create sftp client: %v", err)
  412. } else {
  413. defer client.Close()
  414. err = client.Mkdir("test1")
  415. if err != nil {
  416. t.Errorf("error mkdir: %v", err)
  417. }
  418. err = client.Rename("test1", "test")
  419. if err != nil {
  420. t.Errorf("error rename: %v", err)
  421. }
  422. _, err = client.Lstat("/test1")
  423. if err == nil {
  424. t.Errorf("stat for renamed dir must not succeed")
  425. }
  426. err = client.PosixRename("test", "test1")
  427. if err != nil {
  428. t.Errorf("error posix rename: %v", err)
  429. }
  430. err = client.Remove("test1")
  431. if err != nil {
  432. t.Errorf("error rmdir: %v", err)
  433. }
  434. err = client.Mkdir("/test/test1")
  435. if err == nil {
  436. t.Errorf("recursive mkdir must fail")
  437. }
  438. client.Mkdir("/test")
  439. err = client.Mkdir("/test/test1")
  440. if err != nil {
  441. t.Errorf("mkdir dir error: %v", err)
  442. }
  443. _, err = client.ReadDir("/this/dir/does/not/exist")
  444. if err == nil {
  445. t.Errorf("reading a missing dir must fail")
  446. }
  447. err = client.RemoveDirectory("/test/test1")
  448. if err != nil {
  449. t.Errorf("remove dir error: %v", err)
  450. }
  451. err = client.RemoveDirectory("/test")
  452. if err != nil {
  453. t.Errorf("remove dir error: %v", err)
  454. }
  455. _, err = client.Lstat("/test")
  456. if err == nil {
  457. t.Errorf("stat for deleted dir must not succeed")
  458. }
  459. err = client.RemoveDirectory("/test")
  460. if err == nil {
  461. t.Errorf("remove missing path must fail")
  462. }
  463. }
  464. httpd.RemoveUser(user, http.StatusOK)
  465. os.RemoveAll(user.GetHomeDir())
  466. }
  467. func TestRemove(t *testing.T) {
  468. usePubKey := true
  469. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  470. if err != nil {
  471. t.Errorf("unable to add user: %v", err)
  472. }
  473. client, err := getSftpClient(user, usePubKey)
  474. if err != nil {
  475. t.Errorf("unable to create sftp client: %v", err)
  476. } else {
  477. defer client.Close()
  478. err = client.Mkdir("test")
  479. if err != nil {
  480. t.Errorf("error mkdir: %v", err)
  481. }
  482. err = client.Mkdir("/test/test1")
  483. if err != nil {
  484. t.Errorf("error mkdir subdir: %v", err)
  485. }
  486. testFileName := "/test_file.dat"
  487. testFilePath := filepath.Join(homeBasePath, testFileName)
  488. testFileSize := int64(65535)
  489. err = createTestFile(testFilePath, testFileSize)
  490. if err != nil {
  491. t.Errorf("unable to create test file: %v", err)
  492. }
  493. err = sftpUploadFile(testFilePath, path.Join("/test", testFileName), testFileSize, client)
  494. if err != nil {
  495. t.Errorf("file upload error: %v", err)
  496. }
  497. err = client.Remove("/test")
  498. if err == nil {
  499. t.Errorf("remove non empty dir must fail")
  500. }
  501. err = client.RemoveDirectory(path.Join("/test", testFileName))
  502. if err == nil {
  503. t.Errorf("remove a file with rmdir must fail")
  504. }
  505. err = client.Remove(path.Join("/test", testFileName))
  506. if err != nil {
  507. t.Errorf("remove file error: %v", err)
  508. }
  509. err = client.Remove(path.Join("/test", testFileName))
  510. if err == nil {
  511. t.Errorf("remove missing file must fail")
  512. }
  513. err = client.Remove("/test/test1")
  514. if err != nil {
  515. t.Errorf("remove dir error: %v", err)
  516. }
  517. err = client.Remove("/test")
  518. if err != nil {
  519. t.Errorf("remove dir error: %v", err)
  520. }
  521. os.Remove(testFilePath)
  522. }
  523. _, err = httpd.RemoveUser(user, http.StatusOK)
  524. if err != nil {
  525. t.Errorf("unable to remove user: %v", err)
  526. }
  527. os.RemoveAll(user.GetHomeDir())
  528. }
  529. func TestLink(t *testing.T) {
  530. usePubKey := false
  531. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  532. if err != nil {
  533. t.Errorf("unable to add user: %v", err)
  534. }
  535. client, err := getSftpClient(user, usePubKey)
  536. if err != nil {
  537. t.Errorf("unable to create sftp client: %v", err)
  538. } else {
  539. defer client.Close()
  540. testFileName := "test_file.dat"
  541. testFilePath := filepath.Join(homeBasePath, testFileName)
  542. testFileSize := int64(65535)
  543. err = createTestFile(testFilePath, testFileSize)
  544. if err != nil {
  545. t.Errorf("unable to create test file: %v", err)
  546. }
  547. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  548. if err != nil {
  549. t.Errorf("file upload error: %v", err)
  550. }
  551. err = client.Symlink(testFileName, testFileName+".link")
  552. if err != nil {
  553. t.Errorf("error creating symlink: %v", err)
  554. }
  555. _, err = client.ReadLink(testFileName + ".link")
  556. if err == nil {
  557. t.Errorf("readlink is currently not implemented so must fail")
  558. }
  559. err = client.Symlink(testFileName, testFileName+".link")
  560. if err == nil {
  561. t.Errorf("creating a symlink to an existing one must fail")
  562. }
  563. err = client.Link(testFileName, testFileName+".hlink")
  564. if err == nil {
  565. t.Errorf("hard link is not supported and must fail")
  566. }
  567. err = client.Remove(testFileName + ".link")
  568. if err != nil {
  569. t.Errorf("error removing symlink: %v", err)
  570. }
  571. err = client.Remove(testFileName)
  572. if err != nil {
  573. t.Errorf("error removing uploaded file: %v", err)
  574. }
  575. os.Remove(testFilePath)
  576. }
  577. _, err = httpd.RemoveUser(user, http.StatusOK)
  578. if err != nil {
  579. t.Errorf("unable to remove user: %v", err)
  580. }
  581. os.RemoveAll(user.GetHomeDir())
  582. }
  583. func TestStat(t *testing.T) {
  584. usePubKey := false
  585. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  586. if err != nil {
  587. t.Errorf("unable to add user: %v", err)
  588. }
  589. client, err := getSftpClient(user, usePubKey)
  590. if err != nil {
  591. t.Errorf("unable to create sftp client: %v", err)
  592. } else {
  593. defer client.Close()
  594. testFileName := "test_file.dat"
  595. testFilePath := filepath.Join(homeBasePath, testFileName)
  596. testFileSize := int64(65535)
  597. createTestFile(testFilePath, testFileSize)
  598. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  599. if err != nil {
  600. t.Errorf("file upload error: %v", err)
  601. }
  602. _, err := client.Lstat(testFileName)
  603. if err != nil {
  604. t.Errorf("stat error: %v", err)
  605. }
  606. // mode 0666 and 0444 works on Windows too
  607. newPerm := os.FileMode(0666)
  608. err = client.Chmod(testFileName, newPerm)
  609. if err != nil {
  610. t.Errorf("chmod error: %v", err)
  611. }
  612. newFi, err := client.Lstat(testFileName)
  613. if err != nil {
  614. t.Errorf("stat error: %v", err)
  615. }
  616. if newPerm != newFi.Mode().Perm() {
  617. t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  618. }
  619. newPerm = os.FileMode(0444)
  620. err = client.Chmod(testFileName, newPerm)
  621. if err != nil {
  622. t.Errorf("chmod error: %v", err)
  623. }
  624. newFi, err = client.Lstat(testFileName)
  625. if err != nil {
  626. t.Errorf("stat error: %v", err)
  627. }
  628. if newPerm != newFi.Mode().Perm() {
  629. t.Errorf("chmod failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  630. }
  631. _, err = client.ReadLink(testFileName)
  632. if err == nil {
  633. t.Errorf("readlink is not supported and must fail")
  634. }
  635. err = client.Truncate(testFileName, 0)
  636. if err != nil {
  637. t.Errorf("truncate must be silently ignored: %v", err)
  638. }
  639. os.Remove(testFilePath)
  640. }
  641. _, err = httpd.RemoveUser(user, http.StatusOK)
  642. if err != nil {
  643. t.Errorf("unable to remove user: %v", err)
  644. }
  645. os.RemoveAll(user.GetHomeDir())
  646. }
  647. func TestStatChownChmod(t *testing.T) {
  648. if runtime.GOOS == "windows" {
  649. t.Skip("chown is not supported on Windows, chmod is partially supported")
  650. }
  651. usePubKey := true
  652. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  653. if err != nil {
  654. t.Errorf("unable to add user: %v", err)
  655. }
  656. client, err := getSftpClient(user, usePubKey)
  657. if err != nil {
  658. t.Errorf("unable to create sftp client: %v", err)
  659. } else {
  660. defer client.Close()
  661. testFileName := "test_file.dat"
  662. testFilePath := filepath.Join(homeBasePath, testFileName)
  663. testFileSize := int64(65535)
  664. createTestFile(testFilePath, testFileSize)
  665. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  666. if err != nil {
  667. t.Errorf("file upload error: %v", err)
  668. }
  669. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  670. if err != nil {
  671. t.Errorf("chown error: %v", err)
  672. }
  673. newPerm := os.FileMode(0600)
  674. err = client.Chmod(testFileName, newPerm)
  675. if err != nil {
  676. t.Errorf("chmod error: %v", err)
  677. }
  678. newFi, err := client.Lstat(testFileName)
  679. if err != nil {
  680. t.Errorf("stat error: %v", err)
  681. }
  682. if newPerm != newFi.Mode().Perm() {
  683. t.Errorf("chown failed expected: %v, actual: %v", newPerm, newFi.Mode().Perm())
  684. }
  685. err = client.Remove(testFileName)
  686. if err != nil {
  687. t.Errorf("error removing uploaded file: %v", err)
  688. }
  689. // l'errore viene riconvertito da sftp.ErrSSHFxNoSuchFile in os.ErrNotExist
  690. err = client.Chmod(testFileName, newPerm)
  691. if err != os.ErrNotExist {
  692. t.Errorf("unexpected chmod error: %v expected: %v", err, os.ErrNotExist)
  693. }
  694. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  695. if err != os.ErrNotExist {
  696. t.Errorf("unexpected chown error: %v expected: %v", err, os.ErrNotExist)
  697. }
  698. os.Remove(testFilePath)
  699. }
  700. _, err = httpd.RemoveUser(user, http.StatusOK)
  701. if err != nil {
  702. t.Errorf("unable to remove user: %v", err)
  703. }
  704. os.RemoveAll(user.GetHomeDir())
  705. }
  706. func TestChtimes(t *testing.T) {
  707. usePubKey := false
  708. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  709. if err != nil {
  710. t.Errorf("unable to add user: %v", err)
  711. }
  712. client, err := getSftpClient(user, usePubKey)
  713. if err != nil {
  714. t.Errorf("unable to create sftp client: %v", err)
  715. } else {
  716. defer client.Close()
  717. testFileName := "test_file.dat"
  718. testFilePath := filepath.Join(homeBasePath, testFileName)
  719. testFileSize := int64(65535)
  720. testDir := "test"
  721. createTestFile(testFilePath, testFileSize)
  722. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  723. if err != nil {
  724. t.Errorf("file upload error: %v", err)
  725. }
  726. acmodTime := time.Now()
  727. err = client.Chtimes(testFileName, acmodTime, acmodTime)
  728. if err != nil {
  729. t.Errorf("error changing file times")
  730. }
  731. newFi, err := client.Lstat(testFileName)
  732. if err != nil {
  733. t.Errorf("file stat error: %v", err)
  734. }
  735. diff := math.Abs(newFi.ModTime().Sub(acmodTime).Seconds())
  736. if diff > 1 {
  737. t.Errorf("diff between wanted and real modification time too big: %v", diff)
  738. }
  739. err = client.Chtimes("invalidFile", acmodTime, acmodTime)
  740. if !os.IsNotExist(err) {
  741. t.Errorf("unexpected error: %v", err)
  742. }
  743. err = client.Mkdir(testDir)
  744. if err != nil {
  745. t.Errorf("unable to create dir: %v", err)
  746. }
  747. err = client.Chtimes(testDir, acmodTime, acmodTime)
  748. if err != nil {
  749. t.Errorf("error changing dir times")
  750. }
  751. newFi, err = client.Lstat(testDir)
  752. if err != nil {
  753. t.Errorf("dir stat error: %v", err)
  754. }
  755. diff = math.Abs(newFi.ModTime().Sub(acmodTime).Seconds())
  756. if diff > 1 {
  757. t.Errorf("diff between wanted and real modification time too big: %v", diff)
  758. }
  759. os.Remove(testFilePath)
  760. }
  761. _, err = httpd.RemoveUser(user, http.StatusOK)
  762. if err != nil {
  763. t.Errorf("unable to remove user: %v", err)
  764. }
  765. os.RemoveAll(user.GetHomeDir())
  766. }
  767. // basic tests to verify virtual chroot, should be improved to cover more cases ...
  768. func TestEscapeHomeDir(t *testing.T) {
  769. usePubKey := true
  770. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  771. if err != nil {
  772. t.Errorf("unable to add user: %v", err)
  773. }
  774. client, err := getSftpClient(user, usePubKey)
  775. if err != nil {
  776. t.Errorf("unable to create sftp client: %v", err)
  777. } else {
  778. defer client.Close()
  779. _, err := client.Getwd()
  780. if err != nil {
  781. t.Errorf("unable to get working dir: %v", err)
  782. }
  783. testDir := "testDir"
  784. linkPath := filepath.Join(homeBasePath, defaultUsername, testDir)
  785. err = os.Symlink(homeBasePath, linkPath)
  786. if err != nil {
  787. t.Errorf("error making local symlink: %v", err)
  788. }
  789. _, err = client.ReadDir(testDir)
  790. if err == nil {
  791. t.Errorf("reading a symbolic link outside home dir should not succeeded")
  792. }
  793. os.Remove(linkPath)
  794. testFileName := "test_file.dat"
  795. testFilePath := filepath.Join(homeBasePath, testFileName)
  796. testFileSize := int64(65535)
  797. err = createTestFile(testFilePath, testFileSize)
  798. if err != nil {
  799. t.Errorf("unable to create test file: %v", err)
  800. }
  801. remoteDestPath := path.Join("..", "..", testFileName)
  802. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  803. if err != nil {
  804. t.Errorf("file upload error: %v", err)
  805. }
  806. _, err = client.Lstat(testFileName)
  807. if err != nil {
  808. t.Errorf("file stat error: %v the file was created outside the user dir!", err)
  809. }
  810. err = client.Remove(testFileName)
  811. if err != nil {
  812. t.Errorf("error removing uploaded file: %v", err)
  813. }
  814. linkPath = filepath.Join(homeBasePath, defaultUsername, testFileName)
  815. err = os.Symlink(homeBasePath, linkPath)
  816. if err != nil {
  817. t.Errorf("error making local symlink: %v", err)
  818. }
  819. err = sftpDownloadFile(testFileName, testFilePath, 0, client)
  820. if err == nil {
  821. t.Errorf("download file outside home dir must fail")
  822. }
  823. err = sftpUploadFile(testFilePath, remoteDestPath, testFileSize, client)
  824. if err == nil {
  825. t.Errorf("overwrite a file outside home dir must fail")
  826. }
  827. err = client.Chmod(remoteDestPath, 0644)
  828. if err == nil {
  829. t.Errorf("setstat on a file outside home dir must fail")
  830. }
  831. os.Remove(linkPath)
  832. os.Remove(testFilePath)
  833. }
  834. _, err = httpd.RemoveUser(user, http.StatusOK)
  835. if err != nil {
  836. t.Errorf("unable to remove user: %v", err)
  837. }
  838. os.RemoveAll(user.GetHomeDir())
  839. }
  840. func TestHomeSpecialChars(t *testing.T) {
  841. usePubKey := true
  842. u := getTestUser(usePubKey)
  843. u.HomeDir = filepath.Join(homeBasePath, "abc açà#&%lk")
  844. user, _, err := httpd.AddUser(u, http.StatusOK)
  845. if err != nil {
  846. t.Errorf("unable to add user: %v", err)
  847. }
  848. client, err := getSftpClient(user, usePubKey)
  849. if err != nil {
  850. t.Errorf("unable to create sftp client: %v", err)
  851. } else {
  852. defer client.Close()
  853. _, err := client.Getwd()
  854. if err != nil {
  855. t.Errorf("unable to get working dir: %v", err)
  856. }
  857. testFileName := "test_file.dat"
  858. testFilePath := filepath.Join(homeBasePath, testFileName)
  859. testFileSize := int64(65535)
  860. err = createTestFile(testFilePath, testFileSize)
  861. if err != nil {
  862. t.Errorf("unable to create test file: %v", err)
  863. }
  864. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  865. if err != nil {
  866. t.Errorf("file upload error: %v", err)
  867. }
  868. files, err := client.ReadDir(".")
  869. if err != nil {
  870. t.Errorf("unable to read remote dir: %v", err)
  871. }
  872. if len(files) < 1 {
  873. t.Errorf("expected at least 1 file in this dir")
  874. }
  875. err = client.Remove(testFileName)
  876. if err != nil {
  877. t.Errorf("error removing uploaded file: %v", err)
  878. }
  879. os.Remove(testFilePath)
  880. }
  881. _, err = httpd.RemoveUser(user, http.StatusOK)
  882. if err != nil {
  883. t.Errorf("unable to remove user: %v", err)
  884. }
  885. os.RemoveAll(user.GetHomeDir())
  886. }
  887. func TestLogin(t *testing.T) {
  888. u := getTestUser(false)
  889. u.PublicKeys = []string{testPubKey}
  890. user, _, err := httpd.AddUser(u, http.StatusOK)
  891. if err != nil {
  892. t.Errorf("unable to add user: %v", err)
  893. }
  894. client, err := getSftpClient(user, false)
  895. if err != nil {
  896. t.Errorf("unable to create sftp client: %v", err)
  897. } else {
  898. defer client.Close()
  899. _, err := client.Getwd()
  900. if err != nil {
  901. t.Errorf("sftp client with valid password must work")
  902. }
  903. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  904. if err != nil {
  905. t.Errorf("error getting user: %v", err)
  906. }
  907. if user.LastLogin <= 0 {
  908. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  909. }
  910. }
  911. client, err = getSftpClient(user, true)
  912. if err != nil {
  913. t.Errorf("unable to create sftp client: %v", err)
  914. } else {
  915. defer client.Close()
  916. _, err := client.Getwd()
  917. if err != nil {
  918. t.Errorf("sftp client with valid public key must work")
  919. }
  920. }
  921. user.Password = "invalid password"
  922. client, err = getSftpClient(user, false)
  923. if err == nil {
  924. t.Errorf("login with invalid password must fail")
  925. defer client.Close()
  926. }
  927. // testPubKey1 is not authorized
  928. user.PublicKeys = []string{testPubKey1}
  929. user.Password = ""
  930. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  931. if err != nil {
  932. t.Errorf("unable to update user: %v", err)
  933. }
  934. client, err = getSftpClient(user, true)
  935. if err == nil {
  936. t.Errorf("login with invalid public key must fail")
  937. defer client.Close()
  938. }
  939. // login a user with multiple public keys, only the second one is valid
  940. user.PublicKeys = []string{testPubKey1, testPubKey}
  941. user.Password = ""
  942. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  943. if err != nil {
  944. t.Errorf("unable to update user: %v", err)
  945. }
  946. client, err = getSftpClient(user, true)
  947. if err != nil {
  948. t.Errorf("unable to create sftp client: %v", err)
  949. } else {
  950. defer client.Close()
  951. _, err := client.Getwd()
  952. if err != nil {
  953. t.Errorf("sftp client with multiple public key must work if at least one public key is valid")
  954. }
  955. }
  956. _, err = httpd.RemoveUser(user, http.StatusOK)
  957. if err != nil {
  958. t.Errorf("unable to remove user: %v", err)
  959. }
  960. os.RemoveAll(user.GetHomeDir())
  961. }
  962. func TestLoginUserStatus(t *testing.T) {
  963. usePubKey := true
  964. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  965. if err != nil {
  966. t.Errorf("unable to add user: %v", err)
  967. }
  968. client, err := getSftpClient(user, usePubKey)
  969. if err != nil {
  970. t.Errorf("unable to create sftp client: %v", err)
  971. } else {
  972. defer client.Close()
  973. _, err := client.Getwd()
  974. if err != nil {
  975. t.Errorf("sftp client with valid credentials must work")
  976. }
  977. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  978. if err != nil {
  979. t.Errorf("error getting user: %v", err)
  980. }
  981. if user.LastLogin <= 0 {
  982. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  983. }
  984. }
  985. user.Status = 0
  986. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  987. if err != nil {
  988. t.Errorf("unable to update user: %v", err)
  989. }
  990. client, err = getSftpClient(user, usePubKey)
  991. if err == nil {
  992. t.Errorf("login for a disabled user must fail")
  993. defer client.Close()
  994. }
  995. _, err = httpd.RemoveUser(user, http.StatusOK)
  996. if err != nil {
  997. t.Errorf("unable to remove user: %v", err)
  998. }
  999. os.RemoveAll(user.GetHomeDir())
  1000. }
  1001. func TestLoginUserExpiration(t *testing.T) {
  1002. usePubKey := true
  1003. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1004. if err != nil {
  1005. t.Errorf("unable to add user: %v", err)
  1006. }
  1007. client, err := getSftpClient(user, usePubKey)
  1008. if err != nil {
  1009. t.Errorf("unable to create sftp client: %v", err)
  1010. } else {
  1011. defer client.Close()
  1012. _, err := client.Getwd()
  1013. if err != nil {
  1014. t.Errorf("sftp client with valid credentials must work")
  1015. }
  1016. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1017. if err != nil {
  1018. t.Errorf("error getting user: %v", err)
  1019. }
  1020. if user.LastLogin <= 0 {
  1021. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  1022. }
  1023. }
  1024. user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) - 120000
  1025. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1026. if err != nil {
  1027. t.Errorf("unable to update user: %v", err)
  1028. }
  1029. client, err = getSftpClient(user, usePubKey)
  1030. if err == nil {
  1031. t.Errorf("login for an expired user must fail")
  1032. defer client.Close()
  1033. }
  1034. user.ExpirationDate = utils.GetTimeAsMsSinceEpoch(time.Now()) + 120000
  1035. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1036. if err != nil {
  1037. t.Errorf("unable to update user: %v", err)
  1038. }
  1039. client, err = getSftpClient(user, usePubKey)
  1040. if err != nil {
  1041. t.Errorf("login for a non expired user must succeed: %v", err)
  1042. } else {
  1043. defer client.Close()
  1044. }
  1045. _, err = httpd.RemoveUser(user, http.StatusOK)
  1046. if err != nil {
  1047. t.Errorf("unable to remove user: %v", err)
  1048. }
  1049. os.RemoveAll(user.GetHomeDir())
  1050. }
  1051. func TestLoginInvalidFs(t *testing.T) {
  1052. if runtime.GOOS == "windows" {
  1053. t.Skip("this test is not available on Windows")
  1054. }
  1055. config.LoadConfig(configDir, "")
  1056. providerConf := config.GetProviderConf()
  1057. if providerConf.Driver != dataprovider.SQLiteDataProviderName {
  1058. t.Skip("this test require sqlite provider")
  1059. }
  1060. dbPath := providerConf.Name
  1061. if !filepath.IsAbs(dbPath) {
  1062. dbPath = filepath.Join(configDir, dbPath)
  1063. }
  1064. usePubKey := true
  1065. u := getTestUser(usePubKey)
  1066. user, _, err := httpd.AddUser(u, http.StatusOK)
  1067. if err != nil {
  1068. t.Errorf("unable to add user: %v", err)
  1069. }
  1070. // we update the database using sqlite3 CLI since we cannot add an user with an invalid config
  1071. time.Sleep(200 * time.Millisecond)
  1072. updateUserQuery := fmt.Sprintf("UPDATE users SET filesystem='{\"provider\":1}' WHERE id=%v", user.ID)
  1073. cmd := exec.Command("sqlite3", dbPath, updateUserQuery)
  1074. out, err := cmd.CombinedOutput()
  1075. if err != nil {
  1076. t.Errorf("unexpected error: %v, cmd out: %v", err, string(out))
  1077. }
  1078. time.Sleep(200 * time.Millisecond)
  1079. _, err = getSftpClient(user, usePubKey)
  1080. if err == nil {
  1081. t.Error("login must fail, the user has an invalid filesystem config")
  1082. }
  1083. _, err = httpd.RemoveUser(user, http.StatusOK)
  1084. if err != nil {
  1085. t.Errorf("unable to remove user: %v", err)
  1086. }
  1087. os.RemoveAll(user.GetHomeDir())
  1088. }
  1089. func TestDeniedLoginMethods(t *testing.T) {
  1090. u := getTestUser(true)
  1091. u.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodPublicKey, dataprovider.SSHLoginMethodPassword}
  1092. user, _, err := httpd.AddUser(u, http.StatusOK)
  1093. if err != nil {
  1094. t.Errorf("unable to add user: %v", err)
  1095. }
  1096. _, err = getSftpClient(user, true)
  1097. if err == nil {
  1098. t.Error("public key login is disabled, authentication must fail")
  1099. }
  1100. user.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodKeyboardInteractive, dataprovider.SSHLoginMethodPassword}
  1101. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1102. if err != nil {
  1103. t.Errorf("unable to update user: %v", err)
  1104. }
  1105. client, err := getSftpClient(user, true)
  1106. if err != nil {
  1107. t.Errorf("unable to create sftp client: %v", err)
  1108. } else {
  1109. client.Close()
  1110. }
  1111. user.Password = defaultPassword
  1112. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1113. if err != nil {
  1114. t.Errorf("unable to update user: %v", err)
  1115. }
  1116. _, err = getSftpClient(user, false)
  1117. if err == nil {
  1118. t.Error("password login is disabled, authentication must fail")
  1119. }
  1120. user.Filters.DeniedLoginMethods = []string{dataprovider.SSHLoginMethodKeyboardInteractive, dataprovider.SSHLoginMethodPublicKey}
  1121. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1122. if err != nil {
  1123. t.Errorf("unable to update user: %v", err)
  1124. }
  1125. client, err = getSftpClient(user, false)
  1126. if err != nil {
  1127. t.Errorf("unable to create sftp client: %v", err)
  1128. } else {
  1129. client.Close()
  1130. }
  1131. _, err = httpd.RemoveUser(user, http.StatusOK)
  1132. if err != nil {
  1133. t.Errorf("unable to remove user: %v", err)
  1134. }
  1135. os.RemoveAll(user.GetHomeDir())
  1136. }
  1137. func TestLoginWithIPFilters(t *testing.T) {
  1138. usePubKey := true
  1139. u := getTestUser(usePubKey)
  1140. u.Filters.DeniedIP = []string{"192.167.0.0/24", "172.18.0.0/16"}
  1141. u.Filters.AllowedIP = []string{}
  1142. user, _, err := httpd.AddUser(u, http.StatusOK)
  1143. if err != nil {
  1144. t.Errorf("unable to add user: %v", err)
  1145. }
  1146. client, err := getSftpClient(user, usePubKey)
  1147. if err != nil {
  1148. t.Errorf("unable to create sftp client: %v", err)
  1149. } else {
  1150. defer client.Close()
  1151. _, err := client.Getwd()
  1152. if err != nil {
  1153. t.Errorf("sftp client with valid credentials must work")
  1154. }
  1155. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1156. if err != nil {
  1157. t.Errorf("error getting user: %v", err)
  1158. }
  1159. if user.LastLogin <= 0 {
  1160. t.Errorf("last login must be updated after a successful login: %v", user.LastLogin)
  1161. }
  1162. }
  1163. user.Filters.AllowedIP = []string{"127.0.0.0/8"}
  1164. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1165. if err != nil {
  1166. t.Errorf("unable to update user: %v", err)
  1167. }
  1168. client, err = getSftpClient(user, usePubKey)
  1169. if err != nil {
  1170. t.Errorf("login from an allowed IP must succeed: %v", err)
  1171. } else {
  1172. defer client.Close()
  1173. }
  1174. user.Filters.AllowedIP = []string{"172.19.0.0/16"}
  1175. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1176. if err != nil {
  1177. t.Errorf("unable to update user: %v", err)
  1178. }
  1179. client, err = getSftpClient(user, usePubKey)
  1180. if err == nil {
  1181. t.Errorf("login from an not allowed IP must fail")
  1182. client.Close()
  1183. }
  1184. _, err = httpd.RemoveUser(user, http.StatusOK)
  1185. if err != nil {
  1186. t.Errorf("unable to remove user: %v", err)
  1187. }
  1188. os.RemoveAll(user.GetHomeDir())
  1189. }
  1190. func TestLoginAfterUserUpdateEmptyPwd(t *testing.T) {
  1191. usePubKey := false
  1192. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1193. if err != nil {
  1194. t.Errorf("unable to add user: %v", err)
  1195. }
  1196. user.Password = ""
  1197. user.PublicKeys = []string{}
  1198. // password and public key should remain unchanged
  1199. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1200. if err != nil {
  1201. t.Errorf("unable to update user: %v", err)
  1202. }
  1203. client, err := getSftpClient(user, usePubKey)
  1204. if err != nil {
  1205. t.Errorf("unable to create sftp client: %v", err)
  1206. } else {
  1207. defer client.Close()
  1208. _, err := client.Getwd()
  1209. if err != nil {
  1210. t.Errorf("unable to get working dir: %v", err)
  1211. }
  1212. _, err = client.ReadDir(".")
  1213. if err != nil {
  1214. t.Errorf("unable to read remote dir: %v", err)
  1215. }
  1216. }
  1217. _, err = httpd.RemoveUser(user, http.StatusOK)
  1218. if err != nil {
  1219. t.Errorf("unable to remove user: %v", err)
  1220. }
  1221. os.RemoveAll(user.GetHomeDir())
  1222. }
  1223. func TestLoginAfterUserUpdateEmptyPubKey(t *testing.T) {
  1224. usePubKey := true
  1225. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1226. if err != nil {
  1227. t.Errorf("unable to add user: %v", err)
  1228. }
  1229. user.Password = ""
  1230. user.PublicKeys = []string{}
  1231. // password and public key should remain unchanged
  1232. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  1233. if err != nil {
  1234. t.Errorf("unable to update user: %v", err)
  1235. }
  1236. client, err := getSftpClient(user, usePubKey)
  1237. if err != nil {
  1238. t.Errorf("unable to create sftp client: %v", err)
  1239. } else {
  1240. defer client.Close()
  1241. _, err := client.Getwd()
  1242. if err != nil {
  1243. t.Errorf("unable to get working dir: %v", err)
  1244. }
  1245. _, err = client.ReadDir(".")
  1246. if err != nil {
  1247. t.Errorf("unable to read remote dir: %v", err)
  1248. }
  1249. }
  1250. _, err = httpd.RemoveUser(user, http.StatusOK)
  1251. if err != nil {
  1252. t.Errorf("unable to remove user: %v", err)
  1253. }
  1254. os.RemoveAll(user.GetHomeDir())
  1255. }
  1256. func TestLoginKeyboardInteractiveAuth(t *testing.T) {
  1257. if runtime.GOOS == "windows" {
  1258. t.Skip("this test is not available on Windows")
  1259. }
  1260. user, _, err := httpd.AddUser(getTestUser(false), http.StatusOK)
  1261. if err != nil {
  1262. t.Errorf("unable to add user: %v", err)
  1263. }
  1264. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  1265. client, err := getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1266. if err != nil {
  1267. t.Errorf("unable to create sftp client: %v", err)
  1268. } else {
  1269. defer client.Close()
  1270. _, err := client.Getwd()
  1271. if err != nil {
  1272. t.Errorf("unable to get working dir: %v", err)
  1273. }
  1274. _, err = client.ReadDir(".")
  1275. if err != nil {
  1276. t.Errorf("unable to read remote dir: %v", err)
  1277. }
  1278. }
  1279. user.Status = 0
  1280. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1281. if err != nil {
  1282. t.Errorf("error updating user: %v", err)
  1283. }
  1284. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1285. if err == nil {
  1286. t.Error("keyboard interactive auth must fail the user is disabled")
  1287. }
  1288. user.Status = 1
  1289. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1290. if err != nil {
  1291. t.Errorf("error updating user: %v", err)
  1292. }
  1293. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, -1), 0755)
  1294. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1295. if err == nil {
  1296. t.Error("keyboard interactive auth must fail the script returned -1")
  1297. }
  1298. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, true, 1), 0755)
  1299. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1300. if err == nil {
  1301. t.Error("keyboard interactive auth must fail the script returned bad json")
  1302. }
  1303. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 5, true, 1), 0755)
  1304. client, err = getKeyboardInteractiveSftpClient(user, []string{"1", "2"})
  1305. if err == nil {
  1306. t.Error("keyboard interactive auth must fail the script returned bad json")
  1307. }
  1308. _, err = httpd.RemoveUser(user, http.StatusOK)
  1309. if err != nil {
  1310. t.Errorf("unable to remove user: %v", err)
  1311. }
  1312. os.RemoveAll(user.GetHomeDir())
  1313. }
  1314. func TestPreLoginScript(t *testing.T) {
  1315. if runtime.GOOS == "windows" {
  1316. t.Skip("this test is not available on Windows")
  1317. }
  1318. usePubKey := true
  1319. u := getTestUser(usePubKey)
  1320. dataProvider := dataprovider.GetProvider()
  1321. dataprovider.Close(dataProvider)
  1322. config.LoadConfig(configDir, "")
  1323. providerConf := config.GetProviderConf()
  1324. ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(u, false), 0755)
  1325. providerConf.PreLoginProgram = preLoginPath
  1326. err := dataprovider.Initialize(providerConf, configDir)
  1327. if err != nil {
  1328. t.Errorf("error initializing data provider")
  1329. }
  1330. httpd.SetDataProvider(dataprovider.GetProvider())
  1331. sftpd.SetDataProvider(dataprovider.GetProvider())
  1332. user, _, err := httpd.AddUser(u, http.StatusOK)
  1333. if err != nil {
  1334. t.Errorf("unable to add user: %v", err)
  1335. }
  1336. client, err := getSftpClient(u, usePubKey)
  1337. if err != nil {
  1338. t.Errorf("unable to create sftp client: %v", err)
  1339. } else {
  1340. defer client.Close()
  1341. _, err = client.Getwd()
  1342. if err != nil {
  1343. t.Errorf("unable to get working dir: %v", err)
  1344. }
  1345. }
  1346. ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, true), 0755)
  1347. _, err = getSftpClient(u, usePubKey)
  1348. if err == nil {
  1349. t.Error("pre login script returned a non json response, login must fail")
  1350. }
  1351. user.Status = 0
  1352. ioutil.WriteFile(preLoginPath, getPreLoginScriptContent(user, false), 0755)
  1353. _, err = getSftpClient(u, usePubKey)
  1354. if err == nil {
  1355. t.Error("pre login script returned a disabled user, login must fail")
  1356. }
  1357. _, err = httpd.RemoveUser(user, http.StatusOK)
  1358. if err != nil {
  1359. t.Errorf("unable to remove user: %v", err)
  1360. }
  1361. os.RemoveAll(user.GetHomeDir())
  1362. dataProvider = dataprovider.GetProvider()
  1363. dataprovider.Close(dataProvider)
  1364. config.LoadConfig(configDir, "")
  1365. providerConf = config.GetProviderConf()
  1366. err = dataprovider.Initialize(providerConf, configDir)
  1367. if err != nil {
  1368. t.Errorf("error initializing data provider")
  1369. }
  1370. httpd.SetDataProvider(dataprovider.GetProvider())
  1371. sftpd.SetDataProvider(dataprovider.GetProvider())
  1372. os.Remove(preLoginPath)
  1373. }
  1374. func TestLoginExternalAuthPwdAndPubKey(t *testing.T) {
  1375. if runtime.GOOS == "windows" {
  1376. t.Skip("this test is not available on Windows")
  1377. }
  1378. usePubKey := true
  1379. u := getTestUser(usePubKey)
  1380. u.QuotaFiles = 1000
  1381. dataProvider := dataprovider.GetProvider()
  1382. dataprovider.Close(dataProvider)
  1383. config.LoadConfig(configDir, "")
  1384. providerConf := config.GetProviderConf()
  1385. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1386. providerConf.ExternalAuthProgram = extAuthPath
  1387. providerConf.ExternalAuthScope = 0
  1388. err := dataprovider.Initialize(providerConf, configDir)
  1389. if err != nil {
  1390. t.Errorf("error initializing data provider")
  1391. }
  1392. httpd.SetDataProvider(dataprovider.GetProvider())
  1393. sftpd.SetDataProvider(dataprovider.GetProvider())
  1394. client, err := getSftpClient(u, usePubKey)
  1395. if err != nil {
  1396. t.Errorf("unable to create sftp client: %v", err)
  1397. } else {
  1398. defer client.Close()
  1399. testFileName := "test_file.dat"
  1400. testFilePath := filepath.Join(homeBasePath, testFileName)
  1401. testFileSize := int64(65535)
  1402. err = createTestFile(testFilePath, testFileSize)
  1403. if err != nil {
  1404. t.Errorf("unable to create test file: %v", err)
  1405. }
  1406. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1407. if err != nil {
  1408. t.Errorf("file upload error: %v", err)
  1409. }
  1410. os.Remove(testFilePath)
  1411. }
  1412. u.Username = defaultUsername + "1"
  1413. client, err = getSftpClient(u, usePubKey)
  1414. if err == nil {
  1415. t.Error("external auth login with invalid user must fail")
  1416. }
  1417. usePubKey = false
  1418. u = getTestUser(usePubKey)
  1419. u.PublicKeys = []string{}
  1420. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1421. client, err = getSftpClient(u, usePubKey)
  1422. if err != nil {
  1423. t.Errorf("unable to create sftp client: %v", err)
  1424. } else {
  1425. defer client.Close()
  1426. _, err := client.Getwd()
  1427. if err != nil {
  1428. t.Errorf("unable to get working dir: %v", err)
  1429. }
  1430. }
  1431. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1432. if err != nil {
  1433. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1434. }
  1435. if len(users) != 1 {
  1436. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1437. }
  1438. user := users[0]
  1439. if len(user.PublicKeys) != 0 {
  1440. t.Errorf("number of public keys mismatch, expected: 0, actual: %v", len(user.PublicKeys))
  1441. }
  1442. if user.UsedQuotaSize == 0 {
  1443. t.Error("quota size must be > 0")
  1444. }
  1445. _, err = httpd.RemoveUser(user, http.StatusOK)
  1446. if err != nil {
  1447. t.Errorf("unable to remove: %v", err)
  1448. }
  1449. os.RemoveAll(user.GetHomeDir())
  1450. dataProvider = dataprovider.GetProvider()
  1451. dataprovider.Close(dataProvider)
  1452. config.LoadConfig(configDir, "")
  1453. providerConf = config.GetProviderConf()
  1454. err = dataprovider.Initialize(providerConf, configDir)
  1455. if err != nil {
  1456. t.Errorf("error initializing data provider")
  1457. }
  1458. httpd.SetDataProvider(dataprovider.GetProvider())
  1459. sftpd.SetDataProvider(dataprovider.GetProvider())
  1460. os.Remove(extAuthPath)
  1461. }
  1462. func TestLoginExternalAuthPwd(t *testing.T) {
  1463. if runtime.GOOS == "windows" {
  1464. t.Skip("this test is not available on Windows")
  1465. }
  1466. usePubKey := false
  1467. u := getTestUser(usePubKey)
  1468. dataProvider := dataprovider.GetProvider()
  1469. dataprovider.Close(dataProvider)
  1470. config.LoadConfig(configDir, "")
  1471. providerConf := config.GetProviderConf()
  1472. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1473. providerConf.ExternalAuthProgram = extAuthPath
  1474. providerConf.ExternalAuthScope = 1
  1475. err := dataprovider.Initialize(providerConf, configDir)
  1476. if err != nil {
  1477. t.Errorf("error initializing data provider")
  1478. }
  1479. httpd.SetDataProvider(dataprovider.GetProvider())
  1480. sftpd.SetDataProvider(dataprovider.GetProvider())
  1481. client, err := getSftpClient(u, usePubKey)
  1482. if err != nil {
  1483. t.Errorf("unable to create sftp client: %v", err)
  1484. } else {
  1485. defer client.Close()
  1486. _, err := client.Getwd()
  1487. if err != nil {
  1488. t.Errorf("unable to get working dir: %v", err)
  1489. }
  1490. }
  1491. u.Username = defaultUsername + "1"
  1492. client, err = getSftpClient(u, usePubKey)
  1493. if err == nil {
  1494. t.Error("external auth login with invalid user must fail")
  1495. }
  1496. usePubKey = true
  1497. u = getTestUser(usePubKey)
  1498. client, err = getSftpClient(u, usePubKey)
  1499. if err == nil {
  1500. t.Error("external auth login with valid user but invalid auth scope must fail")
  1501. }
  1502. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1503. if err != nil {
  1504. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1505. }
  1506. if len(users) != 1 {
  1507. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1508. }
  1509. user := users[0]
  1510. _, err = httpd.RemoveUser(user, http.StatusOK)
  1511. if err != nil {
  1512. t.Errorf("unable to remove: %v", err)
  1513. }
  1514. os.RemoveAll(user.GetHomeDir())
  1515. dataProvider = dataprovider.GetProvider()
  1516. dataprovider.Close(dataProvider)
  1517. config.LoadConfig(configDir, "")
  1518. providerConf = config.GetProviderConf()
  1519. err = dataprovider.Initialize(providerConf, configDir)
  1520. if err != nil {
  1521. t.Errorf("error initializing data provider")
  1522. }
  1523. httpd.SetDataProvider(dataprovider.GetProvider())
  1524. sftpd.SetDataProvider(dataprovider.GetProvider())
  1525. os.Remove(extAuthPath)
  1526. }
  1527. func TestLoginExternalAuthPubKey(t *testing.T) {
  1528. if runtime.GOOS == "windows" {
  1529. t.Skip("this test is not available on Windows")
  1530. }
  1531. usePubKey := true
  1532. u := getTestUser(usePubKey)
  1533. dataProvider := dataprovider.GetProvider()
  1534. dataprovider.Close(dataProvider)
  1535. config.LoadConfig(configDir, "")
  1536. providerConf := config.GetProviderConf()
  1537. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1538. providerConf.ExternalAuthProgram = extAuthPath
  1539. providerConf.ExternalAuthScope = 2
  1540. err := dataprovider.Initialize(providerConf, configDir)
  1541. if err != nil {
  1542. t.Errorf("error initializing data provider")
  1543. }
  1544. httpd.SetDataProvider(dataprovider.GetProvider())
  1545. sftpd.SetDataProvider(dataprovider.GetProvider())
  1546. client, err := getSftpClient(u, usePubKey)
  1547. if err != nil {
  1548. t.Errorf("unable to create sftp client: %v", err)
  1549. } else {
  1550. defer client.Close()
  1551. _, err := client.Getwd()
  1552. if err != nil {
  1553. t.Errorf("unable to get working dir: %v", err)
  1554. }
  1555. }
  1556. u.Username = defaultUsername + "1"
  1557. client, err = getSftpClient(u, usePubKey)
  1558. if err == nil {
  1559. t.Error("external auth login with invalid user must fail")
  1560. }
  1561. usePubKey = false
  1562. u = getTestUser(usePubKey)
  1563. client, err = getSftpClient(u, usePubKey)
  1564. if err == nil {
  1565. t.Error("external auth login with valid user but invalid auth scope must fail")
  1566. }
  1567. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1568. if err != nil {
  1569. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1570. }
  1571. if len(users) != 1 {
  1572. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1573. }
  1574. user := users[0]
  1575. _, err = httpd.RemoveUser(user, http.StatusOK)
  1576. if err != nil {
  1577. t.Errorf("unable to remove: %v", err)
  1578. }
  1579. os.RemoveAll(user.GetHomeDir())
  1580. dataProvider = dataprovider.GetProvider()
  1581. dataprovider.Close(dataProvider)
  1582. config.LoadConfig(configDir, "")
  1583. providerConf = config.GetProviderConf()
  1584. err = dataprovider.Initialize(providerConf, configDir)
  1585. if err != nil {
  1586. t.Errorf("error initializing data provider")
  1587. }
  1588. httpd.SetDataProvider(dataprovider.GetProvider())
  1589. sftpd.SetDataProvider(dataprovider.GetProvider())
  1590. os.Remove(extAuthPath)
  1591. }
  1592. func TestLoginExternalAuthInteractive(t *testing.T) {
  1593. if runtime.GOOS == "windows" {
  1594. t.Skip("this test is not available on Windows")
  1595. }
  1596. usePubKey := false
  1597. u := getTestUser(usePubKey)
  1598. dataProvider := dataprovider.GetProvider()
  1599. dataprovider.Close(dataProvider)
  1600. config.LoadConfig(configDir, "")
  1601. providerConf := config.GetProviderConf()
  1602. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, false), 0755)
  1603. providerConf.ExternalAuthProgram = extAuthPath
  1604. providerConf.ExternalAuthScope = 4
  1605. err := dataprovider.Initialize(providerConf, configDir)
  1606. if err != nil {
  1607. t.Errorf("error initializing data provider")
  1608. }
  1609. httpd.SetDataProvider(dataprovider.GetProvider())
  1610. sftpd.SetDataProvider(dataprovider.GetProvider())
  1611. ioutil.WriteFile(keyIntAuthPath, getKeyboardInteractiveScriptContent([]string{"1", "2"}, 0, false, 1), 0755)
  1612. client, err := getKeyboardInteractiveSftpClient(u, []string{"1", "2"})
  1613. if err != nil {
  1614. t.Errorf("unable to create sftp client: %v", err)
  1615. } else {
  1616. defer client.Close()
  1617. _, err := client.Getwd()
  1618. if err != nil {
  1619. t.Errorf("unable to get working dir: %v", err)
  1620. }
  1621. }
  1622. u.Username = defaultUsername + "1"
  1623. client, err = getKeyboardInteractiveSftpClient(u, []string{"1", "2"})
  1624. if err == nil {
  1625. t.Error("external auth login with invalid user must fail")
  1626. }
  1627. usePubKey = true
  1628. u = getTestUser(usePubKey)
  1629. client, err = getSftpClient(u, usePubKey)
  1630. if err == nil {
  1631. t.Error("external auth login with valid user but invalid auth scope must fail")
  1632. }
  1633. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1634. if err != nil {
  1635. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1636. }
  1637. if len(users) != 1 {
  1638. t.Errorf("number of users mismatch, expected: 1, actual: %v", len(users))
  1639. }
  1640. user := users[0]
  1641. _, err = httpd.RemoveUser(user, http.StatusOK)
  1642. if err != nil {
  1643. t.Errorf("unable to remove: %v", err)
  1644. }
  1645. os.RemoveAll(user.GetHomeDir())
  1646. dataProvider = dataprovider.GetProvider()
  1647. dataprovider.Close(dataProvider)
  1648. config.LoadConfig(configDir, "")
  1649. providerConf = config.GetProviderConf()
  1650. err = dataprovider.Initialize(providerConf, configDir)
  1651. if err != nil {
  1652. t.Errorf("error initializing data provider")
  1653. }
  1654. httpd.SetDataProvider(dataprovider.GetProvider())
  1655. sftpd.SetDataProvider(dataprovider.GetProvider())
  1656. os.Remove(extAuthPath)
  1657. }
  1658. func TestLoginExternalAuthErrors(t *testing.T) {
  1659. if runtime.GOOS == "windows" {
  1660. t.Skip("this test is not available on Windows")
  1661. }
  1662. usePubKey := true
  1663. u := getTestUser(usePubKey)
  1664. dataProvider := dataprovider.GetProvider()
  1665. dataprovider.Close(dataProvider)
  1666. config.LoadConfig(configDir, "")
  1667. providerConf := config.GetProviderConf()
  1668. ioutil.WriteFile(extAuthPath, getExtAuthScriptContent(u, 0, true), 0755)
  1669. providerConf.ExternalAuthProgram = extAuthPath
  1670. providerConf.ExternalAuthScope = 0
  1671. err := dataprovider.Initialize(providerConf, configDir)
  1672. if err != nil {
  1673. t.Errorf("error initializing data provider")
  1674. }
  1675. httpd.SetDataProvider(dataprovider.GetProvider())
  1676. sftpd.SetDataProvider(dataprovider.GetProvider())
  1677. _, err = getSftpClient(u, usePubKey)
  1678. if err == nil {
  1679. t.Error("login must fail, external auth returns a non json response")
  1680. }
  1681. usePubKey = false
  1682. u = getTestUser(usePubKey)
  1683. _, err = getSftpClient(u, usePubKey)
  1684. if err == nil {
  1685. t.Error("login must fail, external auth returns a non json response")
  1686. }
  1687. users, out, err := httpd.GetUsers(0, 0, defaultUsername, http.StatusOK)
  1688. if err != nil {
  1689. t.Errorf("unable to get users: %v, out: %v", err, string(out))
  1690. }
  1691. if len(users) != 0 {
  1692. t.Errorf("number of users mismatch, expected: 0, actual: %v", len(users))
  1693. }
  1694. dataProvider = dataprovider.GetProvider()
  1695. dataprovider.Close(dataProvider)
  1696. config.LoadConfig(configDir, "")
  1697. providerConf = config.GetProviderConf()
  1698. err = dataprovider.Initialize(providerConf, configDir)
  1699. if err != nil {
  1700. t.Errorf("error initializing data provider")
  1701. }
  1702. httpd.SetDataProvider(dataprovider.GetProvider())
  1703. sftpd.SetDataProvider(dataprovider.GetProvider())
  1704. os.Remove(extAuthPath)
  1705. }
  1706. func TestQuotaDisabledError(t *testing.T) {
  1707. dataProvider := dataprovider.GetProvider()
  1708. dataprovider.Close(dataProvider)
  1709. config.LoadConfig(configDir, "")
  1710. providerConf := config.GetProviderConf()
  1711. providerConf.TrackQuota = 0
  1712. err := dataprovider.Initialize(providerConf, configDir)
  1713. if err != nil {
  1714. t.Errorf("error initializing data provider")
  1715. }
  1716. httpd.SetDataProvider(dataprovider.GetProvider())
  1717. sftpd.SetDataProvider(dataprovider.GetProvider())
  1718. usePubKey := false
  1719. u := getTestUser(usePubKey)
  1720. u.QuotaFiles = 10
  1721. user, _, err := httpd.AddUser(u, http.StatusOK)
  1722. if err != nil {
  1723. t.Errorf("unable to add user: %v", err)
  1724. }
  1725. client, err := getSftpClient(user, usePubKey)
  1726. if err != nil {
  1727. t.Errorf("unable to create sftp client: %v", err)
  1728. } else {
  1729. defer client.Close()
  1730. testFileName := "test_file.dat"
  1731. testFilePath := filepath.Join(homeBasePath, testFileName)
  1732. testFileSize := int64(65535)
  1733. err = createTestFile(testFilePath, testFileSize)
  1734. if err != nil {
  1735. t.Errorf("unable to create test file: %v", err)
  1736. }
  1737. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1738. if err != nil {
  1739. t.Errorf("file upload error: %v", err)
  1740. }
  1741. os.Remove(testFilePath)
  1742. }
  1743. _, err = httpd.RemoveUser(user, http.StatusOK)
  1744. if err != nil {
  1745. t.Errorf("unable to remove: %v", err)
  1746. }
  1747. os.RemoveAll(user.GetHomeDir())
  1748. dataProvider = dataprovider.GetProvider()
  1749. dataprovider.Close(dataProvider)
  1750. config.LoadConfig(configDir, "")
  1751. providerConf = config.GetProviderConf()
  1752. err = dataprovider.Initialize(providerConf, configDir)
  1753. if err != nil {
  1754. t.Errorf("error initializing data provider")
  1755. }
  1756. httpd.SetDataProvider(dataprovider.GetProvider())
  1757. sftpd.SetDataProvider(dataprovider.GetProvider())
  1758. }
  1759. func TestMaxSessions(t *testing.T) {
  1760. usePubKey := false
  1761. u := getTestUser(usePubKey)
  1762. u.Username += "1"
  1763. u.MaxSessions = 1
  1764. user, _, err := httpd.AddUser(u, http.StatusOK)
  1765. if err != nil {
  1766. t.Errorf("unable to add user: %v", err)
  1767. }
  1768. client, err := getSftpClient(user, usePubKey)
  1769. if err != nil {
  1770. t.Errorf("unable to create sftp client: %v", err)
  1771. } else {
  1772. defer client.Close()
  1773. _, err := client.Getwd()
  1774. if err != nil {
  1775. t.Errorf("unable to get working dir: %v", err)
  1776. }
  1777. _, err = client.ReadDir(".")
  1778. if err != nil {
  1779. t.Errorf("unable to read remote dir: %v", err)
  1780. }
  1781. _, err = getSftpClient(user, usePubKey)
  1782. if err == nil {
  1783. t.Errorf("max sessions exceeded, new login should not succeed")
  1784. }
  1785. }
  1786. _, err = httpd.RemoveUser(user, http.StatusOK)
  1787. if err != nil {
  1788. t.Errorf("unable to remove user: %v", err)
  1789. }
  1790. os.RemoveAll(user.GetHomeDir())
  1791. }
  1792. func TestQuotaFileReplace(t *testing.T) {
  1793. usePubKey := false
  1794. u := getTestUser(usePubKey)
  1795. u.QuotaFiles = 1000
  1796. user, _, err := httpd.AddUser(u, http.StatusOK)
  1797. if err != nil {
  1798. t.Errorf("unable to add user: %v", err)
  1799. }
  1800. os.RemoveAll(user.GetHomeDir())
  1801. testFileSize := int64(65535)
  1802. testFileName := "test_file.dat"
  1803. testFilePath := filepath.Join(homeBasePath, testFileName)
  1804. client, err := getSftpClient(user, usePubKey)
  1805. if err != nil {
  1806. t.Errorf("unable to create sftp client: %v", err)
  1807. } else {
  1808. defer client.Close()
  1809. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  1810. expectedQuotaFiles := user.UsedQuotaFiles + 1
  1811. err = createTestFile(testFilePath, testFileSize)
  1812. if err != nil {
  1813. t.Errorf("unable to create test file: %v", err)
  1814. }
  1815. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1816. if err != nil {
  1817. t.Errorf("file upload error: %v", err)
  1818. }
  1819. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1820. if err != nil {
  1821. t.Errorf("error getting user: %v", err)
  1822. }
  1823. // now replace the same file, the quota must not change
  1824. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1825. if err != nil {
  1826. t.Errorf("file upload error: %v", err)
  1827. }
  1828. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1829. if err != nil {
  1830. t.Errorf("error getting user: %v", err)
  1831. }
  1832. if expectedQuotaFiles != user.UsedQuotaFiles {
  1833. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  1834. }
  1835. if expectedQuotaSize != user.UsedQuotaSize {
  1836. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  1837. }
  1838. }
  1839. // now set a quota size restriction and upload the same file, upload should fail for space limit exceeded
  1840. user.QuotaSize = testFileSize - 1
  1841. user, _, err = httpd.UpdateUser(user, http.StatusOK)
  1842. if err != nil {
  1843. t.Errorf("error updating user: %v", err)
  1844. }
  1845. client, err = getSftpClient(user, usePubKey)
  1846. if err != nil {
  1847. t.Errorf("unable to create sftp client: %v", err)
  1848. } else {
  1849. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1850. if err == nil {
  1851. t.Errorf("quota size exceeded, file upload must fail")
  1852. }
  1853. err = client.Remove(testFileName)
  1854. if err != nil {
  1855. t.Errorf("error removing uploaded file: %v", err)
  1856. }
  1857. }
  1858. _, err = httpd.RemoveUser(user, http.StatusOK)
  1859. if err != nil {
  1860. t.Errorf("unable to remove user: %v", err)
  1861. }
  1862. os.Remove(testFilePath)
  1863. os.RemoveAll(user.GetHomeDir())
  1864. }
  1865. func TestQuotaScan(t *testing.T) {
  1866. usePubKey := false
  1867. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1868. if err != nil {
  1869. t.Errorf("unable to add user: %v", err)
  1870. }
  1871. testFileSize := int64(65535)
  1872. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  1873. expectedQuotaFiles := user.UsedQuotaFiles + 1
  1874. client, err := getSftpClient(user, usePubKey)
  1875. if err != nil {
  1876. t.Errorf("unable to create sftp client: %v", err)
  1877. } else {
  1878. defer client.Close()
  1879. testFileName := "test_file.dat"
  1880. testFilePath := filepath.Join(homeBasePath, testFileName)
  1881. err = createTestFile(testFilePath, testFileSize)
  1882. if err != nil {
  1883. t.Errorf("unable to create test file: %v", err)
  1884. }
  1885. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  1886. if err != nil {
  1887. t.Errorf("file upload error: %v", err)
  1888. }
  1889. os.Remove(testFilePath)
  1890. }
  1891. _, err = httpd.RemoveUser(user, http.StatusOK)
  1892. if err != nil {
  1893. t.Errorf("unable to remove user: %v", err)
  1894. }
  1895. // create user with the same home dir, so there is at least an untracked file
  1896. user, _, err = httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  1897. if err != nil {
  1898. t.Errorf("unable to add user: %v", err)
  1899. }
  1900. _, err = httpd.StartQuotaScan(user, http.StatusCreated)
  1901. if err != nil {
  1902. t.Errorf("error starting quota scan: %v", err)
  1903. }
  1904. err = waitQuotaScans()
  1905. if err != nil {
  1906. t.Errorf("error waiting for active quota scans: %v", err)
  1907. }
  1908. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  1909. if err != nil {
  1910. t.Errorf("error getting user: %v", err)
  1911. }
  1912. if expectedQuotaFiles != user.UsedQuotaFiles {
  1913. t.Errorf("quota files does not match after scan, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  1914. }
  1915. if expectedQuotaSize != user.UsedQuotaSize {
  1916. t.Errorf("quota size does not match after scan, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  1917. }
  1918. _, err = httpd.RemoveUser(user, http.StatusOK)
  1919. if err != nil {
  1920. t.Errorf("unable to remove user: %v", err)
  1921. }
  1922. os.RemoveAll(user.GetHomeDir())
  1923. }
  1924. func TestMultipleQuotaScans(t *testing.T) {
  1925. if !sftpd.AddQuotaScan(defaultUsername) {
  1926. t.Errorf("add quota failed")
  1927. }
  1928. if sftpd.AddQuotaScan(defaultUsername) {
  1929. t.Errorf("add quota must fail if another scan is already active")
  1930. }
  1931. sftpd.RemoveQuotaScan(defaultUsername)
  1932. activeScans := sftpd.GetQuotaScans()
  1933. if len(activeScans) > 0 {
  1934. t.Errorf("no quota scan must be active: %v", len(activeScans))
  1935. }
  1936. }
  1937. func TestQuotaSize(t *testing.T) {
  1938. usePubKey := false
  1939. testFileSize := int64(65535)
  1940. u := getTestUser(usePubKey)
  1941. u.QuotaFiles = 1
  1942. u.QuotaSize = testFileSize - 1
  1943. user, _, err := httpd.AddUser(u, http.StatusOK)
  1944. if err != nil {
  1945. t.Errorf("unable to add user: %v", err)
  1946. }
  1947. client, err := getSftpClient(user, usePubKey)
  1948. if err != nil {
  1949. t.Errorf("unable to create sftp client: %v", err)
  1950. } else {
  1951. defer client.Close()
  1952. testFileName := "test_file.dat"
  1953. testFilePath := filepath.Join(homeBasePath, testFileName)
  1954. err = createTestFile(testFilePath, testFileSize)
  1955. if err != nil {
  1956. t.Errorf("unable to create test file: %v", err)
  1957. }
  1958. err = sftpUploadFile(testFilePath, testFileName+".quota", testFileSize, client)
  1959. if err != nil {
  1960. t.Errorf("file upload error: %v", err)
  1961. }
  1962. err = sftpUploadFile(testFilePath, testFileName+".quota.1", testFileSize, client)
  1963. if err == nil {
  1964. t.Errorf("user is over quota file upload must fail")
  1965. }
  1966. err = client.Remove(testFileName + ".quota")
  1967. if err != nil {
  1968. t.Errorf("error removing uploaded file: %v", err)
  1969. }
  1970. os.Remove(testFilePath)
  1971. }
  1972. _, err = httpd.RemoveUser(user, http.StatusOK)
  1973. if err != nil {
  1974. t.Errorf("unable to remove user: %v", err)
  1975. }
  1976. os.RemoveAll(user.GetHomeDir())
  1977. }
  1978. func TestBandwidthAndConnections(t *testing.T) {
  1979. usePubKey := false
  1980. testFileSize := int64(131072)
  1981. u := getTestUser(usePubKey)
  1982. u.UploadBandwidth = 30
  1983. u.DownloadBandwidth = 25
  1984. wantedUploadElapsed := 1000 * (testFileSize / 1000) / u.UploadBandwidth
  1985. wantedDownloadElapsed := 1000 * (testFileSize / 1000) / u.DownloadBandwidth
  1986. // 100 ms tolerance
  1987. wantedUploadElapsed -= 100
  1988. wantedDownloadElapsed -= 100
  1989. user, _, err := httpd.AddUser(u, http.StatusOK)
  1990. if err != nil {
  1991. t.Errorf("unable to add user: %v", err)
  1992. }
  1993. client, err := getSftpClient(user, usePubKey)
  1994. if err != nil {
  1995. t.Errorf("unable to create sftp client: %v", err)
  1996. } else {
  1997. defer client.Close()
  1998. testFileName := "test_file.dat"
  1999. testFilePath := filepath.Join(homeBasePath, testFileName)
  2000. err = createTestFile(testFilePath, testFileSize)
  2001. if err != nil {
  2002. t.Errorf("unable to create test file: %v", err)
  2003. }
  2004. startTime := time.Now()
  2005. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2006. if err != nil {
  2007. t.Errorf("file upload error: %v", err)
  2008. }
  2009. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  2010. if elapsed < (wantedUploadElapsed) {
  2011. t.Errorf("upload bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedUploadElapsed)
  2012. }
  2013. startTime = time.Now()
  2014. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2015. c := sftpDownloadNonBlocking(testFileName, localDownloadPath, testFileSize, client)
  2016. waitForActiveTransfer()
  2017. // wait some additional arbitrary time to wait for transfer activity to happen
  2018. // it is need to reach all the code in CheckIdleConnections
  2019. time.Sleep(100 * time.Millisecond)
  2020. sftpd.CheckIdleConnections()
  2021. err = <-c
  2022. if err != nil {
  2023. t.Errorf("file download error: %v", err)
  2024. }
  2025. elapsed = time.Since(startTime).Nanoseconds() / 1000000
  2026. if elapsed < (wantedDownloadElapsed) {
  2027. t.Errorf("download bandwidth throttling not respected, elapsed: %v, wanted: %v", elapsed, wantedDownloadElapsed)
  2028. }
  2029. // test disconnection
  2030. c = sftpUploadNonBlocking(testFilePath, testFileName+"_partial", testFileSize, client)
  2031. waitForActiveTransfer()
  2032. time.Sleep(100 * time.Millisecond)
  2033. sftpd.CheckIdleConnections()
  2034. stats := sftpd.GetConnectionsStats()
  2035. for _, stat := range stats {
  2036. sftpd.CloseActiveConnection(stat.ConnectionID)
  2037. }
  2038. err = <-c
  2039. if err == nil {
  2040. t.Errorf("connection closed upload must fail")
  2041. }
  2042. os.Remove(testFilePath)
  2043. os.Remove(localDownloadPath)
  2044. }
  2045. _, err = httpd.RemoveUser(user, http.StatusOK)
  2046. if err != nil {
  2047. t.Errorf("unable to remove user: %v", err)
  2048. }
  2049. os.RemoveAll(user.GetHomeDir())
  2050. }
  2051. func TestExtensionsFilters(t *testing.T) {
  2052. usePubKey := true
  2053. u := getTestUser(usePubKey)
  2054. user, _, err := httpd.AddUser(u, http.StatusOK)
  2055. if err != nil {
  2056. t.Errorf("unable to add user: %v", err)
  2057. }
  2058. testFileSize := int64(131072)
  2059. testFileName := "test_file.dat"
  2060. testFilePath := filepath.Join(homeBasePath, testFileName)
  2061. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2062. client, err := getSftpClient(user, usePubKey)
  2063. if err != nil {
  2064. t.Errorf("unable to create sftp client: %v", err)
  2065. } else {
  2066. defer client.Close()
  2067. err = createTestFile(testFilePath, testFileSize)
  2068. if err != nil {
  2069. t.Errorf("unable to create test file: %v", err)
  2070. }
  2071. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2072. if err != nil {
  2073. t.Errorf("file upload error: %v", err)
  2074. }
  2075. }
  2076. user.Filters.FileExtensions = []dataprovider.ExtensionsFilter{
  2077. dataprovider.ExtensionsFilter{
  2078. Path: "/",
  2079. AllowedExtensions: []string{".zip"},
  2080. DeniedExtensions: []string{},
  2081. },
  2082. }
  2083. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  2084. if err != nil {
  2085. t.Errorf("unable to update user: %v", err)
  2086. }
  2087. client, err = getSftpClient(user, usePubKey)
  2088. if err != nil {
  2089. t.Errorf("unable to create sftp client: %v", err)
  2090. } else {
  2091. defer client.Close()
  2092. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2093. if err == nil {
  2094. t.Error("file upload must fail")
  2095. }
  2096. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2097. if err == nil {
  2098. t.Error("file download must fail")
  2099. }
  2100. err = client.Rename(testFileName, testFileName+"1")
  2101. if err == nil {
  2102. t.Error("rename must fail")
  2103. }
  2104. err = client.Remove(testFileName)
  2105. if err == nil {
  2106. t.Error("remove must fail")
  2107. }
  2108. err = client.Mkdir("dir.zip")
  2109. if err != nil {
  2110. t.Errorf("unexpected error: %v", err)
  2111. }
  2112. err = client.Rename("dir.zip", "dir1.zip")
  2113. if err != nil {
  2114. t.Errorf("unexpected error: %v", err)
  2115. }
  2116. }
  2117. _, err = httpd.RemoveUser(user, http.StatusOK)
  2118. if err != nil {
  2119. t.Errorf("unable to remove user: %v", err)
  2120. }
  2121. os.Remove(testFilePath)
  2122. os.Remove(localDownloadPath)
  2123. os.RemoveAll(user.GetHomeDir())
  2124. }
  2125. func TestVirtualFolders(t *testing.T) {
  2126. usePubKey := true
  2127. u := getTestUser(usePubKey)
  2128. mappedPath := filepath.Join(os.TempDir(), "vdir")
  2129. vdirPath := "/vdir"
  2130. u.VirtualFolders = append(u.VirtualFolders, vfs.VirtualFolder{
  2131. VirtualPath: vdirPath,
  2132. MappedPath: mappedPath,
  2133. })
  2134. os.MkdirAll(mappedPath, 0777)
  2135. user, _, err := httpd.AddUser(u, http.StatusOK)
  2136. if err != nil {
  2137. t.Errorf("unable to add user: %v", err)
  2138. }
  2139. client, err := getSftpClient(user, usePubKey)
  2140. if err != nil {
  2141. t.Errorf("unable to create sftp client: %v", err)
  2142. } else {
  2143. defer client.Close()
  2144. testFileSize := int64(131072)
  2145. testFileName := "test_file.dat"
  2146. testFilePath := filepath.Join(homeBasePath, testFileName)
  2147. err = createTestFile(testFilePath, testFileSize)
  2148. if err != nil {
  2149. t.Errorf("unable to create test file: %v", err)
  2150. }
  2151. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2152. err = sftpUploadFile(testFilePath, path.Join(vdirPath, testFileName), testFileSize, client)
  2153. if err != nil {
  2154. t.Errorf("file upload error: %v", err)
  2155. }
  2156. err = sftpDownloadFile(path.Join(vdirPath, testFileName), localDownloadPath, testFileSize, client)
  2157. if err != nil {
  2158. t.Errorf("file download error: %v", err)
  2159. }
  2160. err = client.Rename(vdirPath, "new_name")
  2161. if err == nil {
  2162. t.Error("renaming a virtual folder must fail")
  2163. }
  2164. err = client.RemoveDirectory(vdirPath)
  2165. if err == nil {
  2166. t.Error("removing a virtual folder must fail")
  2167. }
  2168. err = client.Mkdir(vdirPath)
  2169. if err == nil {
  2170. t.Error("creating a virtual folder must fail")
  2171. }
  2172. err = client.Symlink(path.Join(vdirPath, testFileName), vdirPath)
  2173. if err == nil {
  2174. t.Error("symlink to a virtual folder must fail")
  2175. }
  2176. os.Remove(testFilePath)
  2177. os.Remove(localDownloadPath)
  2178. }
  2179. _, err = httpd.RemoveUser(user, http.StatusOK)
  2180. if err != nil {
  2181. t.Errorf("unable to remove user: %v", err)
  2182. }
  2183. os.RemoveAll(user.GetHomeDir())
  2184. os.RemoveAll(mappedPath)
  2185. }
  2186. func TestMissingFile(t *testing.T) {
  2187. usePubKey := false
  2188. u := getTestUser(usePubKey)
  2189. user, _, err := httpd.AddUser(u, http.StatusOK)
  2190. if err != nil {
  2191. t.Errorf("unable to add user: %v", err)
  2192. }
  2193. client, err := getSftpClient(user, usePubKey)
  2194. if err != nil {
  2195. t.Errorf("unable to create sftp client: %v", err)
  2196. } else {
  2197. defer client.Close()
  2198. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2199. err = sftpDownloadFile("missing_file", localDownloadPath, 0, client)
  2200. if err == nil {
  2201. t.Errorf("download missing file must fail")
  2202. }
  2203. os.Remove(localDownloadPath)
  2204. }
  2205. _, err = httpd.RemoveUser(user, http.StatusOK)
  2206. if err != nil {
  2207. t.Errorf("unable to remove user: %v", err)
  2208. }
  2209. os.RemoveAll(user.GetHomeDir())
  2210. }
  2211. func TestOpenError(t *testing.T) {
  2212. if runtime.GOOS == "windows" {
  2213. t.Skip("this test is not available on Windows")
  2214. }
  2215. usePubKey := false
  2216. u := getTestUser(usePubKey)
  2217. user, _, err := httpd.AddUser(u, http.StatusOK)
  2218. if err != nil {
  2219. t.Errorf("unable to add user: %v", err)
  2220. }
  2221. os.RemoveAll(user.GetHomeDir())
  2222. client, err := getSftpClient(user, usePubKey)
  2223. if err != nil {
  2224. t.Errorf("unable to create sftp client: %v", err)
  2225. } else {
  2226. defer client.Close()
  2227. os.Chmod(user.GetHomeDir(), 0001)
  2228. _, err = client.ReadDir(".")
  2229. if err == nil {
  2230. t.Errorf("read dir must fail if we have no filesystem read permissions")
  2231. }
  2232. os.Chmod(user.GetHomeDir(), 0755)
  2233. testFileSize := int64(65535)
  2234. testFileName := "test_file.dat"
  2235. testFilePath := filepath.Join(user.GetHomeDir(), testFileName)
  2236. err = createTestFile(testFilePath, testFileSize)
  2237. if err != nil {
  2238. t.Errorf("unable to create test file: %v", err)
  2239. }
  2240. _, err = client.Stat(testFileName)
  2241. if err != nil {
  2242. t.Errorf("file stat error: %v", err)
  2243. }
  2244. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2245. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2246. if err != nil {
  2247. t.Errorf("file download error: %v", err)
  2248. }
  2249. os.Chmod(testFilePath, 0001)
  2250. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2251. if err == nil {
  2252. t.Errorf("file download must fail if we have no filesystem read permissions")
  2253. }
  2254. err = sftpUploadFile(localDownloadPath, testFileName, testFileSize, client)
  2255. if err == nil {
  2256. t.Errorf("upload must fail if we have no filesystem write permissions")
  2257. }
  2258. err = client.Mkdir("test")
  2259. if err != nil {
  2260. t.Errorf("error making dir: %v", err)
  2261. }
  2262. os.Chmod(user.GetHomeDir(), 0000)
  2263. _, err = client.Lstat(testFileName)
  2264. if err == nil {
  2265. t.Errorf("file stat must fail if we have no filesystem read permissions")
  2266. }
  2267. os.Chmod(user.GetHomeDir(), 0755)
  2268. os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0000)
  2269. err = client.Rename(testFileName, path.Join("test", testFileName))
  2270. if err == nil || !strings.Contains(err.Error(), sftp.ErrSSHFxPermissionDenied.Error()) {
  2271. t.Errorf("unexpected error: %v expected: %v", err, sftp.ErrSSHFxPermissionDenied)
  2272. }
  2273. os.Chmod(filepath.Join(user.GetHomeDir(), "test"), 0755)
  2274. os.Remove(testFilePath)
  2275. os.Remove(localDownloadPath)
  2276. }
  2277. _, err = httpd.RemoveUser(user, http.StatusOK)
  2278. if err != nil {
  2279. t.Errorf("unable to remove user: %v", err)
  2280. }
  2281. os.RemoveAll(user.GetHomeDir())
  2282. }
  2283. func TestOverwriteDirWithFile(t *testing.T) {
  2284. usePubKey := false
  2285. u := getTestUser(usePubKey)
  2286. user, _, err := httpd.AddUser(u, http.StatusOK)
  2287. if err != nil {
  2288. t.Errorf("unable to add user: %v", err)
  2289. }
  2290. client, err := getSftpClient(user, usePubKey)
  2291. if err != nil {
  2292. t.Errorf("unable to create sftp client: %v", err)
  2293. } else {
  2294. defer client.Close()
  2295. testFileSize := int64(65535)
  2296. testFileName := "test_file.dat"
  2297. testDirName := "test_dir"
  2298. testFilePath := filepath.Join(homeBasePath, testFileName)
  2299. err = createTestFile(testFilePath, testFileSize)
  2300. if err != nil {
  2301. t.Errorf("unable to create test file: %v", err)
  2302. }
  2303. err = client.Mkdir(testDirName)
  2304. if err != nil {
  2305. t.Errorf("mkdir error: %v", err)
  2306. }
  2307. err = sftpUploadFile(testFilePath, testDirName, testFileSize, client)
  2308. if err == nil {
  2309. t.Errorf("copying a file over an existing dir must fail")
  2310. }
  2311. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2312. if err != nil {
  2313. t.Errorf("file upload error: %v", err)
  2314. }
  2315. err = client.Rename(testFileName, testDirName)
  2316. if err == nil {
  2317. t.Errorf("rename a file over an existing dir must fail")
  2318. }
  2319. err = client.RemoveDirectory(testDirName)
  2320. if err != nil {
  2321. t.Errorf("dir remove error: %v", err)
  2322. }
  2323. err = client.Remove(testFileName)
  2324. if err != nil {
  2325. t.Errorf("error removing uploaded file: %v", err)
  2326. }
  2327. os.Remove(testFilePath)
  2328. }
  2329. _, err = httpd.RemoveUser(user, http.StatusOK)
  2330. if err != nil {
  2331. t.Errorf("unable to remove user: %v", err)
  2332. }
  2333. os.RemoveAll(user.GetHomeDir())
  2334. }
  2335. func TestPasswordsHashPbkdf2Sha1(t *testing.T) {
  2336. pbkdf2Pwd := "$pbkdf2-sha1$150000$DveVjgYUD05R$X6ydQZdyMeOvpgND2nqGR/0GGic="
  2337. pbkdf2ClearPwd := "password"
  2338. usePubKey := false
  2339. u := getTestUser(usePubKey)
  2340. u.Password = pbkdf2Pwd
  2341. user, _, err := httpd.AddUser(u, http.StatusOK)
  2342. if err != nil {
  2343. t.Errorf("unable to add user: %v", err)
  2344. }
  2345. user.Password = pbkdf2ClearPwd
  2346. client, err := getSftpClient(user, usePubKey)
  2347. if err != nil {
  2348. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2349. } else {
  2350. defer client.Close()
  2351. _, err = client.Getwd()
  2352. if err != nil {
  2353. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2354. }
  2355. }
  2356. user.Password = pbkdf2Pwd
  2357. _, err = getSftpClient(user, usePubKey)
  2358. if err == nil {
  2359. t.Errorf("login with wrong password must fail")
  2360. }
  2361. _, err = httpd.RemoveUser(user, http.StatusOK)
  2362. if err != nil {
  2363. t.Errorf("unable to remove user: %v", err)
  2364. }
  2365. os.RemoveAll(user.GetHomeDir())
  2366. }
  2367. func TestPasswordsHashPbkdf2Sha256(t *testing.T) {
  2368. pbkdf2Pwd := "$pbkdf2-sha256$150000$E86a9YMX3zC7$R5J62hsSq+pYw00hLLPKBbcGXmq7fj5+/M0IFoYtZbo="
  2369. pbkdf2ClearPwd := "password"
  2370. usePubKey := false
  2371. u := getTestUser(usePubKey)
  2372. u.Password = pbkdf2Pwd
  2373. user, _, err := httpd.AddUser(u, http.StatusOK)
  2374. if err != nil {
  2375. t.Errorf("unable to add user: %v", err)
  2376. }
  2377. user.Password = pbkdf2ClearPwd
  2378. client, err := getSftpClient(user, usePubKey)
  2379. if err != nil {
  2380. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2381. } else {
  2382. defer client.Close()
  2383. _, err = client.Getwd()
  2384. if err != nil {
  2385. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2386. }
  2387. }
  2388. user.Password = pbkdf2Pwd
  2389. _, err = getSftpClient(user, usePubKey)
  2390. if err == nil {
  2391. t.Errorf("login with wrong password must fail")
  2392. }
  2393. _, err = httpd.RemoveUser(user, http.StatusOK)
  2394. if err != nil {
  2395. t.Errorf("unable to remove user: %v", err)
  2396. }
  2397. os.RemoveAll(user.GetHomeDir())
  2398. }
  2399. func TestPasswordsHashPbkdf2Sha512(t *testing.T) {
  2400. pbkdf2Pwd := "$pbkdf2-sha512$150000$dsu7T5R3IaVQ$1hFXPO1ntRBcoWkSLKw+s4sAP09Xtu4Ya7CyxFq64jM9zdUg8eRJVr3NcR2vQgb0W9HHvZaILHsL4Q/Vr6arCg=="
  2401. pbkdf2ClearPwd := "password"
  2402. usePubKey := false
  2403. u := getTestUser(usePubKey)
  2404. u.Password = pbkdf2Pwd
  2405. user, _, err := httpd.AddUser(u, http.StatusOK)
  2406. if err != nil {
  2407. t.Errorf("unable to add user: %v", err)
  2408. }
  2409. user.Password = pbkdf2ClearPwd
  2410. client, err := getSftpClient(user, usePubKey)
  2411. if err != nil {
  2412. t.Errorf("unable to login with pkkdf2 sha1 password: %v", err)
  2413. } else {
  2414. defer client.Close()
  2415. _, err = client.Getwd()
  2416. if err != nil {
  2417. t.Errorf("unable to get working dir with pkkdf2 sha1 password: %v", err)
  2418. }
  2419. }
  2420. user.Password = pbkdf2Pwd
  2421. _, err = getSftpClient(user, usePubKey)
  2422. if err == nil {
  2423. t.Errorf("login with wrong password must fail")
  2424. }
  2425. _, err = httpd.RemoveUser(user, http.StatusOK)
  2426. if err != nil {
  2427. t.Errorf("unable to remove user: %v", err)
  2428. }
  2429. os.RemoveAll(user.GetHomeDir())
  2430. }
  2431. func TestPasswordsHashBcrypt(t *testing.T) {
  2432. bcryptPwd := "$2a$14$ajq8Q7fbtFRQvXpdCq7Jcuy.Rx1h/L4J60Otx.gyNLbAYctGMJ9tK"
  2433. bcryptClearPwd := "secret"
  2434. usePubKey := false
  2435. u := getTestUser(usePubKey)
  2436. u.Password = bcryptPwd
  2437. user, _, err := httpd.AddUser(u, http.StatusOK)
  2438. if err != nil {
  2439. t.Errorf("unable to add user: %v", err)
  2440. }
  2441. user.Password = bcryptClearPwd
  2442. client, err := getSftpClient(user, usePubKey)
  2443. if err != nil {
  2444. t.Errorf("unable to login with bcrypt password: %v", err)
  2445. } else {
  2446. defer client.Close()
  2447. _, err = client.Getwd()
  2448. if err != nil {
  2449. t.Errorf("unable to get working dir with bcrypt password: %v", err)
  2450. }
  2451. }
  2452. user.Password = bcryptPwd
  2453. _, err = getSftpClient(user, usePubKey)
  2454. if err == nil {
  2455. t.Errorf("login with wrong password must fail")
  2456. }
  2457. _, err = httpd.RemoveUser(user, http.StatusOK)
  2458. if err != nil {
  2459. t.Errorf("unable to remove user: %v", err)
  2460. }
  2461. os.RemoveAll(user.GetHomeDir())
  2462. }
  2463. func TestPasswordsHashSHA512Crypt(t *testing.T) {
  2464. sha512CryptPwd := "$6$459ead56b72e44bc$uog86fUxscjt28BZxqFBE2pp2QD8P/1e98MNF75Z9xJfQvOckZnQ/1YJqiq1XeytPuDieHZvDAMoP7352ELkO1"
  2465. clearPwd := "secret"
  2466. usePubKey := false
  2467. u := getTestUser(usePubKey)
  2468. u.Password = sha512CryptPwd
  2469. user, _, err := httpd.AddUser(u, http.StatusOK)
  2470. if err != nil {
  2471. t.Errorf("unable to add user: %v", err)
  2472. }
  2473. user.Password = clearPwd
  2474. client, err := getSftpClient(user, usePubKey)
  2475. if err != nil {
  2476. t.Errorf("unable to login with sha512 crypt password: %v", err)
  2477. } else {
  2478. defer client.Close()
  2479. _, err = client.Getwd()
  2480. if err != nil {
  2481. t.Errorf("unable to get working dir with sha512 crypt password: %v", err)
  2482. }
  2483. }
  2484. user.Password = sha512CryptPwd
  2485. _, err = getSftpClient(user, usePubKey)
  2486. if err == nil {
  2487. t.Errorf("login with wrong password must fail")
  2488. }
  2489. _, err = httpd.RemoveUser(user, http.StatusOK)
  2490. if err != nil {
  2491. t.Errorf("unable to remove user: %v", err)
  2492. }
  2493. os.RemoveAll(user.GetHomeDir())
  2494. }
  2495. func TestPasswordsHashMD5Crypt(t *testing.T) {
  2496. md5CryptPwd := "$1$b5caebda$VODr/nyhGWgZaY8sJ4x05."
  2497. clearPwd := "password"
  2498. usePubKey := false
  2499. u := getTestUser(usePubKey)
  2500. u.Password = md5CryptPwd
  2501. user, _, err := httpd.AddUser(u, http.StatusOK)
  2502. if err != nil {
  2503. t.Errorf("unable to add user: %v", err)
  2504. }
  2505. user.Password = clearPwd
  2506. client, err := getSftpClient(user, usePubKey)
  2507. if err != nil {
  2508. t.Errorf("unable to login with md5 crypt password: %v", err)
  2509. } else {
  2510. defer client.Close()
  2511. _, err = client.Getwd()
  2512. if err != nil {
  2513. t.Errorf("unable to get working dir with md5 crypt password: %v", err)
  2514. }
  2515. }
  2516. user.Password = md5CryptPwd
  2517. _, err = getSftpClient(user, usePubKey)
  2518. if err == nil {
  2519. t.Errorf("login with wrong password must fail")
  2520. }
  2521. _, err = httpd.RemoveUser(user, http.StatusOK)
  2522. if err != nil {
  2523. t.Errorf("unable to remove user: %v", err)
  2524. }
  2525. os.RemoveAll(user.GetHomeDir())
  2526. }
  2527. func TestPasswordsHashMD5CryptApr1(t *testing.T) {
  2528. md5CryptPwd := "$apr1$OBWLeSme$WoJbB736e7kKxMBIAqilb1"
  2529. clearPwd := "password"
  2530. usePubKey := false
  2531. u := getTestUser(usePubKey)
  2532. u.Password = md5CryptPwd
  2533. user, _, err := httpd.AddUser(u, http.StatusOK)
  2534. if err != nil {
  2535. t.Errorf("unable to add user: %v", err)
  2536. }
  2537. user.Password = clearPwd
  2538. client, err := getSftpClient(user, usePubKey)
  2539. if err != nil {
  2540. t.Errorf("unable to login with md5 crypt password: %v", err)
  2541. } else {
  2542. defer client.Close()
  2543. _, err = client.Getwd()
  2544. if err != nil {
  2545. t.Errorf("unable to get working dir with md5 crypt password: %v", err)
  2546. }
  2547. }
  2548. user.Password = md5CryptPwd
  2549. _, err = getSftpClient(user, usePubKey)
  2550. if err == nil {
  2551. t.Errorf("login with wrong password must fail")
  2552. }
  2553. _, err = httpd.RemoveUser(user, http.StatusOK)
  2554. if err != nil {
  2555. t.Errorf("unable to remove user: %v", err)
  2556. }
  2557. os.RemoveAll(user.GetHomeDir())
  2558. }
  2559. func TestPermList(t *testing.T) {
  2560. usePubKey := true
  2561. u := getTestUser(usePubKey)
  2562. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  2563. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2564. dataprovider.PermChown, dataprovider.PermChtimes}
  2565. user, _, err := httpd.AddUser(u, http.StatusOK)
  2566. if err != nil {
  2567. t.Errorf("unable to add user: %v", err)
  2568. }
  2569. client, err := getSftpClient(user, usePubKey)
  2570. if err != nil {
  2571. t.Errorf("unable to create sftp client: %v", err)
  2572. } else {
  2573. defer client.Close()
  2574. _, err = client.ReadDir(".")
  2575. if err == nil {
  2576. t.Errorf("read remote dir without permission should not succeed")
  2577. }
  2578. _, err = client.Stat("test_file")
  2579. if err == nil {
  2580. t.Errorf("stat remote file without permission should not succeed")
  2581. }
  2582. }
  2583. _, err = httpd.RemoveUser(user, http.StatusOK)
  2584. if err != nil {
  2585. t.Errorf("unable to remove user: %v", err)
  2586. }
  2587. os.RemoveAll(user.GetHomeDir())
  2588. }
  2589. func TestPermDownload(t *testing.T) {
  2590. usePubKey := true
  2591. u := getTestUser(usePubKey)
  2592. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermUpload, dataprovider.PermDelete, dataprovider.PermRename,
  2593. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2594. dataprovider.PermChown, dataprovider.PermChtimes}
  2595. user, _, err := httpd.AddUser(u, http.StatusOK)
  2596. if err != nil {
  2597. t.Errorf("unable to add user: %v", err)
  2598. }
  2599. client, err := getSftpClient(user, usePubKey)
  2600. if err != nil {
  2601. t.Errorf("unable to create sftp client: %v", err)
  2602. } else {
  2603. defer client.Close()
  2604. testFileName := "test_file.dat"
  2605. testFilePath := filepath.Join(homeBasePath, testFileName)
  2606. testFileSize := int64(65535)
  2607. err = createTestFile(testFilePath, testFileSize)
  2608. if err != nil {
  2609. t.Errorf("unable to create test file: %v", err)
  2610. }
  2611. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2612. if err != nil {
  2613. t.Errorf("file upload error: %v", err)
  2614. }
  2615. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  2616. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  2617. if err == nil {
  2618. t.Errorf("file download without permission should not succeed")
  2619. }
  2620. err = client.Remove(testFileName)
  2621. if err != nil {
  2622. t.Errorf("error removing uploaded file: %v", err)
  2623. }
  2624. os.Remove(testFilePath)
  2625. os.Remove(localDownloadPath)
  2626. }
  2627. _, err = httpd.RemoveUser(user, http.StatusOK)
  2628. if err != nil {
  2629. t.Errorf("unable to remove user: %v", err)
  2630. }
  2631. os.RemoveAll(user.GetHomeDir())
  2632. }
  2633. func TestPermUpload(t *testing.T) {
  2634. usePubKey := false
  2635. u := getTestUser(usePubKey)
  2636. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermDelete, dataprovider.PermRename,
  2637. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2638. dataprovider.PermChown, dataprovider.PermChtimes}
  2639. user, _, err := httpd.AddUser(u, http.StatusOK)
  2640. if err != nil {
  2641. t.Errorf("unable to add user: %v", err)
  2642. }
  2643. client, err := getSftpClient(user, usePubKey)
  2644. if err != nil {
  2645. t.Errorf("unable to create sftp client: %v", err)
  2646. } else {
  2647. defer client.Close()
  2648. testFileName := "test_file.dat"
  2649. testFilePath := filepath.Join(homeBasePath, testFileName)
  2650. testFileSize := int64(65535)
  2651. err = createTestFile(testFilePath, testFileSize)
  2652. if err != nil {
  2653. t.Errorf("unable to create test file: %v", err)
  2654. }
  2655. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2656. if err == nil {
  2657. t.Errorf("file upload without permission should not succeed")
  2658. }
  2659. os.Remove(testFilePath)
  2660. }
  2661. _, err = httpd.RemoveUser(user, http.StatusOK)
  2662. if err != nil {
  2663. t.Errorf("unable to remove user: %v", err)
  2664. }
  2665. os.RemoveAll(user.GetHomeDir())
  2666. }
  2667. func TestPermOverwrite(t *testing.T) {
  2668. usePubKey := false
  2669. u := getTestUser(usePubKey)
  2670. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2671. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermChmod,
  2672. dataprovider.PermChown, dataprovider.PermChtimes}
  2673. user, _, err := httpd.AddUser(u, http.StatusOK)
  2674. if err != nil {
  2675. t.Errorf("unable to add user: %v", err)
  2676. }
  2677. client, err := getSftpClient(user, usePubKey)
  2678. if err != nil {
  2679. t.Errorf("unable to create sftp client: %v", err)
  2680. } else {
  2681. defer client.Close()
  2682. testFileName := "test_file.dat"
  2683. testFilePath := filepath.Join(homeBasePath, testFileName)
  2684. testFileSize := int64(65535)
  2685. err = createTestFile(testFilePath, testFileSize)
  2686. if err != nil {
  2687. t.Errorf("unable to create test file: %v", err)
  2688. }
  2689. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2690. if err != nil {
  2691. t.Errorf("error uploading file: %v", err)
  2692. }
  2693. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2694. if err == nil {
  2695. t.Errorf("file overwrite without permission should not succeed")
  2696. }
  2697. os.Remove(testFilePath)
  2698. }
  2699. _, err = httpd.RemoveUser(user, http.StatusOK)
  2700. if err != nil {
  2701. t.Errorf("unable to remove user: %v", err)
  2702. }
  2703. os.RemoveAll(user.GetHomeDir())
  2704. }
  2705. func TestPermDelete(t *testing.T) {
  2706. usePubKey := false
  2707. u := getTestUser(usePubKey)
  2708. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermRename,
  2709. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2710. dataprovider.PermChown, dataprovider.PermChtimes}
  2711. user, _, err := httpd.AddUser(u, http.StatusOK)
  2712. if err != nil {
  2713. t.Errorf("unable to add user: %v", err)
  2714. }
  2715. client, err := getSftpClient(user, usePubKey)
  2716. if err != nil {
  2717. t.Errorf("unable to create sftp client: %v", err)
  2718. } else {
  2719. defer client.Close()
  2720. testFileName := "test_file.dat"
  2721. testFilePath := filepath.Join(homeBasePath, testFileName)
  2722. testFileSize := int64(65535)
  2723. err = createTestFile(testFilePath, testFileSize)
  2724. if err != nil {
  2725. t.Errorf("unable to create test file: %v", err)
  2726. }
  2727. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2728. if err != nil {
  2729. t.Errorf("file upload error: %v", err)
  2730. }
  2731. err = client.Remove(testFileName)
  2732. if err == nil {
  2733. t.Errorf("delete without permission should not succeed")
  2734. }
  2735. os.Remove(testFilePath)
  2736. }
  2737. _, err = httpd.RemoveUser(user, http.StatusOK)
  2738. if err != nil {
  2739. t.Errorf("unable to remove user: %v", err)
  2740. }
  2741. os.RemoveAll(user.GetHomeDir())
  2742. }
  2743. func TestPermRename(t *testing.T) {
  2744. usePubKey := false
  2745. u := getTestUser(usePubKey)
  2746. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2747. dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2748. dataprovider.PermChown, dataprovider.PermChtimes}
  2749. user, _, err := httpd.AddUser(u, http.StatusOK)
  2750. if err != nil {
  2751. t.Errorf("unable to add user: %v", err)
  2752. }
  2753. client, err := getSftpClient(user, usePubKey)
  2754. if err != nil {
  2755. t.Errorf("unable to create sftp client: %v", err)
  2756. } else {
  2757. defer client.Close()
  2758. testFileName := "test_file.dat"
  2759. testFilePath := filepath.Join(homeBasePath, testFileName)
  2760. testFileSize := int64(65535)
  2761. err = createTestFile(testFilePath, testFileSize)
  2762. if err != nil {
  2763. t.Errorf("unable to create test file: %v", err)
  2764. }
  2765. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2766. if err != nil {
  2767. t.Errorf("file upload error: %v", err)
  2768. }
  2769. err = client.Rename(testFileName, testFileName+".rename")
  2770. if err == nil {
  2771. t.Errorf("rename without permission should not succeed")
  2772. }
  2773. err = client.Remove(testFileName)
  2774. if err != nil {
  2775. t.Errorf("error removing uploaded file: %v", err)
  2776. }
  2777. os.Remove(testFilePath)
  2778. }
  2779. _, err = httpd.RemoveUser(user, http.StatusOK)
  2780. if err != nil {
  2781. t.Errorf("unable to remove user: %v", err)
  2782. }
  2783. os.RemoveAll(user.GetHomeDir())
  2784. }
  2785. func TestPermCreateDirs(t *testing.T) {
  2786. usePubKey := false
  2787. u := getTestUser(usePubKey)
  2788. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2789. dataprovider.PermRename, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite, dataprovider.PermChmod,
  2790. dataprovider.PermChown, dataprovider.PermChtimes}
  2791. user, _, err := httpd.AddUser(u, http.StatusOK)
  2792. if err != nil {
  2793. t.Errorf("unable to add user: %v", err)
  2794. }
  2795. client, err := getSftpClient(user, usePubKey)
  2796. if err != nil {
  2797. t.Errorf("unable to create sftp client: %v", err)
  2798. } else {
  2799. defer client.Close()
  2800. err = client.Mkdir("testdir")
  2801. if err == nil {
  2802. t.Errorf("mkdir without permission should not succeed")
  2803. }
  2804. }
  2805. _, err = httpd.RemoveUser(user, http.StatusOK)
  2806. if err != nil {
  2807. t.Errorf("unable to remove user: %v", err)
  2808. }
  2809. os.RemoveAll(user.GetHomeDir())
  2810. }
  2811. func TestPermSymlink(t *testing.T) {
  2812. usePubKey := false
  2813. u := getTestUser(usePubKey)
  2814. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2815. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermOverwrite, dataprovider.PermChmod, dataprovider.PermChown,
  2816. dataprovider.PermChtimes}
  2817. user, _, err := httpd.AddUser(u, http.StatusOK)
  2818. if err != nil {
  2819. t.Errorf("unable to add user: %v", err)
  2820. }
  2821. client, err := getSftpClient(user, usePubKey)
  2822. if err != nil {
  2823. t.Errorf("unable to create sftp client: %v", err)
  2824. } else {
  2825. defer client.Close()
  2826. testFileName := "test_file.dat"
  2827. testFilePath := filepath.Join(homeBasePath, testFileName)
  2828. testFileSize := int64(65535)
  2829. err = createTestFile(testFilePath, testFileSize)
  2830. if err != nil {
  2831. t.Errorf("unable to create test file: %v", err)
  2832. }
  2833. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2834. if err != nil {
  2835. t.Errorf("file upload error: %v", err)
  2836. }
  2837. err = client.Symlink(testFilePath, testFilePath+".symlink")
  2838. if err == nil {
  2839. t.Errorf("symlink without permission should not succeed")
  2840. }
  2841. err = client.Remove(testFileName)
  2842. if err != nil {
  2843. t.Errorf("error removing uploaded file: %v", err)
  2844. }
  2845. os.Remove(testFilePath)
  2846. }
  2847. _, err = httpd.RemoveUser(user, http.StatusOK)
  2848. if err != nil {
  2849. t.Errorf("unable to remove user: %v", err)
  2850. }
  2851. os.RemoveAll(user.GetHomeDir())
  2852. }
  2853. func TestPermChmod(t *testing.T) {
  2854. usePubKey := false
  2855. u := getTestUser(usePubKey)
  2856. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2857. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2858. dataprovider.PermChown, dataprovider.PermChtimes}
  2859. user, _, err := httpd.AddUser(u, http.StatusOK)
  2860. if err != nil {
  2861. t.Errorf("unable to add user: %v", err)
  2862. }
  2863. client, err := getSftpClient(user, usePubKey)
  2864. if err != nil {
  2865. t.Errorf("unable to create sftp client: %v", err)
  2866. } else {
  2867. defer client.Close()
  2868. testFileName := "test_file.dat"
  2869. testFilePath := filepath.Join(homeBasePath, testFileName)
  2870. testFileSize := int64(65535)
  2871. err = createTestFile(testFilePath, testFileSize)
  2872. if err != nil {
  2873. t.Errorf("unable to create test file: %v", err)
  2874. }
  2875. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2876. if err != nil {
  2877. t.Errorf("file upload error: %v", err)
  2878. }
  2879. err = client.Chmod(testFileName, 0666)
  2880. if err == nil {
  2881. t.Errorf("chmod without permission should not succeed")
  2882. }
  2883. err = client.Remove(testFileName)
  2884. if err != nil {
  2885. t.Errorf("error removing uploaded file: %v", err)
  2886. }
  2887. os.Remove(testFilePath)
  2888. }
  2889. _, err = httpd.RemoveUser(user, http.StatusOK)
  2890. if err != nil {
  2891. t.Errorf("unable to remove user: %v", err)
  2892. }
  2893. os.RemoveAll(user.GetHomeDir())
  2894. }
  2895. func TestPermChown(t *testing.T) {
  2896. usePubKey := false
  2897. u := getTestUser(usePubKey)
  2898. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2899. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2900. dataprovider.PermChmod, dataprovider.PermChtimes}
  2901. user, _, err := httpd.AddUser(u, http.StatusOK)
  2902. if err != nil {
  2903. t.Errorf("unable to add user: %v", err)
  2904. }
  2905. client, err := getSftpClient(user, usePubKey)
  2906. if err != nil {
  2907. t.Errorf("unable to create sftp client: %v", err)
  2908. } else {
  2909. defer client.Close()
  2910. testFileName := "test_file.dat"
  2911. testFilePath := filepath.Join(homeBasePath, testFileName)
  2912. testFileSize := int64(65535)
  2913. err = createTestFile(testFilePath, testFileSize)
  2914. if err != nil {
  2915. t.Errorf("unable to create test file: %v", err)
  2916. }
  2917. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2918. if err != nil {
  2919. t.Errorf("file upload error: %v", err)
  2920. }
  2921. err = client.Chown(testFileName, os.Getuid(), os.Getgid())
  2922. if err == nil {
  2923. t.Errorf("chown without permission should not succeed")
  2924. }
  2925. err = client.Remove(testFileName)
  2926. if err != nil {
  2927. t.Errorf("error removing uploaded file: %v", err)
  2928. }
  2929. os.Remove(testFilePath)
  2930. }
  2931. _, err = httpd.RemoveUser(user, http.StatusOK)
  2932. if err != nil {
  2933. t.Errorf("unable to remove user: %v", err)
  2934. }
  2935. os.RemoveAll(user.GetHomeDir())
  2936. }
  2937. func TestPermChtimes(t *testing.T) {
  2938. usePubKey := false
  2939. u := getTestUser(usePubKey)
  2940. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermDownload, dataprovider.PermUpload, dataprovider.PermDelete,
  2941. dataprovider.PermRename, dataprovider.PermCreateDirs, dataprovider.PermCreateSymlinks, dataprovider.PermOverwrite,
  2942. dataprovider.PermChmod, dataprovider.PermChown}
  2943. user, _, err := httpd.AddUser(u, http.StatusOK)
  2944. if err != nil {
  2945. t.Errorf("unable to add user: %v", err)
  2946. }
  2947. client, err := getSftpClient(user, usePubKey)
  2948. if err != nil {
  2949. t.Errorf("unable to create sftp client: %v", err)
  2950. } else {
  2951. defer client.Close()
  2952. testFileName := "test_file.dat"
  2953. testFilePath := filepath.Join(homeBasePath, testFileName)
  2954. testFileSize := int64(65535)
  2955. err = createTestFile(testFilePath, testFileSize)
  2956. if err != nil {
  2957. t.Errorf("unable to create test file: %v", err)
  2958. }
  2959. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  2960. if err != nil {
  2961. t.Errorf("file upload error: %v", err)
  2962. }
  2963. err = client.Chtimes(testFileName, time.Now(), time.Now())
  2964. if err == nil {
  2965. t.Errorf("chtimes without permission should not succeed")
  2966. }
  2967. err = client.Remove(testFileName)
  2968. if err != nil {
  2969. t.Errorf("error removing uploaded file: %v", err)
  2970. }
  2971. os.Remove(testFilePath)
  2972. }
  2973. _, err = httpd.RemoveUser(user, http.StatusOK)
  2974. if err != nil {
  2975. t.Errorf("unable to remove user: %v", err)
  2976. }
  2977. os.RemoveAll(user.GetHomeDir())
  2978. }
  2979. func TestSubDirsUploads(t *testing.T) {
  2980. usePubKey := true
  2981. u := getTestUser(usePubKey)
  2982. u.Permissions["/"] = []string{dataprovider.PermAny}
  2983. u.Permissions["/subdir"] = []string{dataprovider.PermChtimes, dataprovider.PermDownload}
  2984. user, _, err := httpd.AddUser(u, http.StatusOK)
  2985. if err != nil {
  2986. t.Errorf("unable to add user: %v", err)
  2987. }
  2988. client, err := getSftpClient(user, usePubKey)
  2989. if err != nil {
  2990. t.Errorf("unable to create sftp client: %v", err)
  2991. } else {
  2992. defer client.Close()
  2993. err = client.Mkdir("subdir")
  2994. if err != nil {
  2995. t.Errorf("unexpected mkdir error: %v", err)
  2996. }
  2997. testFileName := "test_file.dat"
  2998. testFileNameSub := "/subdir/test_file_dat"
  2999. testFilePath := filepath.Join(homeBasePath, testFileName)
  3000. testFileSize := int64(65535)
  3001. err = createTestFile(testFilePath, testFileSize)
  3002. if err != nil {
  3003. t.Errorf("unable to create test file: %v", err)
  3004. }
  3005. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3006. if err != nil {
  3007. t.Errorf("file upload error: %v", err)
  3008. }
  3009. err = sftpUploadFile(testFilePath, testFileNameSub, testFileSize, client)
  3010. if !strings.Contains(err.Error(), "Permission Denied") {
  3011. t.Errorf("unexpected upload error: %v", err)
  3012. }
  3013. err = client.Symlink(testFileName, testFileNameSub+".link")
  3014. if !strings.Contains(err.Error(), "Permission Denied") {
  3015. t.Errorf("unexpected upload error: %v", err)
  3016. }
  3017. err = client.Symlink(testFileName, testFileName+".link")
  3018. if err != nil {
  3019. t.Errorf("symlink error: %v", err)
  3020. }
  3021. err = client.Rename(testFileName, testFileNameSub+".rename")
  3022. if !strings.Contains(err.Error(), "Permission Denied") {
  3023. t.Errorf("unexpected rename error: %v", err)
  3024. }
  3025. err = client.Rename(testFileName, testFileName+".rename")
  3026. if err != nil {
  3027. t.Errorf("rename error: %v", err)
  3028. }
  3029. err = client.Remove(testFileNameSub)
  3030. if !strings.Contains(err.Error(), "Permission Denied") {
  3031. t.Errorf("unexpected upload error: %v", err)
  3032. }
  3033. err = client.Remove(testFileName + ".rename")
  3034. if err != nil {
  3035. t.Errorf("remove error: %v", err)
  3036. }
  3037. os.Remove(testFilePath)
  3038. }
  3039. httpd.RemoveUser(user, http.StatusOK)
  3040. os.RemoveAll(user.GetHomeDir())
  3041. }
  3042. func TestSubDirsOverwrite(t *testing.T) {
  3043. usePubKey := true
  3044. u := getTestUser(usePubKey)
  3045. u.Permissions["/"] = []string{dataprovider.PermAny}
  3046. u.Permissions["/subdir"] = []string{dataprovider.PermOverwrite, dataprovider.PermListItems}
  3047. user, _, err := httpd.AddUser(u, http.StatusOK)
  3048. if err != nil {
  3049. t.Errorf("unable to add user: %v", err)
  3050. }
  3051. client, err := getSftpClient(user, usePubKey)
  3052. if err != nil {
  3053. t.Errorf("unable to create sftp client: %v", err)
  3054. } else {
  3055. defer client.Close()
  3056. testFileName := "/subdir/test_file.dat"
  3057. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  3058. testFileSFTPPath := filepath.Join(u.GetHomeDir(), "subdir", "test_file.dat")
  3059. testFileSize := int64(65535)
  3060. err = createTestFile(testFilePath, testFileSize)
  3061. if err != nil {
  3062. t.Errorf("unable to create test file: %v", err)
  3063. }
  3064. err = createTestFile(testFileSFTPPath, 16384)
  3065. if err != nil {
  3066. t.Errorf("unable to create test file: %v", err)
  3067. }
  3068. err = sftpUploadFile(testFilePath, testFileName+".new", testFileSize, client)
  3069. if !strings.Contains(err.Error(), "Permission Denied") {
  3070. t.Errorf("unexpected upload error: %v", err)
  3071. }
  3072. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3073. if err != nil {
  3074. t.Errorf("unexpected overwrite error: %v", err)
  3075. }
  3076. os.Remove(testFilePath)
  3077. }
  3078. httpd.RemoveUser(user, http.StatusOK)
  3079. os.RemoveAll(user.GetHomeDir())
  3080. }
  3081. func TestSubDirsDownloads(t *testing.T) {
  3082. usePubKey := true
  3083. u := getTestUser(usePubKey)
  3084. u.Permissions["/"] = []string{dataprovider.PermAny}
  3085. u.Permissions["/subdir"] = []string{dataprovider.PermChmod, dataprovider.PermUpload, dataprovider.PermListItems}
  3086. user, _, err := httpd.AddUser(u, http.StatusOK)
  3087. if err != nil {
  3088. t.Errorf("unable to add user: %v", err)
  3089. }
  3090. client, err := getSftpClient(user, usePubKey)
  3091. if err != nil {
  3092. t.Errorf("unable to create sftp client: %v", err)
  3093. } else {
  3094. defer client.Close()
  3095. err = client.Mkdir("subdir")
  3096. if err != nil {
  3097. t.Errorf("unexpected mkdir error: %v", err)
  3098. }
  3099. testFileName := "/subdir/test_file.dat"
  3100. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  3101. testFileSize := int64(65535)
  3102. err = createTestFile(testFilePath, testFileSize)
  3103. if err != nil {
  3104. t.Errorf("unable to create test file: %v", err)
  3105. }
  3106. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3107. if err != nil {
  3108. t.Errorf("file upload error: %v", err)
  3109. }
  3110. localDownloadPath := filepath.Join(homeBasePath, "test_download.dat")
  3111. err = sftpDownloadFile(testFileName, localDownloadPath, testFileSize, client)
  3112. if !strings.Contains(err.Error(), "Permission Denied") {
  3113. t.Errorf("unexpected upload error: %v", err)
  3114. }
  3115. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3116. if !strings.Contains(err.Error(), "Permission Denied") {
  3117. t.Errorf("unexpected overwrite error: %v", err)
  3118. }
  3119. err = client.Chtimes(testFileName, time.Now(), time.Now())
  3120. if !strings.Contains(err.Error(), "Permission Denied") {
  3121. t.Errorf("unexpected chtimes error: %v", err)
  3122. }
  3123. err = client.Rename(testFileName, testFileName+".rename")
  3124. if !strings.Contains(err.Error(), "Permission Denied") {
  3125. t.Errorf("unexpected rename error: %v", err)
  3126. }
  3127. err = client.Symlink(testFileName, testFileName+".link")
  3128. if !strings.Contains(err.Error(), "Permission Denied") {
  3129. t.Errorf("unexpected symlink error: %v", err)
  3130. }
  3131. err = client.Remove(testFileName)
  3132. if !strings.Contains(err.Error(), "Permission Denied") {
  3133. t.Errorf("unexpected remove error: %v", err)
  3134. }
  3135. os.Remove(localDownloadPath)
  3136. os.Remove(testFilePath)
  3137. }
  3138. httpd.RemoveUser(user, http.StatusOK)
  3139. os.RemoveAll(user.GetHomeDir())
  3140. }
  3141. func TestPermsSubDirsSetstat(t *testing.T) {
  3142. // for setstat we check the parent dir permission if the requested path is a dir
  3143. // otherwise the path permission
  3144. usePubKey := true
  3145. u := getTestUser(usePubKey)
  3146. u.Permissions["/"] = []string{dataprovider.PermListItems, dataprovider.PermCreateDirs}
  3147. u.Permissions["/subdir"] = []string{dataprovider.PermAny}
  3148. user, _, err := httpd.AddUser(u, http.StatusOK)
  3149. if err != nil {
  3150. t.Errorf("unable to add user: %v", err)
  3151. }
  3152. client, err := getSftpClient(user, usePubKey)
  3153. if err != nil {
  3154. t.Errorf("unable to create sftp client: %v", err)
  3155. } else {
  3156. defer client.Close()
  3157. err = client.Mkdir("subdir")
  3158. if err != nil {
  3159. t.Errorf("unexpected mkdir error: %v", err)
  3160. }
  3161. testFileName := "/subdir/test_file.dat"
  3162. testFilePath := filepath.Join(homeBasePath, "test_file.dat")
  3163. testFileSize := int64(65535)
  3164. err = createTestFile(testFilePath, testFileSize)
  3165. if err != nil {
  3166. t.Errorf("unable to create test file: %v", err)
  3167. }
  3168. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3169. if err != nil {
  3170. t.Errorf("file upload error: %v", err)
  3171. }
  3172. err = client.Chtimes("/subdir/", time.Now(), time.Now())
  3173. if !strings.Contains(err.Error(), "Permission Denied") {
  3174. t.Errorf("unexpected chtimes error: %v", err)
  3175. }
  3176. err = client.Chtimes("subdir/", time.Now(), time.Now())
  3177. if !strings.Contains(err.Error(), "Permission Denied") {
  3178. t.Errorf("unexpected chtimes error: %v", err)
  3179. }
  3180. err = client.Chtimes(testFileName, time.Now(), time.Now())
  3181. if err != nil {
  3182. t.Errorf("unexpected chtimes error: %v", err)
  3183. }
  3184. os.Remove(testFilePath)
  3185. }
  3186. httpd.RemoveUser(user, http.StatusOK)
  3187. os.RemoveAll(user.GetHomeDir())
  3188. }
  3189. func TestPermsSubDirsCommands(t *testing.T) {
  3190. usePubKey := true
  3191. u := getTestUser(usePubKey)
  3192. u.Permissions["/"] = []string{dataprovider.PermAny}
  3193. u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  3194. user, _, err := httpd.AddUser(u, http.StatusOK)
  3195. if err != nil {
  3196. t.Errorf("unable to add user: %v", err)
  3197. }
  3198. client, err := getSftpClient(user, usePubKey)
  3199. if err != nil {
  3200. t.Errorf("unable to create sftp client: %v", err)
  3201. } else {
  3202. defer client.Close()
  3203. client.Mkdir("subdir")
  3204. acmodTime := time.Now()
  3205. err = client.Chtimes("/subdir", acmodTime, acmodTime)
  3206. if err != nil {
  3207. t.Errorf("unexpected chtimes error: %v", err)
  3208. }
  3209. _, err = client.Stat("/subdir")
  3210. if err != nil {
  3211. t.Errorf("unexpected stat error: %v", err)
  3212. }
  3213. _, err = client.ReadDir("/")
  3214. if err != nil {
  3215. t.Errorf("unexpected readdir error: %v", err)
  3216. }
  3217. _, err = client.ReadDir("/subdir")
  3218. if !strings.Contains(err.Error(), "Permission Denied") {
  3219. t.Errorf("unexpected error: %v", err)
  3220. }
  3221. err = client.RemoveDirectory("/subdir/dir")
  3222. if !strings.Contains(err.Error(), "Permission Denied") {
  3223. t.Errorf("unexpected error: %v", err)
  3224. }
  3225. err = client.Mkdir("/subdir/dir")
  3226. if !strings.Contains(err.Error(), "Permission Denied") {
  3227. t.Errorf("unexpected error: %v", err)
  3228. }
  3229. client.Mkdir("/otherdir")
  3230. err = client.Rename("/otherdir", "/subdir/otherdir")
  3231. if !strings.Contains(err.Error(), "Permission Denied") {
  3232. t.Errorf("unexpected error: %v", err)
  3233. }
  3234. err = client.Symlink("/otherdir", "/subdir/otherdir")
  3235. if !strings.Contains(err.Error(), "Permission Denied") {
  3236. t.Errorf("unexpected error: %v", err)
  3237. }
  3238. err = client.Symlink("/otherdir", "/otherdir_link")
  3239. if err != nil {
  3240. t.Errorf("unexpected rename dir error: %v", err)
  3241. }
  3242. err = client.Rename("/otherdir", "/otherdir1")
  3243. if err != nil {
  3244. t.Errorf("unexpected rename dir error: %v", err)
  3245. }
  3246. err = client.RemoveDirectory("/subdir")
  3247. if err != nil {
  3248. t.Errorf("unexpected remove dir error: %v", err)
  3249. }
  3250. }
  3251. httpd.RemoveUser(user, http.StatusOK)
  3252. os.RemoveAll(user.GetHomeDir())
  3253. }
  3254. func TestRootDirCommands(t *testing.T) {
  3255. usePubKey := true
  3256. u := getTestUser(usePubKey)
  3257. u.Permissions["/"] = []string{dataprovider.PermAny}
  3258. u.Permissions["/subdir"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  3259. user, _, err := httpd.AddUser(u, http.StatusOK)
  3260. if err != nil {
  3261. t.Errorf("unable to add user: %v", err)
  3262. }
  3263. client, err := getSftpClient(user, usePubKey)
  3264. if err != nil {
  3265. t.Errorf("unable to create sftp client: %v", err)
  3266. } else {
  3267. defer client.Close()
  3268. err = client.Rename("/", "rootdir")
  3269. if !strings.Contains(err.Error(), "Permission Denied") {
  3270. t.Errorf("unexpected error renaming root dir: %v", err)
  3271. }
  3272. err = client.Symlink("/", "rootdir")
  3273. if !strings.Contains(err.Error(), "Permission Denied") {
  3274. t.Errorf("unexpected error symlinking root dir: %v", err)
  3275. }
  3276. err = client.RemoveDirectory("/")
  3277. if !strings.Contains(err.Error(), "Permission Denied") {
  3278. t.Errorf("unexpected error removing root dir: %v", err)
  3279. }
  3280. }
  3281. httpd.RemoveUser(user, http.StatusOK)
  3282. os.RemoveAll(user.GetHomeDir())
  3283. }
  3284. func TestRelativePaths(t *testing.T) {
  3285. user := getTestUser(true)
  3286. var path, rel string
  3287. filesystems := []vfs.Fs{vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders)}
  3288. keyPrefix := strings.TrimPrefix(user.GetHomeDir(), "/") + "/"
  3289. s3config := vfs.S3FsConfig{
  3290. KeyPrefix: keyPrefix,
  3291. }
  3292. s3fs, _ := vfs.NewS3Fs("", user.GetHomeDir(), s3config)
  3293. gcsConfig := vfs.GCSFsConfig{
  3294. KeyPrefix: keyPrefix,
  3295. }
  3296. gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig)
  3297. if runtime.GOOS != "windows" {
  3298. filesystems = append(filesystems, s3fs, gcsfs)
  3299. }
  3300. for _, fs := range filesystems {
  3301. path = filepath.Join(user.HomeDir, "/")
  3302. rel = fs.GetRelativePath(path)
  3303. if rel != "/" {
  3304. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3305. }
  3306. path = filepath.Join(user.HomeDir, "//")
  3307. rel = fs.GetRelativePath(path)
  3308. if rel != "/" {
  3309. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3310. }
  3311. path = filepath.Join(user.HomeDir, "../..")
  3312. rel = fs.GetRelativePath(path)
  3313. if rel != "/" {
  3314. t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name())
  3315. }
  3316. path = filepath.Join(user.HomeDir, "../../../../../")
  3317. rel = fs.GetRelativePath(path)
  3318. if rel != "/" {
  3319. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3320. }
  3321. path = filepath.Join(user.HomeDir, "/..")
  3322. rel = fs.GetRelativePath(path)
  3323. if rel != "/" {
  3324. t.Errorf("Unexpected relative path: %v path: %v fs: %v", rel, path, fs.Name())
  3325. }
  3326. path = filepath.Join(user.HomeDir, "/../../../..")
  3327. rel = fs.GetRelativePath(path)
  3328. if rel != "/" {
  3329. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3330. }
  3331. path = filepath.Join(user.HomeDir, "")
  3332. rel = fs.GetRelativePath(path)
  3333. if rel != "/" {
  3334. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3335. }
  3336. path = filepath.Join(user.HomeDir, ".")
  3337. rel = fs.GetRelativePath(path)
  3338. if rel != "/" {
  3339. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3340. }
  3341. path = filepath.Join(user.HomeDir, "somedir")
  3342. rel = fs.GetRelativePath(path)
  3343. if rel != "/somedir" {
  3344. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3345. }
  3346. path = filepath.Join(user.HomeDir, "/somedir/subdir")
  3347. rel = fs.GetRelativePath(path)
  3348. if rel != "/somedir/subdir" {
  3349. t.Errorf("Unexpected relative path: %v fs: %v", rel, fs.Name())
  3350. }
  3351. }
  3352. }
  3353. func TestResolvePaths(t *testing.T) {
  3354. user := getTestUser(true)
  3355. var path, resolved string
  3356. var err error
  3357. filesystems := []vfs.Fs{vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders)}
  3358. keyPrefix := strings.TrimPrefix(user.GetHomeDir(), "/") + "/"
  3359. s3config := vfs.S3FsConfig{
  3360. KeyPrefix: keyPrefix,
  3361. }
  3362. os.MkdirAll(user.GetHomeDir(), 0777)
  3363. s3fs, _ := vfs.NewS3Fs("", user.GetHomeDir(), s3config)
  3364. gcsConfig := vfs.GCSFsConfig{
  3365. KeyPrefix: keyPrefix,
  3366. }
  3367. gcsfs, _ := vfs.NewGCSFs("", user.GetHomeDir(), gcsConfig)
  3368. if runtime.GOOS != "windows" {
  3369. filesystems = append(filesystems, s3fs, gcsfs)
  3370. }
  3371. for _, fs := range filesystems {
  3372. path = "/"
  3373. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3374. if resolved != fs.Join(user.GetHomeDir(), "/") {
  3375. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3376. }
  3377. path = "."
  3378. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3379. if resolved != fs.Join(user.GetHomeDir(), "/") {
  3380. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3381. }
  3382. path = "test/sub"
  3383. resolved, _ = fs.ResolvePath(filepath.ToSlash(path))
  3384. if resolved != fs.Join(user.GetHomeDir(), "/test/sub") {
  3385. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3386. }
  3387. path = "../test/sub"
  3388. resolved, err = fs.ResolvePath(filepath.ToSlash(path))
  3389. if vfs.IsLocalOsFs(fs) {
  3390. if err == nil {
  3391. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3392. }
  3393. } else {
  3394. if resolved != fs.Join(user.GetHomeDir(), "/test/sub") && err == nil {
  3395. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3396. }
  3397. }
  3398. path = "../../../test/../sub"
  3399. resolved, err = fs.ResolvePath(filepath.ToSlash(path))
  3400. if vfs.IsLocalOsFs(fs) {
  3401. if err == nil {
  3402. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3403. }
  3404. } else {
  3405. if resolved != fs.Join(user.GetHomeDir(), "/sub") && err == nil {
  3406. t.Errorf("Unexpected resolved path: %v for: %v, fs: %v", resolved, path, fs.Name())
  3407. }
  3408. }
  3409. }
  3410. os.RemoveAll(user.GetHomeDir())
  3411. }
  3412. func TestVirtualRelativePaths(t *testing.T) {
  3413. user := getTestUser(true)
  3414. mappedPath := filepath.Join(os.TempDir(), "vdir")
  3415. vdirPath := "/vdir"
  3416. user.VirtualFolders = append(user.VirtualFolders, vfs.VirtualFolder{
  3417. VirtualPath: vdirPath,
  3418. MappedPath: mappedPath,
  3419. })
  3420. os.MkdirAll(mappedPath, 0777)
  3421. fs := vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders)
  3422. rel := fs.GetRelativePath(mappedPath)
  3423. if rel != vdirPath {
  3424. t.Errorf("Unexpected relative path: %v", rel)
  3425. }
  3426. rel = fs.GetRelativePath(filepath.Join(mappedPath, ".."))
  3427. if rel != "/" {
  3428. t.Errorf("Unexpected relative path: %v", rel)
  3429. }
  3430. // path outside home and virtual dir
  3431. rel = fs.GetRelativePath(filepath.Join(mappedPath, "../vdir1"))
  3432. if rel != "/" {
  3433. t.Errorf("Unexpected relative path: %v", rel)
  3434. }
  3435. rel = fs.GetRelativePath(filepath.Join(mappedPath, "../vdir/file.txt"))
  3436. if rel != "/vdir/file.txt" {
  3437. t.Errorf("Unexpected relative path: %v", rel)
  3438. }
  3439. rel = fs.GetRelativePath(filepath.Join(user.HomeDir, "vdir1/file.txt"))
  3440. if rel != "/vdir1/file.txt" {
  3441. t.Errorf("Unexpected relative path: %v", rel)
  3442. }
  3443. }
  3444. func TestResolveVirtualPaths(t *testing.T) {
  3445. user := getTestUser(true)
  3446. mappedPath := filepath.Join(os.TempDir(), "vdir")
  3447. vdirPath := "/vdir"
  3448. user.VirtualFolders = append(user.VirtualFolders, vfs.VirtualFolder{
  3449. VirtualPath: vdirPath,
  3450. MappedPath: mappedPath,
  3451. })
  3452. os.MkdirAll(mappedPath, 0777)
  3453. fs := vfs.NewOsFs("", user.GetHomeDir(), user.VirtualFolders)
  3454. osFs := fs.(*vfs.OsFs)
  3455. b, f := osFs.GetFsPaths("/vdir/a.txt")
  3456. if b != mappedPath {
  3457. t.Errorf("unexpected base path: %#v expected: %#v", b, mappedPath)
  3458. }
  3459. if f != filepath.Join(mappedPath, "a.txt") {
  3460. t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(mappedPath, "a.txt"))
  3461. }
  3462. b, f = osFs.GetFsPaths("/vdir/sub with space & spécial chars/a.txt")
  3463. if b != mappedPath {
  3464. t.Errorf("unexpected base path: %#v expected: %#v", b, mappedPath)
  3465. }
  3466. if f != filepath.Join(mappedPath, "sub with space & spécial chars/a.txt") {
  3467. t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(mappedPath, "sub with space & spécial chars/a.txt"))
  3468. }
  3469. b, f = osFs.GetFsPaths("/vdir/../a.txt")
  3470. if b != user.GetHomeDir() {
  3471. t.Errorf("unexpected base path: %#v expected: %#v", b, user.GetHomeDir())
  3472. }
  3473. if f != filepath.Join(user.GetHomeDir(), "a.txt") {
  3474. t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(user.GetHomeDir(), "a.txt"))
  3475. }
  3476. b, f = osFs.GetFsPaths("/vdir1/a.txt")
  3477. if b != user.GetHomeDir() {
  3478. t.Errorf("unexpected base path: %#v expected: %#v", b, user.GetHomeDir())
  3479. }
  3480. if f != filepath.Join(user.GetHomeDir(), "/vdir1/a.txt") {
  3481. t.Errorf("unexpected fs path: %#v expected: %#v", f, filepath.Join(user.GetHomeDir(), "/vdir1/a.txt"))
  3482. }
  3483. }
  3484. func TestUserPerms(t *testing.T) {
  3485. user := getTestUser(true)
  3486. user.Permissions = make(map[string][]string)
  3487. user.Permissions["/"] = []string{dataprovider.PermListItems}
  3488. user.Permissions["/p"] = []string{dataprovider.PermDelete}
  3489. user.Permissions["/p/1"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  3490. user.Permissions["/p/2"] = []string{dataprovider.PermCreateDirs}
  3491. user.Permissions["/p/3"] = []string{dataprovider.PermChmod}
  3492. user.Permissions["/p/3/4"] = []string{dataprovider.PermChtimes}
  3493. user.Permissions["/tmp"] = []string{dataprovider.PermRename}
  3494. if !user.HasPerm(dataprovider.PermListItems, "/") {
  3495. t.Error("expected permission not found")
  3496. }
  3497. if !user.HasPerm(dataprovider.PermListItems, ".") {
  3498. t.Error("expected permission not found")
  3499. }
  3500. if !user.HasPerm(dataprovider.PermListItems, "") {
  3501. t.Error("expected permission not found")
  3502. }
  3503. if !user.HasPerm(dataprovider.PermListItems, "../") {
  3504. t.Error("expected permission not found")
  3505. }
  3506. // path p and /p are the same
  3507. if !user.HasPerm(dataprovider.PermDelete, "/p") {
  3508. t.Error("expected permission not found")
  3509. }
  3510. if !user.HasPerm(dataprovider.PermDownload, "/p/1") {
  3511. t.Error("expected permission not found")
  3512. }
  3513. if !user.HasPerm(dataprovider.PermCreateDirs, "p/2") {
  3514. t.Error("expected permission not found")
  3515. }
  3516. if !user.HasPerm(dataprovider.PermChmod, "/p/3") {
  3517. t.Error("expected permission not found")
  3518. }
  3519. if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/") {
  3520. t.Error("expected permission not found")
  3521. }
  3522. if !user.HasPerm(dataprovider.PermChtimes, "p/3/4/../4") {
  3523. t.Error("expected permission not found")
  3524. }
  3525. // undefined paths have permissions of the nearest path
  3526. if !user.HasPerm(dataprovider.PermListItems, "/p34") {
  3527. t.Error("expected permission not found")
  3528. }
  3529. if !user.HasPerm(dataprovider.PermListItems, "/p34/p1/file.dat") {
  3530. t.Error("expected permission not found")
  3531. }
  3532. if !user.HasPerm(dataprovider.PermChtimes, "/p/3/4/5/6") {
  3533. t.Error("expected permission not found")
  3534. }
  3535. if !user.HasPerm(dataprovider.PermDownload, "/p/1/test/file.dat") {
  3536. t.Error("expected permission not found")
  3537. }
  3538. }
  3539. func TestFilterFileExtensions(t *testing.T) {
  3540. user := getTestUser(true)
  3541. extension := dataprovider.ExtensionsFilter{
  3542. Path: "/test",
  3543. AllowedExtensions: []string{".jpg", ".png"},
  3544. DeniedExtensions: []string{".pdf"},
  3545. }
  3546. filters := dataprovider.UserFilters{
  3547. FileExtensions: []dataprovider.ExtensionsFilter{extension},
  3548. }
  3549. user.Filters = filters
  3550. if !user.IsFileAllowed("/test/test.jPg") {
  3551. t.Error("this file must be allowed")
  3552. }
  3553. if user.IsFileAllowed("/test/test.pdf") {
  3554. t.Error("this file must be denied")
  3555. }
  3556. if !user.IsFileAllowed("/test.pDf") {
  3557. t.Error("this file must be allowed")
  3558. }
  3559. filters.FileExtensions = append(filters.FileExtensions, dataprovider.ExtensionsFilter{
  3560. Path: "/",
  3561. AllowedExtensions: []string{".zip", ".rar", ".pdf"},
  3562. DeniedExtensions: []string{".gz"},
  3563. })
  3564. user.Filters = filters
  3565. if user.IsFileAllowed("/test1/test.gz") {
  3566. t.Error("this file must be denied")
  3567. }
  3568. if !user.IsFileAllowed("/test1/test.zip") {
  3569. t.Error("this file must be allowed")
  3570. }
  3571. if user.IsFileAllowed("/test/sub/test.pdf") {
  3572. t.Error("this file must be denied")
  3573. }
  3574. if user.IsFileAllowed("/test1/test.png") {
  3575. t.Error("this file must be denied")
  3576. }
  3577. filters.FileExtensions = append(filters.FileExtensions, dataprovider.ExtensionsFilter{
  3578. Path: "/test/sub",
  3579. DeniedExtensions: []string{".tar"},
  3580. })
  3581. user.Filters = filters
  3582. if user.IsFileAllowed("/test/sub/sub/test.tar") {
  3583. t.Error("this file must be denied")
  3584. }
  3585. if !user.IsFileAllowed("/test/sub/test.gz") {
  3586. t.Error("this file must be allowed")
  3587. }
  3588. if user.IsFileAllowed("/test/test.zip") {
  3589. t.Error("this file must be denied")
  3590. }
  3591. }
  3592. func TestUserEmptySubDirPerms(t *testing.T) {
  3593. user := getTestUser(true)
  3594. user.Permissions = make(map[string][]string)
  3595. user.Permissions["/emptyperms"] = []string{}
  3596. for _, p := range dataprovider.ValidPerms {
  3597. if user.HasPerm(p, "/emptyperms") {
  3598. t.Errorf("unexpected permission %#v for dir /emptyperms", p)
  3599. }
  3600. }
  3601. }
  3602. func TestUserFiltersIPMaskConditions(t *testing.T) {
  3603. user := getTestUser(true)
  3604. // with no filter login must be allowed even if the remoteIP is invalid
  3605. if !user.IsLoginFromAddrAllowed("192.168.1.5") {
  3606. t.Error("unexpected login denied")
  3607. }
  3608. if !user.IsLoginFromAddrAllowed("invalid") {
  3609. t.Error("unexpected login denied")
  3610. }
  3611. user.Filters.DeniedIP = append(user.Filters.DeniedIP, "192.168.1.0/24")
  3612. if user.IsLoginFromAddrAllowed("192.168.1.5") {
  3613. t.Error("unexpected login allowed")
  3614. }
  3615. if !user.IsLoginFromAddrAllowed("192.168.2.6") {
  3616. t.Error("unexpected login denied")
  3617. }
  3618. user.Filters.AllowedIP = append(user.Filters.AllowedIP, "192.168.1.5/32")
  3619. // if the same ip/mask is both denied and allowed then login must be denied
  3620. if user.IsLoginFromAddrAllowed("192.168.1.5") {
  3621. t.Error("unexpected login allowed")
  3622. }
  3623. if user.IsLoginFromAddrAllowed("192.168.3.6") {
  3624. t.Error("unexpected login allowed")
  3625. }
  3626. user.Filters.DeniedIP = []string{}
  3627. if !user.IsLoginFromAddrAllowed("192.168.1.5") {
  3628. t.Error("unexpected login denied")
  3629. }
  3630. if user.IsLoginFromAddrAllowed("192.168.1.6") {
  3631. t.Error("unexpected login allowed")
  3632. }
  3633. user.Filters.DeniedIP = []string{"192.168.0.0/16", "172.16.0.0/16"}
  3634. user.Filters.AllowedIP = []string{}
  3635. if user.IsLoginFromAddrAllowed("192.168.5.255") {
  3636. t.Error("unexpected login allowed")
  3637. }
  3638. if user.IsLoginFromAddrAllowed("172.16.1.2") {
  3639. t.Error("unexpected login allowed")
  3640. }
  3641. if !user.IsLoginFromAddrAllowed("172.18.2.1") {
  3642. t.Error("unexpected login denied")
  3643. }
  3644. user.Filters.AllowedIP = []string{"10.4.4.0/24"}
  3645. if user.IsLoginFromAddrAllowed("10.5.4.2") {
  3646. t.Error("unexpected login allowed")
  3647. }
  3648. if !user.IsLoginFromAddrAllowed("10.4.4.2") {
  3649. t.Error("unexpected login denied")
  3650. }
  3651. if !user.IsLoginFromAddrAllowed("invalid") {
  3652. t.Error("unexpected login denied")
  3653. }
  3654. }
  3655. func TestSSHCommands(t *testing.T) {
  3656. usePubKey := false
  3657. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3658. if err != nil {
  3659. t.Errorf("unable to add user: %v", err)
  3660. }
  3661. _, err = runSSHCommand("ls", user, usePubKey)
  3662. if err == nil {
  3663. t.Errorf("unsupported ssh command must fail")
  3664. }
  3665. _, err = runSSHCommand("cd", user, usePubKey)
  3666. if err != nil {
  3667. t.Errorf("unexpected error for ssh cd command: %v", err)
  3668. }
  3669. out, err := runSSHCommand("pwd", user, usePubKey)
  3670. if err != nil {
  3671. t.Errorf("unexpected error: %v", err)
  3672. t.Fail()
  3673. }
  3674. if string(out) != "/\n" {
  3675. t.Errorf("invalid response for ssh pwd command: %v", string(out))
  3676. }
  3677. out, err = runSSHCommand("md5sum", user, usePubKey)
  3678. if err != nil {
  3679. t.Errorf("unexpected error: %v", err)
  3680. t.Fail()
  3681. }
  3682. // echo -n '' | md5sum
  3683. if !strings.Contains(string(out), "d41d8cd98f00b204e9800998ecf8427e") {
  3684. t.Errorf("invalid md5sum: %v", string(out))
  3685. }
  3686. out, err = runSSHCommand("sha1sum", user, usePubKey)
  3687. if err != nil {
  3688. t.Errorf("unexpected error: %v", err)
  3689. t.Fail()
  3690. }
  3691. if !strings.Contains(string(out), "da39a3ee5e6b4b0d3255bfef95601890afd80709") {
  3692. t.Errorf("invalid sha1sum: %v", string(out))
  3693. }
  3694. out, err = runSSHCommand("sha256sum", user, usePubKey)
  3695. if err != nil {
  3696. t.Errorf("unexpected error: %v", err)
  3697. t.Fail()
  3698. }
  3699. if !strings.Contains(string(out), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") {
  3700. t.Errorf("invalid sha256sum: %v", string(out))
  3701. }
  3702. out, err = runSSHCommand("sha384sum", user, usePubKey)
  3703. if err != nil {
  3704. t.Errorf("unexpected error: %v", err)
  3705. t.Fail()
  3706. }
  3707. if !strings.Contains(string(out), "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b") {
  3708. t.Errorf("invalid sha384sum: %v", string(out))
  3709. }
  3710. _, err = httpd.RemoveUser(user, http.StatusOK)
  3711. if err != nil {
  3712. t.Errorf("unable to remove user: %v", err)
  3713. }
  3714. }
  3715. func TestSSHFileHash(t *testing.T) {
  3716. usePubKey := true
  3717. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  3718. if err != nil {
  3719. t.Errorf("unable to add user: %v", err)
  3720. }
  3721. client, err := getSftpClient(user, usePubKey)
  3722. if err != nil {
  3723. t.Errorf("unable to create sftp client: %v", err)
  3724. } else {
  3725. defer client.Close()
  3726. testFileName := "test_file.dat"
  3727. testFilePath := filepath.Join(homeBasePath, testFileName)
  3728. testFileSize := int64(65535)
  3729. err = createTestFile(testFilePath, testFileSize)
  3730. if err != nil {
  3731. t.Errorf("unable to create test file: %v", err)
  3732. }
  3733. err = sftpUploadFile(testFilePath, testFileName, testFileSize, client)
  3734. if err != nil {
  3735. t.Errorf("file upload error: %v", err)
  3736. }
  3737. user.Permissions = make(map[string][]string)
  3738. user.Permissions["/"] = []string{dataprovider.PermUpload}
  3739. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3740. if err != nil {
  3741. t.Errorf("unable to update user: %v", err)
  3742. }
  3743. _, err = runSSHCommand("sha512sum "+testFileName, user, usePubKey)
  3744. if err == nil {
  3745. t.Errorf("hash command with no list permission must fail")
  3746. }
  3747. user.Permissions["/"] = []string{dataprovider.PermAny}
  3748. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3749. if err != nil {
  3750. t.Errorf("unable to update user: %v", err)
  3751. }
  3752. initialHash, err := computeHashForFile(sha512.New(), testFilePath)
  3753. if err != nil {
  3754. t.Errorf("error computing file hash: %v", err)
  3755. }
  3756. out, err := runSSHCommand("sha512sum "+testFileName, user, usePubKey)
  3757. if err != nil {
  3758. t.Errorf("unexpected error: %v", err)
  3759. t.Fail()
  3760. }
  3761. if !strings.Contains(string(out), initialHash) {
  3762. t.Errorf("invalid sha512sum: %v", string(out))
  3763. }
  3764. _, err = runSSHCommand("sha512sum invalid_path", user, usePubKey)
  3765. if err == nil {
  3766. t.Errorf("hash for an invalid path must fail")
  3767. }
  3768. os.Remove(testFilePath)
  3769. }
  3770. _, err = httpd.RemoveUser(user, http.StatusOK)
  3771. if err != nil {
  3772. t.Errorf("unable to remove user: %v", err)
  3773. }
  3774. os.RemoveAll(user.GetHomeDir())
  3775. }
  3776. func TestBasicGitCommands(t *testing.T) {
  3777. if len(gitPath) == 0 || len(sshPath) == 0 {
  3778. t.Skip("git and/or ssh command not found, unable to execute this test")
  3779. }
  3780. usePubKey := true
  3781. u := getTestUser(usePubKey)
  3782. user, _, err := httpd.AddUser(u, http.StatusOK)
  3783. if err != nil {
  3784. t.Errorf("unable to add user: %v", err)
  3785. }
  3786. repoName := "testrepo"
  3787. clonePath := filepath.Join(homeBasePath, repoName)
  3788. os.RemoveAll(user.GetHomeDir())
  3789. os.RemoveAll(filepath.Join(homeBasePath, repoName))
  3790. out, err := initGitRepo(filepath.Join(user.HomeDir, repoName))
  3791. if err != nil {
  3792. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3793. }
  3794. out, err = cloneGitRepo(homeBasePath, "/"+repoName, user.Username)
  3795. if err != nil {
  3796. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3797. }
  3798. out, err = addFileToGitRepo(clonePath, 128)
  3799. if err != nil {
  3800. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3801. }
  3802. user.QuotaFiles = 100000
  3803. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3804. if err != nil {
  3805. t.Errorf("unable to update user: %v", err)
  3806. }
  3807. out, err = pushToGitRepo(clonePath)
  3808. if err != nil {
  3809. t.Errorf("unexpected error: %v out: %v", err, string(out))
  3810. printLatestLogs(10)
  3811. }
  3812. err = waitQuotaScans()
  3813. if err != nil {
  3814. t.Errorf("error waiting for active quota scans: %v", err)
  3815. }
  3816. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3817. if err != nil {
  3818. t.Errorf("unable to get user: %v", err)
  3819. }
  3820. user.QuotaSize = user.UsedQuotaSize - 1
  3821. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  3822. if err != nil {
  3823. t.Errorf("unable to update user: %v", err)
  3824. }
  3825. out, err = pushToGitRepo(clonePath)
  3826. if err == nil {
  3827. t.Errorf("git push must fail if quota is exceeded, out: %v", string(out))
  3828. }
  3829. _, err = httpd.RemoveUser(user, http.StatusOK)
  3830. if err != nil {
  3831. t.Errorf("unable to remove user: %v", err)
  3832. }
  3833. os.RemoveAll(user.GetHomeDir())
  3834. os.RemoveAll(clonePath)
  3835. }
  3836. func TestGitErrors(t *testing.T) {
  3837. if len(gitPath) == 0 || len(sshPath) == 0 {
  3838. t.Skip("git and/or ssh command not found, unable to execute this test")
  3839. }
  3840. usePubKey := true
  3841. u := getTestUser(usePubKey)
  3842. user, _, err := httpd.AddUser(u, http.StatusOK)
  3843. if err != nil {
  3844. t.Errorf("unable to add user: %v", err)
  3845. }
  3846. repoName := "testrepo"
  3847. clonePath := filepath.Join(homeBasePath, repoName)
  3848. os.RemoveAll(user.GetHomeDir())
  3849. os.RemoveAll(filepath.Join(homeBasePath, repoName))
  3850. out, err := cloneGitRepo(homeBasePath, "/"+repoName, user.Username)
  3851. if err == nil {
  3852. t.Errorf("cloning a missing repo must fail, out: %v", string(out))
  3853. }
  3854. _, err = httpd.RemoveUser(user, http.StatusOK)
  3855. if err != nil {
  3856. t.Errorf("unable to remove user: %v", err)
  3857. }
  3858. os.RemoveAll(user.GetHomeDir())
  3859. os.RemoveAll(clonePath)
  3860. }
  3861. // Start SCP tests
  3862. func TestSCPBasicHandling(t *testing.T) {
  3863. if len(scpPath) == 0 {
  3864. t.Skip("scp command not found, unable to execute this test")
  3865. }
  3866. usePubKey := true
  3867. u := getTestUser(usePubKey)
  3868. u.QuotaSize = 6553600
  3869. user, _, err := httpd.AddUser(u, http.StatusOK)
  3870. if err != nil {
  3871. t.Errorf("unable to add user: %v", err)
  3872. }
  3873. testFileName := "test_file.dat"
  3874. testFilePath := filepath.Join(homeBasePath, testFileName)
  3875. testFileSize := int64(131074)
  3876. expectedQuotaSize := user.UsedQuotaSize + testFileSize
  3877. expectedQuotaFiles := user.UsedQuotaFiles + 1
  3878. err = createTestFile(testFilePath, testFileSize)
  3879. if err != nil {
  3880. t.Errorf("unable to create test file: %v", err)
  3881. }
  3882. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  3883. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3884. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3885. // test to download a missing file
  3886. err = scpDownload(localPath, remoteDownPath, false, false)
  3887. if err == nil {
  3888. t.Errorf("downloading a missing file via scp must fail")
  3889. }
  3890. err = scpUpload(testFilePath, remoteUpPath, false, false)
  3891. if err != nil {
  3892. t.Errorf("error uploading file via scp: %v", err)
  3893. }
  3894. err = scpDownload(localPath, remoteDownPath, false, false)
  3895. if err != nil {
  3896. t.Errorf("error downloading file via scp: %v", err)
  3897. }
  3898. fi, err := os.Stat(localPath)
  3899. if err != nil {
  3900. t.Errorf("stat for the downloaded file must succeed")
  3901. } else {
  3902. if fi.Size() != testFileSize {
  3903. t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v",
  3904. fi.Size(), testFileSize)
  3905. }
  3906. }
  3907. os.Remove(localPath)
  3908. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3909. if err != nil {
  3910. t.Errorf("error getting user: %v", err)
  3911. }
  3912. if expectedQuotaFiles != user.UsedQuotaFiles {
  3913. t.Errorf("quota files does not match, expected: %v, actual: %v", expectedQuotaFiles, user.UsedQuotaFiles)
  3914. }
  3915. if expectedQuotaSize != user.UsedQuotaSize {
  3916. t.Errorf("quota size does not match, expected: %v, actual: %v", expectedQuotaSize, user.UsedQuotaSize)
  3917. }
  3918. err = os.RemoveAll(user.GetHomeDir())
  3919. if err != nil {
  3920. t.Errorf("error removing uploaded files")
  3921. }
  3922. _, err = httpd.RemoveUser(user, http.StatusOK)
  3923. if err != nil {
  3924. t.Errorf("unable to remove user: %v", err)
  3925. }
  3926. os.Remove(testFilePath)
  3927. }
  3928. func TestSCPUploadFileOverwrite(t *testing.T) {
  3929. if len(scpPath) == 0 {
  3930. t.Skip("scp command not found, unable to execute this test")
  3931. }
  3932. usePubKey := true
  3933. u := getTestUser(usePubKey)
  3934. u.QuotaFiles = 1000
  3935. user, _, err := httpd.AddUser(u, http.StatusOK)
  3936. if err != nil {
  3937. t.Errorf("unable to add user: %v", err)
  3938. }
  3939. os.RemoveAll(user.GetHomeDir())
  3940. testFileName := "test_file.dat"
  3941. testFilePath := filepath.Join(homeBasePath, testFileName)
  3942. testFileSize := int64(32760)
  3943. err = createTestFile(testFilePath, testFileSize)
  3944. if err != nil {
  3945. t.Errorf("unable to create test file: %v", err)
  3946. }
  3947. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3948. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3949. if err != nil {
  3950. t.Errorf("error uploading file via scp: %v", err)
  3951. }
  3952. // test a new upload that must overwrite the existing file
  3953. err = scpUpload(testFilePath, remoteUpPath, true, false)
  3954. if err != nil {
  3955. t.Errorf("error uploading existing file via scp: %v", err)
  3956. }
  3957. user, _, err = httpd.GetUserByID(user.ID, http.StatusOK)
  3958. if err != nil {
  3959. t.Errorf("error getting user: %v", err)
  3960. }
  3961. if user.UsedQuotaSize != testFileSize || user.UsedQuotaFiles != 1 {
  3962. t.Errorf("update quota error on file overwrite, actual size: %v, expected: %v actual files: %v, expected: 1",
  3963. user.UsedQuotaSize, testFileSize, user.UsedQuotaFiles)
  3964. }
  3965. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  3966. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  3967. err = scpDownload(localPath, remoteDownPath, false, false)
  3968. if err != nil {
  3969. t.Errorf("error downloading file via scp: %v", err)
  3970. }
  3971. fi, err := os.Stat(localPath)
  3972. if err != nil {
  3973. t.Errorf("stat for the downloaded file must succeed")
  3974. } else {
  3975. if fi.Size() != testFileSize {
  3976. t.Errorf("size of the file downloaded via SCP does not match the expected one: %v/%v",
  3977. fi.Size(), testFileSize)
  3978. }
  3979. }
  3980. os.Remove(localPath)
  3981. os.Remove(testFilePath)
  3982. err = os.RemoveAll(user.GetHomeDir())
  3983. if err != nil {
  3984. t.Errorf("error removing uploaded files")
  3985. }
  3986. _, err = httpd.RemoveUser(user, http.StatusOK)
  3987. if err != nil {
  3988. t.Errorf("unable to remove user: %v", err)
  3989. }
  3990. }
  3991. func TestSCPRecursive(t *testing.T) {
  3992. if len(scpPath) == 0 {
  3993. t.Skip("scp command not found, unable to execute this test")
  3994. }
  3995. usePubKey := true
  3996. u := getTestUser(usePubKey)
  3997. user, _, err := httpd.AddUser(u, http.StatusOK)
  3998. if err != nil {
  3999. t.Errorf("unable to add user: %v", err)
  4000. }
  4001. testFileName := "test_file.dat"
  4002. testBaseDirName := "test_dir"
  4003. testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName)
  4004. testBaseDirDownName := "test_dir_down"
  4005. testBaseDirDownPath := filepath.Join(homeBasePath, testBaseDirDownName)
  4006. testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName)
  4007. testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName)
  4008. testFileSize := int64(131074)
  4009. createTestFile(testFilePath, testFileSize)
  4010. createTestFile(testFilePath1, testFileSize)
  4011. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testBaseDirName))
  4012. // test to download a missing dir
  4013. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true)
  4014. if err == nil {
  4015. t.Errorf("downloading a missing dir via scp must fail")
  4016. }
  4017. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4018. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  4019. if err != nil {
  4020. t.Errorf("error uploading dir via scp: %v", err)
  4021. }
  4022. // overwrite existing dir
  4023. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  4024. if err != nil {
  4025. t.Errorf("error uploading dir via scp: %v", err)
  4026. }
  4027. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true)
  4028. if err != nil {
  4029. t.Errorf("error downloading dir via scp: %v", err)
  4030. }
  4031. // test download without passing -r
  4032. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, false)
  4033. if err == nil {
  4034. t.Errorf("recursive download without -r must fail")
  4035. }
  4036. fi, err := os.Stat(filepath.Join(testBaseDirDownPath, testFileName))
  4037. if err != nil {
  4038. t.Errorf("error downloading file using scp recursive: %v", err)
  4039. } else {
  4040. if fi.Size() != testFileSize {
  4041. t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize)
  4042. }
  4043. }
  4044. fi, err = os.Stat(filepath.Join(testBaseDirDownPath, testBaseDirName, testFileName))
  4045. if err != nil {
  4046. t.Errorf("error downloading file using scp recursive: %v", err)
  4047. } else {
  4048. if fi.Size() != testFileSize {
  4049. t.Errorf("size for file downloaded using recursive scp does not match, actual: %v, expected: %v", fi.Size(), testFileSize)
  4050. }
  4051. }
  4052. // upload to a non existent dir
  4053. remoteUpPath = fmt.Sprintf("%[email protected]:%v", user.Username, "/non_existent_dir")
  4054. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  4055. if err == nil {
  4056. t.Errorf("uploading via scp to a non existent dir must fail")
  4057. }
  4058. os.RemoveAll(testBaseDirPath)
  4059. os.RemoveAll(testBaseDirDownPath)
  4060. err = os.RemoveAll(user.GetHomeDir())
  4061. if err != nil {
  4062. t.Errorf("error removing uploaded files")
  4063. }
  4064. _, err = httpd.RemoveUser(user, http.StatusOK)
  4065. if err != nil {
  4066. t.Errorf("unable to remove user: %v", err)
  4067. }
  4068. }
  4069. func TestSCPExtensionsFilter(t *testing.T) {
  4070. if len(scpPath) == 0 {
  4071. t.Skip("scp command not found, unable to execute this test")
  4072. }
  4073. usePubKey := true
  4074. u := getTestUser(usePubKey)
  4075. user, _, err := httpd.AddUser(u, http.StatusOK)
  4076. if err != nil {
  4077. t.Errorf("unable to add user: %v", err)
  4078. }
  4079. testFileSize := int64(131072)
  4080. testFileName := "test_file.dat"
  4081. testFilePath := filepath.Join(homeBasePath, testFileName)
  4082. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4083. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4084. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4085. err = createTestFile(testFilePath, testFileSize)
  4086. if err != nil {
  4087. t.Errorf("unable to create test file: %v", err)
  4088. }
  4089. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4090. if err != nil {
  4091. t.Errorf("error uploading file via scp: %v", err)
  4092. }
  4093. user.Filters.FileExtensions = []dataprovider.ExtensionsFilter{
  4094. dataprovider.ExtensionsFilter{
  4095. Path: "/",
  4096. AllowedExtensions: []string{".zip"},
  4097. DeniedExtensions: []string{},
  4098. },
  4099. }
  4100. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  4101. if err != nil {
  4102. t.Errorf("unable to update user: %v", err)
  4103. }
  4104. err = scpDownload(localPath, remoteDownPath, false, false)
  4105. if err == nil {
  4106. t.Errorf("scp download must fail")
  4107. }
  4108. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4109. if err == nil {
  4110. t.Error("scp upload must fail")
  4111. }
  4112. _, err = httpd.RemoveUser(user, http.StatusOK)
  4113. if err != nil {
  4114. t.Errorf("unable to remove user: %v", err)
  4115. }
  4116. os.Remove(testFilePath)
  4117. os.Remove(localPath)
  4118. os.RemoveAll(user.GetHomeDir())
  4119. }
  4120. func TestSCPVirtualFolders(t *testing.T) {
  4121. if len(scpPath) == 0 {
  4122. t.Skip("scp command not found, unable to execute this test")
  4123. }
  4124. usePubKey := true
  4125. u := getTestUser(usePubKey)
  4126. mappedPath := filepath.Join(os.TempDir(), "vdir")
  4127. vdirPath := "/vdir"
  4128. u.VirtualFolders = append(u.VirtualFolders, vfs.VirtualFolder{
  4129. VirtualPath: vdirPath,
  4130. MappedPath: mappedPath,
  4131. })
  4132. os.MkdirAll(mappedPath, 0777)
  4133. user, _, err := httpd.AddUser(u, http.StatusOK)
  4134. if err != nil {
  4135. t.Errorf("unable to add user: %v", err)
  4136. }
  4137. testFileName := "test_file.dat"
  4138. testBaseDirName := "test_dir"
  4139. testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName)
  4140. testBaseDirDownName := "test_dir_down"
  4141. testBaseDirDownPath := filepath.Join(homeBasePath, testBaseDirDownName)
  4142. testFilePath := filepath.Join(homeBasePath, testBaseDirName, testFileName)
  4143. testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testBaseDirName, testFileName)
  4144. testFileSize := int64(131074)
  4145. createTestFile(testFilePath, testFileSize)
  4146. createTestFile(testFilePath1, testFileSize)
  4147. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", vdirPath))
  4148. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, vdirPath)
  4149. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  4150. if err != nil {
  4151. t.Errorf("error uploading dir via scp: %v", err)
  4152. }
  4153. err = scpDownload(testBaseDirDownPath, remoteDownPath, true, true)
  4154. if err != nil {
  4155. t.Errorf("error downloading dir via scp: %v", err)
  4156. }
  4157. _, err = httpd.RemoveUser(user, http.StatusOK)
  4158. if err != nil {
  4159. t.Errorf("unable to remove user: %v", err)
  4160. }
  4161. os.RemoveAll(testBaseDirPath)
  4162. os.RemoveAll(testBaseDirDownPath)
  4163. os.RemoveAll(user.GetHomeDir())
  4164. os.RemoveAll(mappedPath)
  4165. }
  4166. func TestSCPPermsSubDirs(t *testing.T) {
  4167. if len(scpPath) == 0 {
  4168. t.Skip("scp command not found, unable to execute this test")
  4169. }
  4170. usePubKey := true
  4171. u := getTestUser(usePubKey)
  4172. u.Permissions["/"] = []string{dataprovider.PermAny}
  4173. u.Permissions["/somedir"] = []string{dataprovider.PermListItems, dataprovider.PermUpload}
  4174. user, _, err := httpd.AddUser(u, http.StatusOK)
  4175. if err != nil {
  4176. t.Errorf("unable to add user: %v", err)
  4177. }
  4178. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4179. subPath := filepath.Join(user.GetHomeDir(), "somedir")
  4180. testFileSize := int64(65535)
  4181. os.MkdirAll(subPath, 0777)
  4182. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/somedir")
  4183. err = scpDownload(localPath, remoteDownPath, false, true)
  4184. if err == nil {
  4185. t.Error("download a dir with no permissions must fail")
  4186. }
  4187. os.Remove(subPath)
  4188. err = createTestFile(subPath, testFileSize)
  4189. if err != nil {
  4190. t.Errorf("unable to create test file: %v", err)
  4191. }
  4192. err = scpDownload(localPath, remoteDownPath, false, false)
  4193. if err != nil {
  4194. t.Errorf("unexpected download error: %v", err)
  4195. }
  4196. os.Chmod(subPath, 0001)
  4197. err = scpDownload(localPath, remoteDownPath, false, false)
  4198. if err == nil {
  4199. t.Error("download a file with no system permissions must fail")
  4200. }
  4201. os.Chmod(subPath, 0755)
  4202. os.Remove(localPath)
  4203. os.RemoveAll(user.GetHomeDir())
  4204. _, err = httpd.RemoveUser(user, http.StatusOK)
  4205. if err != nil {
  4206. t.Errorf("unable to remove user: %v", err)
  4207. }
  4208. }
  4209. func TestSCPPermCreateDirs(t *testing.T) {
  4210. if len(scpPath) == 0 {
  4211. t.Skip("scp command not found, unable to execute this test")
  4212. }
  4213. usePubKey := true
  4214. u := getTestUser(usePubKey)
  4215. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermUpload}
  4216. user, _, err := httpd.AddUser(u, http.StatusOK)
  4217. if err != nil {
  4218. t.Errorf("unable to add user: %v", err)
  4219. }
  4220. testFileName := "test_file.dat"
  4221. testFilePath := filepath.Join(homeBasePath, testFileName)
  4222. testFileSize := int64(32760)
  4223. testBaseDirName := "test_dir"
  4224. testBaseDirPath := filepath.Join(homeBasePath, testBaseDirName)
  4225. testFilePath1 := filepath.Join(homeBasePath, testBaseDirName, testFileName)
  4226. err = createTestFile(testFilePath, testFileSize)
  4227. if err != nil {
  4228. t.Errorf("unable to create test file: %v", err)
  4229. }
  4230. err = createTestFile(testFilePath1, testFileSize)
  4231. if err != nil {
  4232. t.Errorf("unable to create test file: %v", err)
  4233. }
  4234. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp/")
  4235. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4236. if err == nil {
  4237. t.Errorf("scp upload must fail, the user cannot create files in a missing dir")
  4238. }
  4239. err = scpUpload(testBaseDirPath, remoteUpPath, true, false)
  4240. if err == nil {
  4241. t.Errorf("scp upload must fail, the user cannot create new dirs")
  4242. }
  4243. err = os.Remove(testFilePath)
  4244. if err != nil {
  4245. t.Errorf("error removing test file")
  4246. }
  4247. os.RemoveAll(testBaseDirPath)
  4248. err = os.RemoveAll(user.GetHomeDir())
  4249. if err != nil {
  4250. t.Errorf("error removing uploaded files")
  4251. }
  4252. _, err = httpd.RemoveUser(user, http.StatusOK)
  4253. if err != nil {
  4254. t.Errorf("unable to remove user: %v", err)
  4255. }
  4256. }
  4257. func TestSCPPermUpload(t *testing.T) {
  4258. if len(scpPath) == 0 {
  4259. t.Skip("scp command not found, unable to execute this test")
  4260. }
  4261. usePubKey := true
  4262. u := getTestUser(usePubKey)
  4263. u.Permissions["/"] = []string{dataprovider.PermDownload, dataprovider.PermCreateDirs}
  4264. user, _, err := httpd.AddUser(u, http.StatusOK)
  4265. if err != nil {
  4266. t.Errorf("unable to add user: %v", err)
  4267. }
  4268. testFileName := "test_file.dat"
  4269. testFilePath := filepath.Join(homeBasePath, testFileName)
  4270. testFileSize := int64(65536)
  4271. err = createTestFile(testFilePath, testFileSize)
  4272. if err != nil {
  4273. t.Errorf("unable to create test file: %v", err)
  4274. }
  4275. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp")
  4276. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4277. if err == nil {
  4278. t.Errorf("scp upload must fail, the user cannot upload")
  4279. }
  4280. err = os.Remove(testFilePath)
  4281. if err != nil {
  4282. t.Errorf("error removing test file")
  4283. }
  4284. err = os.RemoveAll(user.GetHomeDir())
  4285. if err != nil {
  4286. t.Errorf("error removing uploaded files")
  4287. }
  4288. _, err = httpd.RemoveUser(user, http.StatusOK)
  4289. if err != nil {
  4290. t.Errorf("unable to remove user: %v", err)
  4291. }
  4292. }
  4293. func TestSCPPermOverwrite(t *testing.T) {
  4294. if len(scpPath) == 0 {
  4295. t.Skip("scp command not found, unable to execute this test")
  4296. }
  4297. usePubKey := true
  4298. u := getTestUser(usePubKey)
  4299. u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs}
  4300. user, _, err := httpd.AddUser(u, http.StatusOK)
  4301. if err != nil {
  4302. t.Errorf("unable to add user: %v", err)
  4303. }
  4304. testFileName := "test_file.dat"
  4305. testFilePath := filepath.Join(homeBasePath, testFileName)
  4306. testFileSize := int64(65536)
  4307. err = createTestFile(testFilePath, testFileSize)
  4308. if err != nil {
  4309. t.Errorf("unable to create test file: %v", err)
  4310. }
  4311. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/tmp")
  4312. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4313. if err != nil {
  4314. t.Errorf("scp upload error: %v", err)
  4315. }
  4316. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4317. if err == nil {
  4318. t.Errorf("scp upload must fail, the user cannot ovewrite existing files")
  4319. }
  4320. err = os.Remove(testFilePath)
  4321. if err != nil {
  4322. t.Errorf("error removing test file")
  4323. }
  4324. err = os.RemoveAll(user.GetHomeDir())
  4325. if err != nil {
  4326. t.Errorf("error removing uploaded files")
  4327. }
  4328. _, err = httpd.RemoveUser(user, http.StatusOK)
  4329. if err != nil {
  4330. t.Errorf("unable to remove user: %v", err)
  4331. }
  4332. }
  4333. func TestSCPPermDownload(t *testing.T) {
  4334. if len(scpPath) == 0 {
  4335. t.Skip("scp command not found, unable to execute this test")
  4336. }
  4337. usePubKey := true
  4338. u := getTestUser(usePubKey)
  4339. u.Permissions["/"] = []string{dataprovider.PermUpload, dataprovider.PermCreateDirs}
  4340. user, _, err := httpd.AddUser(u, http.StatusOK)
  4341. if err != nil {
  4342. t.Errorf("unable to add user: %v", err)
  4343. }
  4344. testFileName := "test_file.dat"
  4345. testFilePath := filepath.Join(homeBasePath, testFileName)
  4346. testFileSize := int64(65537)
  4347. err = createTestFile(testFilePath, testFileSize)
  4348. if err != nil {
  4349. t.Errorf("unable to create test file: %v", err)
  4350. }
  4351. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4352. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4353. if err != nil {
  4354. t.Errorf("error uploading existing file via scp: %v", err)
  4355. }
  4356. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4357. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4358. err = scpDownload(localPath, remoteDownPath, false, false)
  4359. if err == nil {
  4360. t.Errorf("scp download must fail, the user cannot download")
  4361. }
  4362. err = os.Remove(testFilePath)
  4363. if err != nil {
  4364. t.Errorf("error removing test file")
  4365. }
  4366. err = os.RemoveAll(user.GetHomeDir())
  4367. if err != nil {
  4368. t.Errorf("error removing uploaded files")
  4369. }
  4370. _, err = httpd.RemoveUser(user, http.StatusOK)
  4371. if err != nil {
  4372. t.Errorf("unable to remove user: %v", err)
  4373. }
  4374. }
  4375. func TestSCPQuotaSize(t *testing.T) {
  4376. if len(scpPath) == 0 {
  4377. t.Skip("scp command not found, unable to execute this test")
  4378. }
  4379. usePubKey := true
  4380. testFileSize := int64(65535)
  4381. u := getTestUser(usePubKey)
  4382. u.QuotaFiles = 1
  4383. u.QuotaSize = testFileSize - 1
  4384. user, _, err := httpd.AddUser(u, http.StatusOK)
  4385. if err != nil {
  4386. t.Errorf("unable to add user: %v", err)
  4387. }
  4388. testFileName := "test_file.dat"
  4389. testFilePath := filepath.Join(homeBasePath, testFileName)
  4390. err = createTestFile(testFilePath, testFileSize)
  4391. if err != nil {
  4392. t.Errorf("unable to create test file: %v", err)
  4393. }
  4394. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4395. err = scpUpload(testFilePath, remoteUpPath, true, false)
  4396. if err != nil {
  4397. t.Errorf("error uploading existing file via scp: %v", err)
  4398. }
  4399. err = scpUpload(testFilePath, remoteUpPath+".quota", true, false)
  4400. if err == nil {
  4401. t.Errorf("user is over quota scp upload must fail")
  4402. }
  4403. err = os.Remove(testFilePath)
  4404. if err != nil {
  4405. t.Errorf("error removing test file")
  4406. }
  4407. err = os.RemoveAll(user.GetHomeDir())
  4408. if err != nil {
  4409. t.Errorf("error removing uploaded files")
  4410. }
  4411. _, err = httpd.RemoveUser(user, http.StatusOK)
  4412. if err != nil {
  4413. t.Errorf("unable to remove user: %v", err)
  4414. }
  4415. }
  4416. func TestSCPEscapeHomeDir(t *testing.T) {
  4417. if len(scpPath) == 0 {
  4418. t.Skip("scp command not found, unable to execute this test")
  4419. }
  4420. usePubKey := true
  4421. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  4422. if err != nil {
  4423. t.Errorf("unable to add user: %v", err)
  4424. }
  4425. os.MkdirAll(user.GetHomeDir(), 0777)
  4426. testDir := "testDir"
  4427. linkPath := filepath.Join(homeBasePath, defaultUsername, testDir)
  4428. err = os.Symlink(homeBasePath, linkPath)
  4429. if err != nil {
  4430. t.Errorf("error making local symlink: %v", err)
  4431. }
  4432. testFileName := "test_file.dat"
  4433. testFilePath := filepath.Join(homeBasePath, testFileName)
  4434. testFileSize := int64(65535)
  4435. err = createTestFile(testFilePath, testFileSize)
  4436. if err != nil {
  4437. t.Errorf("unable to create test file: %v", err)
  4438. }
  4439. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDir, testDir))
  4440. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4441. if err == nil {
  4442. t.Errorf("uploading to a dir with a symlink outside home dir must fail")
  4443. }
  4444. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testDir, testFileName))
  4445. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4446. err = scpDownload(localPath, remoteDownPath, false, false)
  4447. if err == nil {
  4448. t.Errorf("scp download must fail, the requested file has a symlink outside user home")
  4449. }
  4450. remoteDownPath = fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testDir))
  4451. err = scpDownload(homeBasePath, remoteDownPath, false, true)
  4452. if err == nil {
  4453. t.Errorf("scp download must fail, the requested dir is a symlink outside user home")
  4454. }
  4455. err = os.Remove(testFilePath)
  4456. if err != nil {
  4457. t.Errorf("error removing test file")
  4458. }
  4459. err = os.RemoveAll(user.GetHomeDir())
  4460. if err != nil {
  4461. t.Errorf("error removing uploaded files")
  4462. }
  4463. _, err = httpd.RemoveUser(user, http.StatusOK)
  4464. if err != nil {
  4465. t.Errorf("unable to remove user: %v", err)
  4466. }
  4467. }
  4468. func TestSCPUploadPaths(t *testing.T) {
  4469. if len(scpPath) == 0 {
  4470. t.Skip("scp command not found, unable to execute this test")
  4471. }
  4472. usePubKey := true
  4473. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  4474. if err != nil {
  4475. t.Errorf("unable to add user: %v", err)
  4476. }
  4477. testFileName := "test_file.dat"
  4478. testFilePath := filepath.Join(homeBasePath, testFileName)
  4479. testFileSize := int64(65535)
  4480. testDirName := "testDir"
  4481. testDirPath := filepath.Join(user.GetHomeDir(), testDirName)
  4482. os.MkdirAll(testDirPath, 0777)
  4483. err = createTestFile(testFilePath, testFileSize)
  4484. if err != nil {
  4485. t.Errorf("unable to create test file: %v", err)
  4486. }
  4487. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, testDirName)
  4488. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDirName, testFileName))
  4489. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4490. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4491. if err != nil {
  4492. t.Errorf("scp upload error: %v", err)
  4493. }
  4494. err = scpDownload(localPath, remoteDownPath, false, false)
  4495. if err != nil {
  4496. t.Errorf("scp download error: %v", err)
  4497. }
  4498. // upload a file to a missing dir
  4499. remoteUpPath = fmt.Sprintf("%[email protected]:%v", user.Username, path.Join(testDirName, testDirName, testFileName))
  4500. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4501. if err == nil {
  4502. t.Errorf("scp upload to a missing dir must fail")
  4503. }
  4504. err = os.RemoveAll(user.GetHomeDir())
  4505. if err != nil {
  4506. t.Errorf("error removing uploaded files")
  4507. }
  4508. os.Remove(localPath)
  4509. _, err = httpd.RemoveUser(user, http.StatusOK)
  4510. if err != nil {
  4511. t.Errorf("unable to remove user: %v", err)
  4512. }
  4513. }
  4514. func TestSCPOverwriteDirWithFile(t *testing.T) {
  4515. if len(scpPath) == 0 {
  4516. t.Skip("scp command not found, unable to execute this test")
  4517. }
  4518. usePubKey := true
  4519. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  4520. if err != nil {
  4521. t.Errorf("unable to add user: %v", err)
  4522. }
  4523. testFileName := "test_file.dat"
  4524. testFilePath := filepath.Join(homeBasePath, testFileName)
  4525. testFileSize := int64(65535)
  4526. testDirPath := filepath.Join(user.GetHomeDir(), testFileName)
  4527. os.MkdirAll(testDirPath, 0777)
  4528. err = createTestFile(testFilePath, testFileSize)
  4529. if err != nil {
  4530. t.Errorf("unable to create test file: %v", err)
  4531. }
  4532. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4533. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4534. if err == nil {
  4535. t.Errorf("copying a file over an existing dir must fail")
  4536. }
  4537. err = os.RemoveAll(user.GetHomeDir())
  4538. if err != nil {
  4539. t.Errorf("error removing uploaded files")
  4540. }
  4541. _, err = httpd.RemoveUser(user, http.StatusOK)
  4542. if err != nil {
  4543. t.Errorf("unable to remove user: %v", err)
  4544. }
  4545. }
  4546. func TestSCPRemoteToRemote(t *testing.T) {
  4547. if len(scpPath) == 0 {
  4548. t.Skip("scp command not found, unable to execute this test")
  4549. }
  4550. usePubKey := true
  4551. user, _, err := httpd.AddUser(getTestUser(usePubKey), http.StatusOK)
  4552. if err != nil {
  4553. t.Errorf("unable to add user: %v", err)
  4554. }
  4555. u := getTestUser(usePubKey)
  4556. u.Username += "1"
  4557. u.HomeDir += "1"
  4558. user1, _, err := httpd.AddUser(u, http.StatusOK)
  4559. if err != nil {
  4560. t.Errorf("unable to add user: %v", err)
  4561. }
  4562. testFileName := "test_file.dat"
  4563. testFilePath := filepath.Join(homeBasePath, testFileName)
  4564. testFileSize := int64(65535)
  4565. err = createTestFile(testFilePath, testFileSize)
  4566. if err != nil {
  4567. t.Errorf("unable to create test file: %v", err)
  4568. }
  4569. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4570. remote1UpPath := fmt.Sprintf("%[email protected]:%v", user1.Username, path.Join("/", testFileName))
  4571. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4572. if err != nil {
  4573. t.Errorf("scp upload error: %v", err)
  4574. }
  4575. err = scpUpload(remoteUpPath, remote1UpPath, false, true)
  4576. if err != nil {
  4577. t.Errorf("scp upload remote to remote error: %v", err)
  4578. }
  4579. err = os.RemoveAll(user.GetHomeDir())
  4580. if err != nil {
  4581. t.Errorf("error removing uploaded files")
  4582. }
  4583. _, err = httpd.RemoveUser(user, http.StatusOK)
  4584. if err != nil {
  4585. t.Errorf("unable to remove user: %v", err)
  4586. }
  4587. err = os.RemoveAll(user1.GetHomeDir())
  4588. if err != nil {
  4589. t.Errorf("error removing uploaded files for user1")
  4590. }
  4591. _, err = httpd.RemoveUser(user1, http.StatusOK)
  4592. if err != nil {
  4593. t.Errorf("unable to remove user1: %v", err)
  4594. }
  4595. }
  4596. func TestSCPErrors(t *testing.T) {
  4597. if len(scpPath) == 0 {
  4598. t.Skip("scp command not found, unable to execute this test")
  4599. }
  4600. u := getTestUser(true)
  4601. user, _, err := httpd.AddUser(u, http.StatusOK)
  4602. if err != nil {
  4603. t.Errorf("unable to add user: %v", err)
  4604. }
  4605. testFileSize := int64(524288)
  4606. testFileName := "test_file.dat"
  4607. testFilePath := filepath.Join(homeBasePath, testFileName)
  4608. err = createTestFile(testFilePath, testFileSize)
  4609. if err != nil {
  4610. t.Errorf("unable to create test file: %v", err)
  4611. }
  4612. remoteUpPath := fmt.Sprintf("%[email protected]:%v", user.Username, "/")
  4613. remoteDownPath := fmt.Sprintf("%[email protected]:%v", user.Username, path.Join("/", testFileName))
  4614. localPath := filepath.Join(homeBasePath, "scp_download.dat")
  4615. err = scpUpload(testFilePath, remoteUpPath, false, false)
  4616. if err != nil {
  4617. t.Errorf("error uploading file via scp: %v", err)
  4618. }
  4619. user.UploadBandwidth = 512
  4620. user.DownloadBandwidth = 512
  4621. _, _, err = httpd.UpdateUser(user, http.StatusOK)
  4622. if err != nil {
  4623. t.Errorf("unable to update user: %v", err)
  4624. }
  4625. cmd := getScpDownloadCommand(localPath, remoteDownPath, false, false)
  4626. go func() {
  4627. if cmd.Run() == nil {
  4628. t.Errorf("SCP download must fail")
  4629. }
  4630. }()
  4631. waitForActiveTransfer()
  4632. // wait some additional arbitrary time to wait for transfer activity to happen
  4633. // it is need to reach all the code in CheckIdleConnections
  4634. time.Sleep(100 * time.Millisecond)
  4635. cmd.Process.Kill()
  4636. waitForNoActiveTransfer()
  4637. cmd = getScpUploadCommand(testFilePath, remoteUpPath, false, false)
  4638. go func() {
  4639. if cmd.Run() == nil {
  4640. t.Errorf("SCP upload must fail")
  4641. }
  4642. }()
  4643. waitForActiveTransfer()
  4644. // wait some additional arbitrary time to wait for transfer activity to happen
  4645. // it is need to reach all the code in CheckIdleConnections
  4646. time.Sleep(100 * time.Millisecond)
  4647. cmd.Process.Kill()
  4648. waitForNoActiveTransfer()
  4649. err = os.Remove(testFilePath)
  4650. if err != nil {
  4651. t.Errorf("error removing test file")
  4652. }
  4653. os.Remove(localPath)
  4654. err = os.RemoveAll(user.GetHomeDir())
  4655. if err != nil {
  4656. t.Errorf("error removing uploaded files")
  4657. }
  4658. _, err = httpd.RemoveUser(user, http.StatusOK)
  4659. if err != nil {
  4660. t.Errorf("unable to remove user: %v", err)
  4661. }
  4662. }
  4663. // End SCP tests
  4664. func waitTCPListening(address string) {
  4665. for {
  4666. conn, err := net.Dial("tcp", address)
  4667. if err != nil {
  4668. logger.WarnToConsole("tcp server %v not listening: %v\n", address, err)
  4669. time.Sleep(100 * time.Millisecond)
  4670. continue
  4671. }
  4672. logger.InfoToConsole("tcp server %v now listening\n", address)
  4673. defer conn.Close()
  4674. break
  4675. }
  4676. }
  4677. func getTestUser(usePubKey bool) dataprovider.User {
  4678. user := dataprovider.User{
  4679. Username: defaultUsername,
  4680. Password: defaultPassword,
  4681. HomeDir: filepath.Join(homeBasePath, defaultUsername),
  4682. Status: 1,
  4683. ExpirationDate: 0,
  4684. }
  4685. user.Permissions = make(map[string][]string)
  4686. user.Permissions["/"] = allPerms
  4687. if usePubKey {
  4688. user.PublicKeys = []string{testPubKey}
  4689. user.Password = ""
  4690. }
  4691. return user
  4692. }
  4693. func runSSHCommand(command string, user dataprovider.User, usePubKey bool) ([]byte, error) {
  4694. var sshSession *ssh.Session
  4695. var output []byte
  4696. config := &ssh.ClientConfig{
  4697. User: defaultUsername,
  4698. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4699. return nil
  4700. },
  4701. }
  4702. if usePubKey {
  4703. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  4704. if err != nil {
  4705. return output, err
  4706. }
  4707. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  4708. } else {
  4709. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  4710. }
  4711. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  4712. if err != nil {
  4713. return output, err
  4714. }
  4715. defer conn.Close()
  4716. sshSession, err = conn.NewSession()
  4717. if err != nil {
  4718. return output, err
  4719. }
  4720. var stdout, stderr bytes.Buffer
  4721. sshSession.Stdout = &stdout
  4722. sshSession.Stderr = &stderr
  4723. err = sshSession.Run(command)
  4724. if err != nil {
  4725. return nil, fmt.Errorf("failed to run command %v: %v", command, stderr.Bytes())
  4726. }
  4727. return stdout.Bytes(), err
  4728. }
  4729. func getSftpClientWithAddr(user dataprovider.User, usePubKey bool, addr string) (*sftp.Client, error) {
  4730. var sftpClient *sftp.Client
  4731. config := &ssh.ClientConfig{
  4732. User: user.Username,
  4733. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4734. return nil
  4735. },
  4736. }
  4737. if usePubKey {
  4738. key, err := ssh.ParsePrivateKey([]byte(testPrivateKey))
  4739. if err != nil {
  4740. return nil, err
  4741. }
  4742. config.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
  4743. } else {
  4744. if len(user.Password) > 0 {
  4745. config.Auth = []ssh.AuthMethod{ssh.Password(user.Password)}
  4746. } else {
  4747. config.Auth = []ssh.AuthMethod{ssh.Password(defaultPassword)}
  4748. }
  4749. }
  4750. conn, err := ssh.Dial("tcp", addr, config)
  4751. if err != nil {
  4752. return sftpClient, err
  4753. }
  4754. sftpClient, err = sftp.NewClient(conn)
  4755. return sftpClient, err
  4756. }
  4757. func getSftpClient(user dataprovider.User, usePubKey bool) (*sftp.Client, error) {
  4758. return getSftpClientWithAddr(user, usePubKey, sftpServerAddr)
  4759. }
  4760. func getKeyboardInteractiveSftpClient(user dataprovider.User, answers []string) (*sftp.Client, error) {
  4761. var sftpClient *sftp.Client
  4762. config := &ssh.ClientConfig{
  4763. User: user.Username,
  4764. HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  4765. return nil
  4766. },
  4767. Auth: []ssh.AuthMethod{
  4768. ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {
  4769. return answers, nil
  4770. }),
  4771. },
  4772. }
  4773. conn, err := ssh.Dial("tcp", sftpServerAddr, config)
  4774. if err != nil {
  4775. return sftpClient, err
  4776. }
  4777. sftpClient, err = sftp.NewClient(conn)
  4778. return sftpClient, err
  4779. }
  4780. func createTestFile(path string, size int64) error {
  4781. baseDir := filepath.Dir(path)
  4782. if _, err := os.Stat(baseDir); os.IsNotExist(err) {
  4783. os.MkdirAll(baseDir, 0777)
  4784. }
  4785. content := make([]byte, size)
  4786. _, err := rand.Read(content)
  4787. if err != nil {
  4788. return err
  4789. }
  4790. return ioutil.WriteFile(path, content, 0666)
  4791. }
  4792. func appendToTestFile(path string, size int64) error {
  4793. content := make([]byte, size)
  4794. _, err := rand.Read(content)
  4795. if err != nil {
  4796. return err
  4797. }
  4798. f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0666)
  4799. if err != nil {
  4800. return err
  4801. }
  4802. written, err := io.Copy(f, bytes.NewReader(content))
  4803. if err != nil {
  4804. return err
  4805. }
  4806. if int64(written) != size {
  4807. return fmt.Errorf("write error, written: %v/%v", written, size)
  4808. }
  4809. return nil
  4810. }
  4811. func sftpUploadFile(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) error {
  4812. srcFile, err := os.Open(localSourcePath)
  4813. if err != nil {
  4814. return err
  4815. }
  4816. defer srcFile.Close()
  4817. destFile, err := client.Create(remoteDestPath)
  4818. if err != nil {
  4819. return err
  4820. }
  4821. _, err = io.Copy(destFile, srcFile)
  4822. if err != nil {
  4823. destFile.Close()
  4824. return err
  4825. }
  4826. // we need to close the file to trigger the close method on server
  4827. // we cannot defer closing or Lstat will fail for uploads in atomic mode
  4828. destFile.Close()
  4829. if expectedSize > 0 {
  4830. fi, err := client.Stat(remoteDestPath)
  4831. if err != nil {
  4832. return err
  4833. }
  4834. if fi.Size() != expectedSize {
  4835. return fmt.Errorf("uploaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4836. }
  4837. }
  4838. return err
  4839. }
  4840. func sftpUploadResumeFile(localSourcePath string, remoteDestPath string, expectedSize int64, invalidOffset bool,
  4841. client *sftp.Client) error {
  4842. srcFile, err := os.Open(localSourcePath)
  4843. if err != nil {
  4844. return err
  4845. }
  4846. defer srcFile.Close()
  4847. fi, err := client.Lstat(remoteDestPath)
  4848. if err != nil {
  4849. return err
  4850. }
  4851. if !invalidOffset {
  4852. _, err = srcFile.Seek(fi.Size(), 0)
  4853. if err != nil {
  4854. return err
  4855. }
  4856. }
  4857. destFile, err := client.OpenFile(remoteDestPath, os.O_WRONLY|os.O_APPEND)
  4858. if err != nil {
  4859. return err
  4860. }
  4861. if !invalidOffset {
  4862. _, err = destFile.Seek(fi.Size(), 0)
  4863. if err != nil {
  4864. return err
  4865. }
  4866. }
  4867. _, err = io.Copy(destFile, srcFile)
  4868. if err != nil {
  4869. destFile.Close()
  4870. return err
  4871. }
  4872. // we need to close the file to trigger the close method on server
  4873. // we cannot defer closing or Lstat will fail for upload atomic mode
  4874. destFile.Close()
  4875. if expectedSize > 0 {
  4876. fi, err := client.Lstat(remoteDestPath)
  4877. if err != nil {
  4878. return err
  4879. }
  4880. if fi.Size() != expectedSize {
  4881. return fmt.Errorf("uploaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4882. }
  4883. }
  4884. return err
  4885. }
  4886. func sftpDownloadFile(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) error {
  4887. downloadDest, err := os.Create(localDestPath)
  4888. if err != nil {
  4889. return err
  4890. }
  4891. defer downloadDest.Close()
  4892. sftpSrcFile, err := client.Open(remoteSourcePath)
  4893. if err != nil {
  4894. return err
  4895. }
  4896. defer sftpSrcFile.Close()
  4897. _, err = io.Copy(downloadDest, sftpSrcFile)
  4898. if err != nil {
  4899. return err
  4900. }
  4901. err = downloadDest.Sync()
  4902. if err != nil {
  4903. return err
  4904. }
  4905. if expectedSize > 0 {
  4906. fi, err := downloadDest.Stat()
  4907. if err != nil {
  4908. return err
  4909. }
  4910. if fi.Size() != expectedSize {
  4911. return fmt.Errorf("downloaded file size does not match, actual: %v, expected: %v", fi.Size(), expectedSize)
  4912. }
  4913. }
  4914. return err
  4915. }
  4916. func sftpUploadNonBlocking(localSourcePath string, remoteDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  4917. c := make(chan error)
  4918. go func() {
  4919. c <- sftpUploadFile(localSourcePath, remoteDestPath, expectedSize, client)
  4920. }()
  4921. return c
  4922. }
  4923. func sftpDownloadNonBlocking(remoteSourcePath string, localDestPath string, expectedSize int64, client *sftp.Client) <-chan error {
  4924. c := make(chan error)
  4925. go func() {
  4926. c <- sftpDownloadFile(remoteSourcePath, localDestPath, expectedSize, client)
  4927. }()
  4928. return c
  4929. }
  4930. func scpUpload(localPath, remotePath string, preserveTime, remoteToRemote bool) error {
  4931. cmd := getScpUploadCommand(localPath, remotePath, preserveTime, remoteToRemote)
  4932. return cmd.Run()
  4933. }
  4934. func scpDownload(localPath, remotePath string, preserveTime, recursive bool) error {
  4935. cmd := getScpDownloadCommand(localPath, remotePath, preserveTime, recursive)
  4936. return cmd.Run()
  4937. }
  4938. func getScpDownloadCommand(localPath, remotePath string, preserveTime, recursive bool) *exec.Cmd {
  4939. var args []string
  4940. if preserveTime {
  4941. args = append(args, "-p")
  4942. }
  4943. if recursive {
  4944. args = append(args, "-r")
  4945. }
  4946. args = append(args, "-P")
  4947. args = append(args, "2022")
  4948. args = append(args, "-o")
  4949. args = append(args, "StrictHostKeyChecking=no")
  4950. args = append(args, "-i")
  4951. args = append(args, privateKeyPath)
  4952. args = append(args, remotePath)
  4953. args = append(args, localPath)
  4954. return exec.Command(scpPath, args...)
  4955. }
  4956. func getScpUploadCommand(localPath, remotePath string, preserveTime, remoteToRemote bool) *exec.Cmd {
  4957. var args []string
  4958. if remoteToRemote {
  4959. args = append(args, "-3")
  4960. }
  4961. if preserveTime {
  4962. args = append(args, "-p")
  4963. }
  4964. fi, err := os.Stat(localPath)
  4965. if err == nil {
  4966. if fi.IsDir() {
  4967. args = append(args, "-r")
  4968. }
  4969. }
  4970. args = append(args, "-P")
  4971. args = append(args, "2022")
  4972. args = append(args, "-o")
  4973. args = append(args, "StrictHostKeyChecking=no")
  4974. args = append(args, "-i")
  4975. args = append(args, privateKeyPath)
  4976. args = append(args, localPath)
  4977. args = append(args, remotePath)
  4978. return exec.Command(scpPath, args...)
  4979. }
  4980. func computeHashForFile(hasher hash.Hash, path string) (string, error) {
  4981. hash := ""
  4982. f, err := os.Open(path)
  4983. if err != nil {
  4984. return hash, err
  4985. }
  4986. defer f.Close()
  4987. _, err = io.Copy(hasher, f)
  4988. if err == nil {
  4989. hash = fmt.Sprintf("%x", hasher.Sum(nil))
  4990. }
  4991. return hash, err
  4992. }
  4993. func waitForNoActiveTransfer() {
  4994. for len(sftpd.GetConnectionsStats()) > 0 {
  4995. time.Sleep(100 * time.Millisecond)
  4996. }
  4997. }
  4998. func waitForActiveTransfer() {
  4999. stats := sftpd.GetConnectionsStats()
  5000. for len(stats) < 1 {
  5001. stats = sftpd.GetConnectionsStats()
  5002. }
  5003. activeTransferFound := false
  5004. for !activeTransferFound {
  5005. stats = sftpd.GetConnectionsStats()
  5006. if len(stats) == 0 {
  5007. break
  5008. }
  5009. for _, stat := range stats {
  5010. if len(stat.Transfers) > 0 {
  5011. activeTransferFound = true
  5012. }
  5013. }
  5014. }
  5015. }
  5016. func waitQuotaScans() error {
  5017. time.Sleep(100 * time.Millisecond)
  5018. scans, _, err := httpd.GetQuotaScans(http.StatusOK)
  5019. if err != nil {
  5020. return err
  5021. }
  5022. for len(scans) > 0 {
  5023. time.Sleep(100 * time.Millisecond)
  5024. scans, _, err = httpd.GetQuotaScans(http.StatusOK)
  5025. if err != nil {
  5026. return err
  5027. }
  5028. }
  5029. return nil
  5030. }
  5031. func initGitRepo(path string) ([]byte, error) {
  5032. os.MkdirAll(path, 0777)
  5033. args := []string{"init", "--bare"}
  5034. cmd := exec.Command(gitPath, args...)
  5035. cmd.Dir = path
  5036. return cmd.CombinedOutput()
  5037. }
  5038. func pushToGitRepo(repoPath string) ([]byte, error) {
  5039. cmd := exec.Command(gitPath, "push")
  5040. cmd.Dir = repoPath
  5041. cmd.Env = append(os.Environ(),
  5042. fmt.Sprintf("GIT_SSH=%v", gitWrapPath))
  5043. return cmd.CombinedOutput()
  5044. }
  5045. func cloneGitRepo(basePath, remotePath, username string) ([]byte, error) {
  5046. remoteUrl := fmt.Sprintf("ssh://%[email protected]:2022%v", username, remotePath)
  5047. args := []string{"clone", remoteUrl}
  5048. cmd := exec.Command(gitPath, args...)
  5049. cmd.Dir = basePath
  5050. cmd.Env = append(os.Environ(),
  5051. fmt.Sprintf("GIT_SSH=%v", gitWrapPath))
  5052. return cmd.CombinedOutput()
  5053. }
  5054. func addFileToGitRepo(repoPath string, fileSize int64) ([]byte, error) {
  5055. path := filepath.Join(repoPath, "test")
  5056. err := createTestFile(path, fileSize)
  5057. if err != nil {
  5058. return []byte(""), err
  5059. }
  5060. cmd := exec.Command(gitPath, "config", "user.email", "[email protected]")
  5061. cmd.Dir = repoPath
  5062. out, err := cmd.CombinedOutput()
  5063. if err != nil {
  5064. return out, err
  5065. }
  5066. cmd = exec.Command(gitPath, "config", "user.name", "testuser")
  5067. cmd.Dir = repoPath
  5068. out, err = cmd.CombinedOutput()
  5069. if err != nil {
  5070. return out, err
  5071. }
  5072. cmd = exec.Command(gitPath, "add", "test")
  5073. cmd.Dir = repoPath
  5074. out, err = cmd.CombinedOutput()
  5075. if err != nil {
  5076. return out, err
  5077. }
  5078. cmd = exec.Command(gitPath, "commit", "-am", "test")
  5079. cmd.Dir = repoPath
  5080. return cmd.CombinedOutput()
  5081. }
  5082. func getKeyboardInteractiveScriptContent(questions []string, sleepTime int, nonJsonResponse bool, result int) []byte {
  5083. content := []byte("#!/bin/sh\n\n")
  5084. q, _ := json.Marshal(questions)
  5085. echos := []bool{}
  5086. for index := range questions {
  5087. echos = append(echos, index%2 == 0)
  5088. }
  5089. e, _ := json.Marshal(echos)
  5090. if nonJsonResponse {
  5091. content = append(content, []byte(fmt.Sprintf("echo 'questions: %v echos: %v\n", string(q), string(e)))...)
  5092. } else {
  5093. content = append(content, []byte(fmt.Sprintf("echo '{\"questions\":%v,\"echos\":%v}'\n", string(q), string(e)))...)
  5094. }
  5095. for index := range questions {
  5096. content = append(content, []byte(fmt.Sprintf("read ANSWER%v\n", index))...)
  5097. }
  5098. if sleepTime > 0 {
  5099. content = append(content, []byte(fmt.Sprintf("sleep %v\n", sleepTime))...)
  5100. }
  5101. content = append(content, []byte(fmt.Sprintf("echo '{\"auth_result\":%v}'\n", result))...)
  5102. return content
  5103. }
  5104. func getExtAuthScriptContent(user dataprovider.User, sleepTime int, nonJsonResponse bool) []byte {
  5105. extAuthContent := []byte("#!/bin/sh\n\n")
  5106. u, _ := json.Marshal(user)
  5107. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("if test \"$SFTPGO_AUTHD_USERNAME\" = \"%v\"; then\n", user.Username))...)
  5108. if nonJsonResponse {
  5109. extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...)
  5110. } else {
  5111. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("echo '%v'\n", string(u)))...)
  5112. }
  5113. extAuthContent = append(extAuthContent, []byte("else\n")...)
  5114. if nonJsonResponse {
  5115. extAuthContent = append(extAuthContent, []byte("echo 'text response'\n")...)
  5116. } else {
  5117. extAuthContent = append(extAuthContent, []byte("echo '{\"username\":\"\"}'\n")...)
  5118. }
  5119. extAuthContent = append(extAuthContent, []byte("fi\n")...)
  5120. if sleepTime > 0 {
  5121. extAuthContent = append(extAuthContent, []byte(fmt.Sprintf("sleep %v\n", sleepTime))...)
  5122. }
  5123. return extAuthContent
  5124. }
  5125. func getPreLoginScriptContent(user dataprovider.User, nonJsonResponse bool) []byte {
  5126. content := []byte("#!/bin/sh\n\n")
  5127. if nonJsonResponse {
  5128. content = append(content, []byte("echo 'text response'\n")...)
  5129. return content
  5130. }
  5131. if len(user.Username) > 0 {
  5132. u, _ := json.Marshal(user)
  5133. content = append(content, []byte(fmt.Sprintf("echo '%v'\n", string(u)))...)
  5134. }
  5135. return content
  5136. }
  5137. func printLatestLogs(maxNumberOfLines int) {
  5138. var lines []string
  5139. f, err := os.Open(logFilePath)
  5140. if err != nil {
  5141. return
  5142. }
  5143. defer f.Close()
  5144. scanner := bufio.NewScanner(f)
  5145. for scanner.Scan() {
  5146. lines = append(lines, scanner.Text()+"\r\n")
  5147. for len(lines) > maxNumberOfLines {
  5148. lines = lines[1:]
  5149. }
  5150. }
  5151. if scanner.Err() != nil {
  5152. logger.WarnToConsole("Unable to print latest logs: %v", scanner.Err())
  5153. return
  5154. }
  5155. for _, line := range lines {
  5156. logger.DebugToConsole(line)
  5157. }
  5158. }