use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.
the class OAuthSessionOverOpenID method authenticateAndRedirect.
private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
com.google.gerrit.server.account.AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
AuthResult arsp;
try {
String claimedIdentifier = user.getClaimedIdentity();
Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
Optional<Account.Id> claimedId = Optional.empty();
// That why we query it here, not to lose linking mode.
if (!Strings.isNullOrEmpty(claimedIdentifier)) {
claimedId = accountManager.lookup(claimedIdentifier);
if (!claimedId.isPresent()) {
logger.atFine().log("Claimed identity is unknown");
}
}
// and user account exists for this identity
if (claimedId.isPresent()) {
logger.atFine().log("Claimed identity is set and is known");
if (actualId.isPresent()) {
if (claimedId.get().equals(actualId.get())) {
// Both link to the same account, that's what we expected.
logger.atFine().log("Both link to the same account. All is fine.");
} else {
// This is (for now) a fatal error. There are two records
// for what might be the same user. The admin would have to
// link the accounts manually.
logger.atFine().log("OAuth accounts disagree over user identity:\n" + " Claimed ID: %s is %s\n" + " Delgate ID: %s is %s", claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
} else {
// Claimed account already exists: link to it.
logger.atFine().log("Claimed account already exists: link to it.");
try {
accountManager.link(claimedId.get(), areq);
} catch (ConfigInvalidException e) {
logger.atSevere().log("Cannot link: %s to user identity:\n Claimed ID: %s is %s", user.getExternalId(), claimedId.get(), claimedIdentifier);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
}
} else if (linkMode) {
// Use case 2: link mode activated from the UI
Account.Id accountId = identifiedUser.get().getAccountId();
try {
logger.atFine().log("Linking \"%s\" to \"%s\"", user.getExternalId(), accountId);
accountManager.link(accountId, areq);
} catch (ConfigInvalidException e) {
logger.atSevere().log("Cannot link: %s to user identity: %s", user.getExternalId(), accountId);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
} finally {
linkMode = false;
}
}
areq.setUserName(user.getUserName());
areq.setEmailAddress(user.getEmailAddress());
areq.setDisplayName(user.getDisplayName());
arsp = accountManager.authenticate(areq);
} catch (AccountException e) {
logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
webSession.get().login(arsp, true);
StringBuilder rdr = new StringBuilder(urlProvider.get(req));
rdr.append(Url.decode(redirectToken));
rsp.sendRedirect(rdr.toString());
}
use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.
the class CreateGroupPermissionSyncer method syncIfNeeded.
/**
* Checks if {@code GlobalCapability.CREATE_GROUP} and {@code CREATE} permission on {@code
* refs/groups/*} have diverged and syncs them by applying the {@code CREATE} permission to {@code
* refs/groups/*}.
*/
public void syncIfNeeded() throws IOException, ConfigInvalidException {
ProjectState allProjectsState = projectCache.getAllProjects();
ProjectState allUsersState = projectCache.getAllUsers();
Set<PermissionRule> createGroupsGlobal = new HashSet<>(allProjectsState.getCapabilityCollection().createGroup);
Set<PermissionRule> createGroupsRef = new HashSet<>();
Optional<AccessSection> allUsersCreateGroupAccessSection = allUsersState.getConfig().getAccessSection(RefNames.REFS_GROUPS + "*");
if (allUsersCreateGroupAccessSection.isPresent()) {
Permission create = allUsersCreateGroupAccessSection.get().getPermission(Permission.CREATE);
if (create != null && create.getRules() != null) {
createGroupsRef.addAll(create.getRules());
}
}
if (Sets.symmetricDifference(createGroupsGlobal, createGroupsRef).isEmpty()) {
// Nothing to sync
return;
}
try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsers)) {
ProjectConfig config = projectConfigFactory.read(md);
config.upsertAccessSection(RefNames.REFS_GROUPS + "*", refsGroupsAccessSectionBuilder -> {
if (createGroupsGlobal.isEmpty()) {
refsGroupsAccessSectionBuilder.modifyPermissions(permissions -> {
permissions.removeIf(p -> Permission.CREATE.equals(p.getName()));
});
} else {
// The create permission is managed by Gerrit at this point only so there is no
// concern of overwriting user-defined permissions here.
Permission.Builder createGroupPermission = Permission.builder(Permission.CREATE);
refsGroupsAccessSectionBuilder.remove(createGroupPermission);
refsGroupsAccessSectionBuilder.addPermission(createGroupPermission);
createGroupsGlobal.stream().map(p -> p.toBuilder()).forEach(createGroupPermission::add);
}
});
config.commit(md);
projectCache.evictAndReindex(config.getProject());
}
}
use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.
the class InitJGitConfig method run.
@Override
public void run() {
ui.header("JGit Configuration");
FileBasedConfig jgitConfig = new FileBasedConfig(sitePaths.jgit_config.toFile(), FS.DETECTED);
try {
jgitConfig.load();
if (!jgitConfig.getNames(ConfigConstants.CONFIG_RECEIVE_SECTION).contains(ConfigConstants.CONFIG_KEY_AUTOGC)) {
jgitConfig.setBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOGC, false);
jgitConfig.save();
ui.error("Auto-configured \"receive.autogc = false\" to disable auto-gc after" + " git-receive-pack.");
} else if (jgitConfig.getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION, ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
ui.error("WARNING: JGit option \"receive.autogc = true\". This is not recommended in Gerrit.\n" + "git-receive-pack will run auto gc after receiving data from " + "git-push and updating refs.\n" + "Disable this behavior to avoid the additional load it creates: " + "gc should be configured in gc config section or run as a separate process.");
}
if (jgitConfig.getNames(ConfigConstants.CONFIG_PROTOCOL_SECTION).contains(ConfigConstants.CONFIG_KEY_VERSION)) {
String version = jgitConfig.getString(ConfigConstants.CONFIG_PROTOCOL_SECTION, null, ConfigConstants.CONFIG_KEY_VERSION);
if (!TransferConfig.ProtocolVersion.V2.version().equals(version)) {
ui.error("HINT: JGit option \"%s.%s = %s\". It's recommended to activate git\n" + "wire protocol version 2 to improve git fetch performance.", ConfigConstants.CONFIG_PROTOCOL_SECTION, ConfigConstants.CONFIG_KEY_VERSION, version);
}
}
} catch (IOException e) {
throw die(String.format("Handling JGit configuration %s failed", sitePaths.jgit_config), e);
} catch (ConfigInvalidException e) {
throw die(String.format("Invalid JGit configuration %s", sitePaths.jgit_config), e);
}
}
use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.
the class AccountManager method create.
private AuthResult create(AuthRequest who) throws AccountException, IOException, ConfigInvalidException {
Account.Id newId = Account.id(sequences.nextAccountId());
logger.atFine().log("Assigning new Id %s to account", newId);
ExternalId extId = externalIdFactory.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
logger.atFine().log("Created external Id: %s", extId);
checkEmailNotUsed(newId, extId);
ExternalId userNameExtId = who.getUserName().isPresent() ? createUsername(newId, who.getUserName().get()) : null;
boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && !accounts.hasAnyAccount();
AccountState accountState;
try {
accountState = accountsUpdateProvider.get().insert("Create Account on First Login", newId, u -> {
u.setFullName(who.getDisplayName()).setPreferredEmail(extId.email()).addExternalId(extId);
if (userNameExtId != null) {
u.addExternalId(userNameExtId);
}
});
} catch (DuplicateExternalIdKeyException e) {
throw new AccountException("Cannot assign external ID \"" + e.getDuplicateKey().get() + "\" to account " + newId + "; external ID already in use.");
} finally {
// If adding the account failed, it may be that it actually was the
// first account. So we reset the 'check for first account'-guard, as
// otherwise the first account would not get administration permissions.
awaitsFirstAccountCheck.set(isFirstAccount);
}
if (userNameExtId != null) {
who.getUserName().ifPresent(sshKeyCache::evict);
}
IdentifiedUser user = userFactory.create(newId);
if (isFirstAccount) {
// This is the first user account on our site. Assume this user
// is going to be the site's administrator and just make them that
// to bootstrap the authentication database.
//
Permission admin = projectCache.getAllProjects().getConfig().getAccessSection(AccessSection.GLOBAL_CAPABILITIES).orElseThrow(() -> new IllegalStateException("access section does not exist")).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
AccountGroup.UUID adminGroupUuid = admin.getRules().get(0).getGroup().getUUID();
addGroupMember(adminGroupUuid, user);
}
realm.onCreateAccount(who, accountState.account());
return new AuthResult(newId, extId.key(), true);
}
use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.
the class AccountIdHandler method parseArguments.
@Override
public int parseArguments(Parameters params) throws CmdLineException {
String token = params.getParameter(0);
Account.Id accountId;
try {
try {
accountId = accountResolver.resolve(token).asUnique().account().id();
} catch (UnprocessableEntityException e) {
switch(authType) {
case HTTP_LDAP:
case CLIENT_SSL_CERT_LDAP:
case LDAP:
accountId = createAccountByLdap(token);
break;
case CUSTOM_EXTENSION:
case DEVELOPMENT_BECOME_ANY_ACCOUNT:
case HTTP:
case LDAP_BIND:
case OAUTH:
case OPENID:
case OPENID_SSO:
default:
String msg = "user \"%s\" not found";
logger.atSevere().withCause(e).log(msg, token);
throw new CmdLineException(owner, localizable(msg), token);
}
}
} catch (StorageException e) {
CmdLineException newException = new CmdLineException(owner, localizable("database is down"));
newException.initCause(e);
throw newException;
} catch (IOException e) {
throw new CmdLineException(owner, "Failed to load account", e);
} catch (ConfigInvalidException e) {
throw new CmdLineException(owner, "Invalid account config", e);
}
setter.addValue(accountId);
return 1;
}
Aggregations