forked from pypi/legacy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webui.py
4208 lines (3658 loc) · 159 KB
/
webui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# import defusedxml before anything else
import defusedxml
import defusedxml.xmlrpc
defusedxml.xmlrpc.monkey_patch()
# system imports
import sys, os, urllib, cStringIO, traceback, cgi, binascii, gzip, functools
import time, random, smtplib, base64, email, types, urlparse
import re, zipfile, logging, shutil, Cookie, subprocess, hashlib
import datetime, string, traceback
from zope.pagetemplate.pagetemplatefile import PageTemplateFile
from distutils.util import rfc822_escape
from distutils2.metadata import Metadata
from xml.etree import cElementTree
import itsdangerous
import redis
import rq
import boto.s3
from pyblake2 import blake2b
from rfc3986 import uri_reference
try:
import json
except ImportError:
import simplejson as json
try:
import psycopg2
OperationalError = psycopg2.OperationalError
IntegrityError = psycopg2.IntegrityError
except ImportError:
class OperationalError(Exception):
pass
# OpenId provider imports
OPENID_FILESTORE = '/tmp/openid-filestore'
from openid.server import server as OpenIDServer
# Raven for error reporting
import raven
import raven.utils.wsgi
from raven.handlers.logging import SentryHandler
import packaging.version
# Filesystem Handling
import fs.errors
import fs.multifs
import fs.osfs
import fs.s3fs
import readme_renderer.rst
import readme_renderer.txt
# local imports
import store, config, versionpredicate, verify_filetype, rpc
import MailingLogger, openid2rp, gae
from mini_pkg_resources import safe_name
from description_utils import extractPackageReadme, trim_docstring
import oauth
import tasks
from perfmetrics import statsd_client
from perfmetrics import set_statsd_client
import config
root = os.path.dirname(os.path.abspath(__file__))
conf = config.Config(os.path.join(root, "config.ini"))
STATSD_URI = "statsd://127.0.0.1:8125?prefix=%s" % (conf.database_name)
set_statsd_client(STATSD_URI)
esc = cgi.escape
esq = lambda x: cgi.escape(x, True)
def enumerate(sequence):
return [(i, sequence[i]) for i in range(len(sequence))]
# Requires:
# - ASCII letters
# - ASCII digits
# - underscores
# - dashes
# - periods
# - Starts with letter or digit
legal_package_name = re.compile(r"^[a-z0-9\._-]+$", re.IGNORECASE)
safe_filenames = re.compile(r'.+?\.(exe|tar\.gz|bz2|rpm|deb|zip|tgz|egg|dmg|msi|whl)$', re.I)
# Must begin and end with an alphanumeric, interior can also contain ._-
safe_username = re.compile(r"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$", re.I)
safe_email = re.compile(r'^[a-zA-Z0-9._+@-]+$')
botre = re.compile(r'^$|brains|yeti|myie2|findlinks|ia_archiver|psycheclone|badass|crawler|slurp|spider|bot|scooter|infoseek|looksmart|jeeves', re.I)
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?)
((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?)
\.whl|\.dist-info)$""",
re.VERBOSE)
packages_path_to_package_name = re.compile(
'^/([0-9\.]+|any|source)/./([a-zA-Z0-9][a-zA-Z0-9_\-\.]*)')
class NotFound(Exception):
pass
class Gone(Exception):
pass
class Unauthorised(Exception):
pass
class UnauthorisedForm(Exception):
pass
class UserNotFound(Exception):
pass
class Forbidden(Exception):
pass
class Redirect(Exception):
pass
class RedirectFound(Exception):# 302
pass
class RedirectTemporary(Exception): # 307
pass
class FormError(Exception):
pass
class OpenIDError(Exception):
pass
class OAuthError(Exception):
pass
class BlockedIP(Exception):
pass
class MultipleReleases(Exception):
def __init__(self, releases):
self.releases = releases
__version__ = '1.1'
providers = (('Launchpad', 'https://launchpad.net/@@/launchpad.png', 'https://login.launchpad.net/'),)
# email sent to user indicating how they should complete their registration
rego_message = '''Subject: Complete your PyPI registration
From: %(admin)s
To: %(email)s
To complete your registration of the user "%(name)s" with the python module
index, please visit the following URL:
%(url)s?:action=user&otk=%(otk)s
'''
# password change request email
password_change_message = '''Subject: PyPI password change request
From: %(admin)s
To: %(email)s
Someone, perhaps you, has requested that the password be changed for your
username, "%(name)s". If you wish to proceed with the change, please follow
the link below:
%(url)s?:action=pw_reset&otk=%(otk)s
This will present a form in which you may set your new password.
'''
_prov = '<p>You may also login or register using <a href="%(url_path)s?:action=openid">OpenID</a>'
for title, favicon, login in providers:
_prov += '''
<a href="%s"><img src="%s" title="%s"/></a>
''' % (login, favicon, title)
_prov += "</p>"
unauth_message = '''
<p>If you are a new user, <a href="%(url_path)s?:action=register_form">please
register</a>.</p>
<p>If you have forgotten your password, you can have it
<a href="%(url_path)s?:action=forgotten_password_form">reset for you</a>.</p>
''' + _prov
blocked_ip_message = '''
You have attempted too many logins from this IP address. Please try again
later.
'''
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
class Provider:
def __init__(self, name, favicon, url):
self.name = self.title = name
self.favicon = favicon
self.url = url
class _PyPiPageTemplate(PageTemplateFile):
def pt_getContext(self, args=(), options={}, **kw):
"""Add our data into ZPT's defaults"""
rval = PageTemplateFile.pt_getContext(self, args=args)
options.update(rval)
return options
cache_templates = True
if cache_templates:
template_cache = {}
def PyPiPageTemplate(file, dir):
try:
return template_cache[(file, dir)]
except KeyError:
t = _PyPiPageTemplate(file, dir)
template_cache[(file, dir)] = t
return t
else:
PyPiPageTemplate = _PyPiPageTemplate
class FileUpload:
pass
# poor man's markup heuristics so we don't have to use <PRE>,
# for when rst didn't work on the text...
br_patt = re.compile(" *\r?\n\r?(?= +)")
p_patt = re.compile(" *\r?\n(\r?\n)+")
def newline_to_br(text):
text = re.sub(br_patt, "<BR/>", text)
return re.sub(p_patt, "\n<P>\n", text)
def path2str(path):
return " :: ".join(path)
def str2path(s):
return [ node.strip() for node in s.split("::") ]
def transmute(field):
if hasattr(field, 'filename') and field.filename:
v = FileUpload()
v.filename = field.filename
v.value = field.value
v.type = field.type
else:
v = field.value.decode('utf-8')
return v
def decode_form(form):
d = {}
if not form:
return d
for k in form.keys():
v = form[k]
if isinstance(v, list):
d[k] = [transmute(i) for i in v]
else:
d[k] = transmute(v)
return d
def must_tls(fn):
@functools.wraps(fn)
def wrapped(self, *args, **kwargs):
if self.env.get('HTTP_X_FORWARDED_PROTO') != 'https':
raise Forbidden("Must access using HTTPS instead of HTTP")
return fn(self, *args, **kwargs)
return wrapped
class MultiWriteFS(fs.multifs.MultiFS):
@fs.multifs.synchronize
def remove(self, path):
# raise FormError, "Deleting files has been disabled."
found = False
for fs in self:
if fs.exists(path):
found = True
fs.remove(path)
if not found:
raise fs.multifs.ResourceNotFoundError(path)
class NoDirS3FS(fs.s3fs.S3FS):
@property
def _s3conn(self):
try:
(c,ctime) = self._tlocal.s3conn
if time.time() - ctime > 60:
raise AttributeError
return c
except AttributeError:
c = boto.s3.connect_to_region(
"us-west-2",
aws_access_key_id=self._access_keys[0],
aws_secret_access_key=self._access_keys[1],
)
self._tlocal.s3conn = (c,time.time())
return c
def makedir(self, *args, **kwargs):
pass # Noop this, S3 doesn't need directories
def removedir(self, *args, **kwargs):
pass # Noop this, S3 doesn't need directories
# Wheel platform checking
# These platforms can be handled by a simple static list:
_allowed_platforms = {
"any",
"win32", "win_amd64", "win_ia64",
"manylinux1_x86_64", "manylinux1_i686",
}
# macosx is a little more complicated:
_macosx_platform_re = re.compile("macosx_10_(\d+)+_(?P<arch>.*)")
_macosx_arches = {
"ppc", "ppc64",
"i386", "x86_64",
"intel", "fat", "fat32", "fat64", "universal",
}
# Actual checking code;
def _valid_platform_tag(platform_tag):
if platform_tag in _allowed_platforms:
return True
m = _macosx_platform_re.match(platform_tag)
if m and m.group("arch") in _macosx_arches:
return True
return False
class WebUI:
''' Handle a request as defined by the "env" parameter. "handler" gives
access to the user via rfile and wfile, and a few convenience
functions (see pypi).
The handling of a request goes as follows:
1. open the database
2. see if the request is supplied with authentication information
3. perform the action defined by :action ("home" if none is supplied)
4a. handle exceptions sanely, including special ones like NotFound,
Unauthorised, Redirect and FormError, or
4b. commit changes to the database
5. close the database to finish off
'''
def __init__(self, handler, env):
self.handler = handler
self.config = handler.config
self.wfile = handler.wfile
self.sentry_client = None
if self.config.sentry_dsn:
self.sentry_client = raven.Client(self.config.sentry_dsn)
if self.config.count_redis_url:
self.count_redis = redis.Redis.from_url(self.config.count_redis_url)
else:
self.count_redis = None
if self.config.queue_redis_url:
self.queue_redis = redis.Redis.from_url(self.config.queue_redis_url)
self.queue = rq.Queue(connection=self.queue_redis)
else:
self.queue = None
if self.config.cache_redis_url:
self.cache_redis = redis.StrictRedis.from_url(self.config.cache_redis_url)
else:
self.cache_redis = None
# block redis is used to store blocked users, IPs, etc to prevent brute
# force attacks
if self.config.block_redis_url:
self.block_redis = redis.Redis.from_url(self.config.block_redis_url)
else:
self.block_redis = None
self.env = env
self.nav_current = None
self.privkey = None
self.username = None
self.authenticated = False # was a password or a valid cookie passed?
self.loggedin = False # was a valid cookie sent?
self.usercookie = None
self.failed = None # error message if initialization already produced a failure
self.s3conn = boto.s3.connect_to_region(
"us-west-2",
aws_access_key_id=self.config.database_aws_access_key_id,
aws_secret_access_key=self.config.database_aws_secret_access_key,
)
self.package_bucket = self.s3conn.get_bucket(
self.config.database_files_bucket,
validate=False,
)
if self.config.database_docs_bucket is not None:
self.docs_fs = NoDirS3FS(
bucket=self.config.database_docs_bucket,
aws_access_key=self.config.database_aws_access_key_id,
aws_secret_key=self.config.database_aws_secret_access_key,
)
else:
self.docs_fs = fs.osfs.OSFS(self.config.database_docs_dir)
# XMLRPC request or not?
if self.env.get('CONTENT_TYPE') != 'text/xml':
fstorage = cgi.FieldStorage(fp=handler.rfile, environ=env)
try:
self.form = decode_form(fstorage)
except UnicodeDecodeError:
self.failed = "Form data is not correctly encoded in UTF-8"
else:
self.form = None
# figure who the end user is
self.remote_addr = self.env['REMOTE_ADDR']
if env.get('HTTP_X_FORWARDED_FOR'):
# X-Forwarded-For: client1, proxy1, proxy2
self.remote_addr = self.env['HTTP_X_FORWARDED_FOR'].split(',')[0]
# set HTTPS mode if we're directly or indirectly (proxy) supposed to be
# serving HTTPS links
if env.get('HTTP_X_FORWARDED_PROTO') == 'https':
self.config.make_https()
else:
self.config.make_http()
(protocol, machine, path, x, x, x) = urlparse.urlparse(self.config.url)
self.url_machine = '%s://%s'%(protocol, machine)
self.url_path = path
# configure logging
if self.config.logfile or self.config.mail_logger or self.config.sentry_dsn:
root = logging.getLogger()
root.setLevel(logging.WARNING)
# I give no shits about getting distutils2 warnings
d2_logger = logging.getLogger('distutils2')
d2_logger.setLevel(logging.ERROR)
if self.config.logfile:
hdlr = logging.FileHandler(self.config.logfile)
formatter = logging.Formatter(
'%(asctime)s %(name)s:%(levelname)s %(message)s')
hdlr.setFormatter(formatter)
root.handlers.append(hdlr)
if self.config.mail_logger:
smtp_starttls = None
if self.config.smtp_starttls:
smtp_starttls = ()
smtp_credentials = None
if self.config.smtp_auth:
smtp_credentials = (self.config.smtp_login, self.config.smtp_password)
hdlr = MailingLogger.MailingLogger(self.config.smtp_hostname,
self.config.fromaddr,
self.config.toaddrs,
'[PyPI] %(line)s',
credentials=smtp_credentials,
secure=smtp_starttls,
send_empty_entries=False,
flood_level=10)
root.handlers.append(hdlr)
if self.config.sentry_dsn:
root.handlers.append(SentryHandler(self.sentry_client))
def run(self):
''' Run the request, handling all uncaught errors and finishing off
cleanly.
'''
if self.failed:
# failed during initialization
self.fail(self.failed)
return
self.store = store.Store(
self.config,
queue=self.queue,
redis=self.count_redis,
package_bucket=self.package_bucket,
)
self.statsd = statsd_client()
try:
try:
self.store.get_cursor() # make sure we can connect
op_endpoint = "%s?:action=openid_endpoint" % (self.config.url,)
self.oid_server = OpenIDServer.Server(self.store.oid_store(), op_endpoint=op_endpoint)
self.inner_run()
except NotFound, err:
self.fail('Not Found (%s)' % err, code=404)
except Gone, err:
self.fail('Gone (%s)' % err, code=410, headers={"Cache-Control": "max-age=31557600, public"})
except Unauthorised, message:
message = str(message)
if not message:
message = 'You must login to access this feature'
msg = unauth_message%self.__dict__
self.fail(message, code=401, heading='Login required',
content=msg, headers={'WWW-Authenticate':
'Basic realm="pypi"'})
except UnauthorisedForm, message:
message = str(message)
if not message:
message = 'You must login to access this feature'
msg = unauth_message%self.__dict__
self.fail(message, code=401, content=msg)
except Forbidden, message:
message = str(message)
self.fail(message, code=403, heading='Forbidden')
except Redirect, e:
self.handler.send_response(301, 'Moved Permanently')
self.handler.send_header('Location', e.args[0].encode("utf8"))
self.handler.end_headers()
except RedirectFound, e:
self.handler.send_response(302, 'Found')
self.handler.send_header('Location', e.args[0].encode("utf8"))
self.handler.end_headers()
except RedirectTemporary, e:
# ask browser not to cache this redirect
self.handler.send_response(307, 'Temporary Redirect')
self.handler.send_header('Location', e.args[0].encode("utf8"))
self.handler.send_header('Cache-Control', 'max-age=0')
self.handler.end_headers()
except BlockedIP:
msg = blocked_ip_message % self.__dict__
self.fail(msg, code=403, heading='Blocked IP')
except FormError, message:
message = str(message)
self.fail(message, code=400, heading='Error processing form')
except OpenIDError, message:
message = str(message)
self.fail(message, code=400, heading='Error processing OpenID request')
except OAuthError, message:
message = str(message)
self.fail(message, code=400, heading='Error processing OAuth request')
except IOError, error:
# ignore broken pipe errors (client vanished on us)
if error.errno != 32: raise
except OperationalError, message:
# clean things up
self.store.force_close()
message = str(message)
self.fail('Please try again later.\n<!-- %s -->'%message,
code=500, heading='Database connection failed')
except:
exc, value, tb = sys.exc_info()
real_tb = traceback.format_exc()
# attempt to send all the exceptions to Raven
try:
from raven.utils.serializer import transform
if self.sentry_client:
if self.form and not isinstance(self.form, FileUpload):
form_data = self.form
else:
form_data = ""
self.sentry_client.captureException(
data={
"sentry.interfaces.Http": {
"method": self.env.get("REQUEST_METHOD"),
"url": raven.utils.wsgi.get_current_url(
self.env,
strip_querystring=True,
),
"query_string": self.env.get(
"QUERY_STRING",
),
"data": transform(form_data),
"headers": dict(
raven.utils.wsgi.get_headers(self.env),
),
"env": dict(
raven.utils.wsgi.get_environ(self.env),
),
}
},
)
except Exception:
# sentry broke so just email the exception like old times
if ('connection limit exceeded for non-superusers'
not in str(value)):
logging.exception('Internal Error\n----\n%s\n----\n%s\n----\n' % (
'\n'.join(['%s: %s' % x for x in self.env.items()]),
real_tb,
))
if self.config.debug_mode == 'yes':
s = cStringIO.StringIO()
traceback.print_exc(None, s)
s = cgi.escape(s.getvalue())
self.fail('Internal Server Error', code=500,
heading='Error...', content='%s'%s)
else:
s = '%s: %s'%(exc, value)
self.fail("There's been a problem with your request",
code=500, heading='Error...', content='%s'%s)
finally:
self.store.close()
# these are inserted at the top of the standard template if set
error_message = None
ok_message = None
def write_plain(self, payload):
self.handler.send_response(200)
self.handler.send_header("Content-type", 'text/plain')
self.handler.send_header("Content-length", str(len(payload)))
self.handler.end_headers()
self.handler.wfile.write(payload)
def write_template(self, filename, headers={}, **options):
context = {}
options.setdefault('norobots', False)
options.setdefault('keywords', 'python programming language object'
' oriented web free source package index download software')
options.setdefault('description', 'The Python Package Index is a'
' repository of software for the Python programming language.')
options['providers'] = self.get_providers()
context['data'] = options
context['app'] = self
fpi = self.config.url+self.env.get('PATH_INFO',"")
try:
options['FULL_PATH_INFO'] = fpi.decode("utf-8")
except UnicodeError:
raise NotFound, fpi + ' is not utf-8 encoded'
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
context['standard_template'] = PyPiPageTemplate(
"standard_template.pt", template_dir)
template = PyPiPageTemplate(filename, template_dir)
content = template(**context)
# dynamic insertion of CSRF token into FORMs
if '"POST"' in content and self.authenticated:
token = '<input type="hidden" name="CSRFToken" value="%s">' % (
self.store.get_token(self.username),)
temp = content.split('\n')
edit = ((i, l) for i, l in enumerate(content.split('\n')) if
'"POST"' in l)
try:
for index, line in edit:
while not line.endswith('>'):
index += 1
line = temp[index]
# count spaces to align entry nicely
spaces = len(line.lstrip()) - len(line)
temp[index] = "\n".join((line, ' ' * spaces + token))
content = '\n'.join(temp)
except IndexError:
# this should not happen with correct HTML syntax
# the try is 'just in case someone does something stupid'
pass
self.handler.send_response(200, 'OK')
if 'content-type' in options:
self.handler.set_content_type(options['content-type'])
else:
self.handler.set_content_type('text/html; charset=utf-8')
if self.usercookie:
if self.url_machine.startswith('https'):
secure = ';secure'
else:
secure = ''
self.handler.send_header('Set-Cookie',
'pypi=%s;path=/%s' % (self.usercookie, secure))
for k,v in headers.items():
self.handler.send_header(k, v)
self.handler.end_headers()
self.wfile.write(content.encode('utf-8'))
def fail(self, message, title="Python Package Index", code=400,
heading=None, headers={}, content=''):
''' Indicate to the user that something has failed.
'''
if isinstance(message, unicode):
message = message.encode("utf-8")
self.handler.send_response(code, message)
if '<' in content and '>' in content:
html = True
self.handler.set_content_type('text/html; charset=utf-8')
else:
html = False
self.handler.set_content_type('text/plain; charset=utf-8')
for k,v in headers.items():
self.handler.send_header(k, v)
self.handler.end_headers()
if heading:
if html:
self.wfile.write('<strong>' + heading +
'</strong><br /><br />\n\n')
else:
self.wfile.write(heading + '\n\n')
self.wfile.write(message)
if html: self.wfile.write('<br /><br />\n')
else: self.wfile.write('\n\n')
self.wfile.write(content)
def link_action(self, action_name=None, **vars):
if action_name:
vars[':action'] = action_name
l = []
for k,v in vars.items():
l.append('%s=%s'%(urllib.quote(k.encode('utf-8')),
urllib.quote(v.encode('utf-8'))))
return self.url_path + '?' + '&'.join(l)
navlinks = (
('browse', 'Browse packages'),
('submit_form', 'Package submission'),
('list_classifiers', 'List trove classifiers'),
('rss', 'RSS (latest 40 updates)'),
('packages_rss', 'RSS (newest 40 packages)'),
('role_form', 'Admin'),
)
def navlinks_html(self):
links = []
for action_name, desc in self.navlinks:
desc = desc.replace(' ', ' ')
if action_name == 'role_form' and (
not self.username or not self.store.has_role('Admin', '')):
continue
cssclass = ''
if action_name == self.nav_current:
cssclass = 'selected'
links.append('<li class="%s"><a class="%s" href="%s">%s</a></li>' %
(cssclass, cssclass, self.link_action(action_name), desc))
return links
def inner_run(self):
''' Figure out what the request is, and farm off to the appropriate
handler.
'''
# See if this is the "simple" pages and signatures
script_name = self.env.get('SCRIPT_NAME')
if script_name and script_name == self.config.simple_script:
return self.run_simple()
if script_name and script_name == self.config.simple_sign_script:
return self.run_simple_sign()
# if script_name == '/packages':
# return self.packages()
if script_name == '/mirrors':
return self.mirrors()
if script_name == '/security':
return self.security()
if script_name == '/daytime':
return self.daytime()
if script_name == '/serial':
return self.current_serial()
if script_name == '/id':
return self.run_id()
if script_name == '/google_login':
return self.google_login()
# on logout, we set the cookie to "logged_out"
self.cookie = Cookie.SimpleCookie(self.env.get('HTTP_COOKIE', ''))
try:
self.usercookie = self.cookie['pypi'].value
except KeyError:
self.usercookie = None
name = self.store.find_user_by_cookie(self.usercookie)
if name:
self.loggedin = True
self.authenticated = True # implied by loggedin
self.username = name
# no login time update, since looking for the
# cookie did that already
self.store.set_user(name, self.remote_addr, False)
else:
# see if the user has provided a username/password
auth = self.env.get('HTTP_CGI_AUTHORIZATION', '').strip()
if auth:
if not self._check_blocked_ip():
try:
self._handle_basic_auth(auth)
except (Unauthorised, UserNotFound):
# if either an invalid user or password was set,
# increase the IP's failed login count
self._failed_login_ip()
else:
raise BlockedIP
else:
un = self.env.get('SSH_USER', '')
if un and self.store.has_user(un):
user = self.store.get_user(un)
self.username = un
self.authenticated = self.loggedin = True
last_login = user['last_login']
# Only update last_login every minute
update_last_login = not last_login or (time.time()-time.mktime(last_login.timetuple()) > 60)
self.store.set_user(un, self.remote_addr, update_last_login)
# Commit all user-related changes made up to here
if self.username:
self.store.commit()
# Now we have a username try running OAuth if necessary
if script_name == '/oauth':
raise Gone, "OAuth has been disabled."
if self.env.get('CONTENT_TYPE') == 'text/xml':
self.xmlrpc()
return
# now handle the request
path = self.env.get('PATH_INFO', '')
if self.form.has_key(':action'):
action = self.form[':action']
if isinstance(action, list):
raise RuntimeError("Multiple actions: %r" % action)
elif path:
# Split into path items, drop leading slash
try:
items = path.decode('utf-8').split('/')[1:]
except UnicodeError:
raise NotFound(path + " is not UTF-8 encoded")
action = None
if path == '/':
self.form['name'] = ''
action = 'index'
elif len(items) >= 1:
self.form['name'] = items[0]
action = 'display'
if len(items) >= 2 and items[1]:
self.form['version'] = items[1]
action = 'display'
if len(items) == 3 and items[2]:
action = self.form[':action'] = items[2]
if not action:
raise NotFound
else:
action = 'home'
if self.form.get('version') in ('doap', 'json'):
action, self.form['version'] = self.form['version'], None
# make sure the user has permission
if action in ('submit', ):
if not self.authenticated:
raise Unauthorised
if self.store.get_otk(self.username):
raise Unauthorised, "Incomplete registration; check your email"
if not self.store.user_active(self.username):
raise Unauthorised("Inactive User")
# handle the action
if action in '''home browse rss index search submit doap
display_pkginfo submit_pkg_info remove_pkg pkg_edit verify submit_form
display register_form user user_form
forgotten_password_form forgotten_password
password_reset pw_reset pw_reset_change
role role_form list_classifiers login logout files
file_upload show_md5 doc_upload claim openid openid_return dropid
clear_auth addkey delkey lasthour json gae_file about delete_user
rss_regen openid_endpoint openid_decide_post packages_rss
exception login_form purge'''.split():
getattr(self, action)()
else:
#raise NotFound, 'Unknown action %s' % action
raise NotFound
if action in 'file_upload submit submit_pkg_info pkg_edit remove_pkg'.split():
self.store.enqueue(tasks.rss_regen,)
# commit any database changes
self.store.commit()
def _check_credentials(self, username, password):
if not self.store.has_user(username):
raise UserNotFound
if self._check_blocked_user(username):
username = password = ''
raise UserNotFound
# Fetch the user from the database
user = self.store.get_user(username)
# Verify the hash, and see if it needs migrated
ok, new_hash = self.config.passlib.verify_and_update(password, user["password"])
# If our password didn't verify as ok then raise an
# error.
if not ok:
self._failed_login_user(username)
raise Unauthorised, 'Incorrect password'
if new_hash:
# The new hash needs to be stored for this user.
self.store.setpasswd(username, new_hash, hashed=True)
# Login the user
self.username = username
self.authenticated = True
# Determine if we need to store the users last login,
# as we only want to do this once a minute.
last_login = user['last_login']
update_last_login = not last_login or (time.time()-time.mktime(last_login.timetuple()) > 60)
self.store.set_user(username, self.remote_addr, update_last_login)
def _handle_basic_auth(self, auth):
if not auth.lower().startswith('basic '):
return
authtype, auth = auth.split(None, 1)
try:
username, password = base64.decodestring(auth).split(':', 1)
except (binascii.Error, ValueError):
# Invalid base64, or no colon
username = password = ''
self._check_credentials(username, password)
self.statsd.incr('password_authentication.basic_auth')
def login_form(self):
if self.env['REQUEST_METHOD'] == "POST":
nonce = self.form.get('nonce', '')
username = self.form.get('username', '')
password = self.form.get('password', '')
cookies = dict([(k, v.value) for k, v in Cookie.SimpleCookie(self.env.get('HTTP_COOKIE', '')).items()])
if nonce != cookies.get('login_nonce', None):
raise FormError, "Form Failure; reset form submission"
if not self._check_blocked_ip():
try:
self._check_credentials(username, password)
except (Unauthorised, UserNotFound):
self._failed_login_ip()
raise UnauthorisedForm, 'Incorrect password'
self.home()
else:
raise BlockedIP
self.statsd.incr('password_authentication.login_form')
self.usercookie = self.store.create_cookie(self.username)
self.store.get_token(self.username)
self.loggedin = 1
self.home()
elif self.env['REQUEST_METHOD'] == "GET":
nonce = store.generate_random(30)
headers = {'Set-Cookie': 'login_nonce=%s;secure' % (nonce),
'X-FRAME-OPTIONS': 'DENY'}
self.write_template('login.pt', title="PyPI Login",
headers=headers, nonce=nonce)
else:
self.handler.send_response(405, 'Method Not Allowed')
def _failed_login_ip(self):
if self.block_redis:
if not self.block_redis.exists(self.remote_addr):
self.block_redis.set(self.remote_addr, 1)
self.block_redis.expire(self.remote_addr,
int(self.config.blocked_timeout))
else:
self.block_redis.incr(self.remote_addr)
def _failed_login_user(self, username):
if self.block_redis:
if not self.block_redis.exists(username):
self.block_redis.set(username, 1)
self.block_redis.expire(username,
int(self.config.blocked_timeout))
else:
self.block_redis.incr(username)
def _check_blocked_ip(self):
if self.block_redis:
if (self.block_redis.exists(self.remote_addr) and
int(self.block_redis.get(self.remote_addr)) >
int(self.config.blocked_attempts_ip)):
return True
return False
def _check_blocked_user(self, username):
if self.block_redis:
if (self.block_redis.exists(username) and
int(self.block_redis.get(username)) >
int(self.config.blocked_attempts_user)):
return True
return False
def exception(self):
FAIL
@must_tls
def xmlrpc(self):