936
881
"""Set a per-branch configuration option"""
937
882
self.branch.lock_write()
939
self._config.set_option(value, name, section)
884
cfg_obj = self._get_config()
889
obj = cfg_obj[section]
891
cfg_obj[section] = {}
892
obj = cfg_obj[section]
894
out_file = StringIO()
895
cfg_obj.write(out_file)
897
self.branch.control_files.put('branch.conf', out_file)
941
899
self.branch.unlock()
944
class AuthenticationConfig(object):
945
"""The authentication configuration file based on a ini file.
947
Implements the authentication.conf file described in
948
doc/developers/authentication-ring.txt.
951
def __init__(self, _file=None):
952
self._config = None # The ConfigObj
954
self._filename = authentication_config_filename()
955
self._input = self._filename = authentication_config_filename()
957
# Tests can provide a string as _file
958
self._filename = None
961
def _get_config(self):
962
if self._config is not None:
965
# FIXME: Should we validate something here ? Includes: empty
966
# sections are useless, at least one of
967
# user/password/password_encoding should be defined, etc.
969
# Note: the encoding below declares that the file itself is utf-8
970
# encoded, but the values in the ConfigObj are always Unicode.
971
self._config = ConfigObj(self._input, encoding='utf-8')
972
except configobj.ConfigObjError, e:
973
raise errors.ParseConfigError(e.errors, e.config.filename)
977
"""Save the config file, only tests should use it for now."""
978
conf_dir = os.path.dirname(self._filename)
979
ensure_config_dir_exists(conf_dir)
980
self._get_config().write(file(self._filename, 'wb'))
982
def _set_option(self, section_name, option_name, value):
983
"""Set an authentication configuration option"""
984
conf = self._get_config()
985
section = conf.get(section_name)
988
section = conf[section]
989
section[option_name] = value
992
def get_credentials(self, scheme, host, port=None, user=None, path=None,
994
"""Returns the matching credentials from authentication.conf file.
996
:param scheme: protocol
998
:param host: the server address
1000
:param port: the associated port (optional)
1002
:param user: login (optional)
1004
:param path: the absolute path on the server (optional)
1006
:param realm: the http authentication realm (optional)
1008
:return: A dict containing the matching credentials or None.
1010
- name: the section name of the credentials in the
1011
authentication.conf file,
1012
- user: can't be different from the provided user if any,
1013
- scheme: the server protocol,
1014
- host: the server address,
1015
- port: the server port (can be None),
1016
- path: the absolute server path (can be None),
1017
- realm: the http specific authentication realm (can be None),
1018
- password: the decoded password, could be None if the credential
1019
defines only the user
1020
- verify_certificates: https specific, True if the server
1021
certificate should be verified, False otherwise.
1024
for auth_def_name, auth_def in self._get_config().items():
1025
if type(auth_def) is not configobj.Section:
1026
raise ValueError("%s defined outside a section" % auth_def_name)
1028
a_scheme, a_host, a_user, a_path = map(
1029
auth_def.get, ['scheme', 'host', 'user', 'path'])
1032
a_port = auth_def.as_int('port')
1036
raise ValueError("'port' not numeric in %s" % auth_def_name)
1038
a_verify_certificates = auth_def.as_bool('verify_certificates')
1040
a_verify_certificates = True
1043
"'verify_certificates' not boolean in %s" % auth_def_name)
1046
if a_scheme is not None and scheme != a_scheme:
1048
if a_host is not None:
1049
if not (host == a_host
1050
or (a_host.startswith('.') and host.endswith(a_host))):
1052
if a_port is not None and port != a_port:
1054
if (a_path is not None and path is not None
1055
and not path.startswith(a_path)):
1057
if (a_user is not None and user is not None
1058
and a_user != user):
1059
# Never contradict the caller about the user to be used
1064
# Prepare a credentials dictionary with additional keys
1065
# for the credential providers
1066
credentials = dict(name=auth_def_name,
1073
password=auth_def.get('password', None),
1074
verify_certificates=a_verify_certificates)
1075
# Decode the password in the credentials (or get one)
1076
self.decode_password(credentials,
1077
auth_def.get('password_encoding', None))
1078
if 'auth' in debug.debug_flags:
1079
trace.mutter("Using authentication section: %r", auth_def_name)
1084
def set_credentials(self, name, host, user, scheme=None, password=None,
1085
port=None, path=None, verify_certificates=None,
1087
"""Set authentication credentials for a host.
1089
Any existing credentials with matching scheme, host, port and path
1090
will be deleted, regardless of name.
1092
:param name: An arbitrary name to describe this set of credentials.
1093
:param host: Name of the host that accepts these credentials.
1094
:param user: The username portion of these credentials.
1095
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1097
:param password: Password portion of these credentials.
1098
:param port: The IP port on the host that these credentials apply to.
1099
:param path: A filesystem path on the host that these credentials
1101
:param verify_certificates: On https, verify server certificates if
1103
:param realm: The http authentication realm (optional).
1105
values = {'host': host, 'user': user}
1106
if password is not None:
1107
values['password'] = password
1108
if scheme is not None:
1109
values['scheme'] = scheme
1110
if port is not None:
1111
values['port'] = '%d' % port
1112
if path is not None:
1113
values['path'] = path
1114
if verify_certificates is not None:
1115
values['verify_certificates'] = str(verify_certificates)
1116
if realm is not None:
1117
values['realm'] = realm
1118
config = self._get_config()
1120
for section, existing_values in config.items():
1121
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1122
if existing_values.get(key) != values.get(key):
1126
config.update({name: values})
1129
def get_user(self, scheme, host, port=None,
1130
realm=None, path=None, prompt=None):
1131
"""Get a user from authentication file.
1133
:param scheme: protocol
1135
:param host: the server address
1137
:param port: the associated port (optional)
1139
:param realm: the realm sent by the server (optional)
1141
:param path: the absolute path on the server (optional)
1143
:return: The found user.
1145
credentials = self.get_credentials(scheme, host, port, user=None,
1146
path=path, realm=realm)
1147
if credentials is not None:
1148
user = credentials['user']
1153
def get_password(self, scheme, host, user, port=None,
1154
realm=None, path=None, prompt=None):
1155
"""Get a password from authentication file or prompt the user for one.
1157
:param scheme: protocol
1159
:param host: the server address
1161
:param port: the associated port (optional)
1165
:param realm: the realm sent by the server (optional)
1167
:param path: the absolute path on the server (optional)
1169
:return: The found password or the one entered by the user.
1171
credentials = self.get_credentials(scheme, host, port, user, path,
1173
if credentials is not None:
1174
password = credentials['password']
1175
if password is not None and scheme is 'ssh':
1176
trace.warning('password ignored in section [%s],'
1177
' use an ssh agent instead'
1178
% credentials['name'])
1182
# Prompt user only if we could't find a password
1183
if password is None:
1185
# Create a default prompt suitable for most cases
1186
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1187
# Special handling for optional fields in the prompt
1188
if port is not None:
1189
prompt_host = '%s:%d' % (host, port)
1192
password = ui.ui_factory.get_password(prompt,
1193
host=prompt_host, user=user)
1196
def decode_password(self, credentials, encoding):
1198
cs = credential_store_registry.get_credential_store(encoding)
1200
raise ValueError('%r is not a known password_encoding' % encoding)
1201
credentials['password'] = cs.decode_password(credentials)
1205
class CredentialStoreRegistry(registry.Registry):
1206
"""A class that registers credential stores.
1208
A credential store provides access to credentials via the password_encoding
1209
field in authentication.conf sections.
1211
Except for stores provided by bzr itself,most stores are expected to be
1212
provided by plugins that will therefore use
1213
register_lazy(password_encoding, module_name, member_name, help=help,
1214
info=info) to install themselves.
1217
def get_credential_store(self, encoding=None):
1218
cs = self.get(encoding)
1224
credential_store_registry = CredentialStoreRegistry()
1227
class CredentialStore(object):
1228
"""An abstract class to implement storage for credentials"""
1230
def decode_password(self, credentials):
1231
"""Returns a password for the provided credentials in clear text."""
1232
raise NotImplementedError(self.decode_password)
1235
class PlainTextCredentialStore(CredentialStore):
1236
"""Plain text credential store for the authentication.conf file."""
1238
def decode_password(self, credentials):
1239
"""See CredentialStore.decode_password."""
1240
return credentials['password']
1243
credential_store_registry.register('plain', PlainTextCredentialStore,
1244
help=PlainTextCredentialStore.__doc__)
1245
credential_store_registry.default_key = 'plain'
1248
class BzrDirConfig(object):
1250
def __init__(self, transport):
1251
self._config = TransportConfig(transport, 'control.conf')
1253
def set_default_stack_on(self, value):
1254
"""Set the default stacking location.
1256
It may be set to a location, or None.
1258
This policy affects all branches contained by this bzrdir, except for
1259
those under repositories.
1262
self._config.set_option('', 'default_stack_on')
1264
self._config.set_option(value, 'default_stack_on')
1266
def get_default_stack_on(self):
1267
"""Return the default stacking location.
1269
This will either be a location, or None.
1271
This policy affects all branches contained by this bzrdir, except for
1272
those under repositories.
1274
value = self._config.get_option('default_stack_on')
1280
class TransportConfig(object):
1281
"""A Config that reads/writes a config file on a Transport.
1283
It is a low-level object that considers config data to be name/value pairs
1284
that may be associated with a section. Assigning meaning to the these
1285
values is done at higher levels like TreeConfig.
1288
def __init__(self, transport, filename):
1289
self._transport = transport
1290
self._filename = filename
1292
def get_option(self, name, section=None, default=None):
1293
"""Return the value associated with a named option.
1295
:param name: The name of the value
1296
:param section: The section the option is in (if any)
1297
:param default: The value to return if the value is not set
1298
:return: The value or default value
1300
configobj = self._get_configobj()
1302
section_obj = configobj
1305
section_obj = configobj[section]
1308
return section_obj.get(name, default)
1310
def set_option(self, value, name, section=None):
1311
"""Set the value associated with a named option.
1313
:param value: The value to set
1314
:param name: The name of the value to set
1315
:param section: The section the option is in (if any)
1317
configobj = self._get_configobj()
1319
configobj[name] = value
1321
configobj.setdefault(section, {})[name] = value
1322
self._set_configobj(configobj)
1324
def _get_configobj(self):
1326
return ConfigObj(self._transport.get(self._filename),
1328
except errors.NoSuchFile:
1329
return ConfigObj(encoding='utf-8')
1331
def _set_configobj(self, configobj):
1332
out_file = StringIO()
1333
configobj.write(out_file)
1335
self._transport.put_file(self._filename, out_file)