Search in sources :

Example 26 with RepositoryException

use of org.platformlayer.RepositoryException in project platformlayer by platformlayer.

the class RegistrationServiceImpl method registerUser.

@Override
public OpsUser registerUser(String username, String password) throws CustomerFacingException {
    if (Strings.isNullOrEmpty(username)) {
        throw CustomerFacingException.buildRequiredField("username");
    }
    if (Strings.isNullOrEmpty(password)) {
        throw CustomerFacingException.buildRequiredField("password");
    }
    password = password.trim();
    username = username.trim();
    checkPassword(password);
    checkUsername(username);
    OpsUser user;
    try {
        user = repository.findUser(username);
        if (user != null) {
            // TODO: Should we hide this fact?
            throw CustomerFacingException.buildFieldError("username", "duplicate", "Username is already registered");
        }
        user = repository.createUser(username, password, null);
        // TODO: We reserve @@, to prevent collisions
        // TODO: Is this good enough? What if project already exists?
        String projectKey = "user@@" + username.toLowerCase();
        repository.createProject(projectKey, user);
    } catch (RepositoryException e) {
        log.warn("Repository error creating user", e);
        throw CustomerFacingException.wrap(e);
    }
    return user;
}
Also used : OpsUser(org.platformlayer.auth.OpsUser) RepositoryException(org.platformlayer.RepositoryException)

Example 27 with RepositoryException

use of org.platformlayer.RepositoryException in project platformlayer by platformlayer.

the class ClientCertificateSystemAuthenticator method authenticate.

@Override
public ServiceAccountEntity authenticate(CertificateChainInfo certChainInfo) throws AuthenticatorException {
    if (certChainInfo.certificates.size() == 0) {
        log.debug("Chain empty; can't authenticate");
        return null;
    }
    // If it's a single cert; we check the cert.
    // Otherwise, we assume a CA signed the tail cert, so we check the penultimate cert
    CertificateInfo inspect;
    if (certChainInfo.certificates.size() == 1) {
        inspect = certChainInfo.certificates.get(0);
    } else {
        inspect = certChainInfo.certificates.get(1);
    }
    String subject = inspect.subjectDN;
    if (Strings.isNullOrEmpty(inspect.publicKey)) {
        throw new IllegalArgumentException();
    }
    byte[] publicKey = Hex.fromHex(inspect.publicKey);
    ServiceAccountEntity auth;
    try {
        auth = repository.findServiceAccount(subject, publicKey);
    } catch (RepositoryException e) {
        throw new AuthenticatorException("Error while authenticating user", e);
    }
    if (auth == null) {
        log.debug("Certificate validation failed (though the caller was authenticated)");
        log.debug("Certificate validation failed - public key not recognized: " + Hex.toHex(publicKey));
        log.debug("Certificate validation failed - chain: " + certChainInfo);
    }
    return auth;
}
Also used : CertificateInfo(org.platformlayer.auth.model.CertificateInfo) AuthenticatorException(org.platformlayer.auth.AuthenticatorException) ServiceAccountEntity(org.platformlayer.auth.ServiceAccountEntity) RepositoryException(org.platformlayer.RepositoryException)

Example 28 with RepositoryException

use of org.platformlayer.RepositoryException in project platformlayer by platformlayer.

the class KeystoneRepositoryAuthenticator method findUserFromKeychain.

@Override
public UserEntity findUserFromKeychain(CertificateChainInfo chain, boolean unlock) throws AuthenticatorException {
    if (chain.certificates == null || chain.certificates.isEmpty()) {
        return null;
    }
    for (int i = 0; i < chain.certificates.size(); i++) {
        String publicKeyHash = chain.certificates.get(i).publicKeyHash;
        if (Strings.isNullOrEmpty(publicKeyHash)) {
            continue;
        }
        log.debug("Checking publicKeyHash: " + publicKeyHash);
        byte[] hash = Hex.fromHex(publicKeyHash);
        UserEntity user;
        try {
            user = repository.findUserByPublicKey(hash);
        } catch (RepositoryException e) {
            throw new AuthenticatorException("Error while authenticating user", e);
        }
        if (user != null) {
            return user;
        }
    }
    return null;
}
Also used : AuthenticatorException(org.platformlayer.auth.AuthenticatorException) RepositoryException(org.platformlayer.RepositoryException) UserEntity(org.platformlayer.auth.UserEntity)

Example 29 with RepositoryException

use of org.platformlayer.RepositoryException in project platformlayer by platformlayer.

the class OperationWorker method doOperation.

Object doOperation() throws OpsException {
    final Action action = activeJob.getAction();
    final PlatformLayerKey targetItemKey = activeJob.getTargetItemKey();
    RenameThread rename = new RenameThread(action.getClass().getSimpleName() + " " + targetItemKey);
    try {
        OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
        final ProjectAuthorization project = activeJob.getProjectAuthorization();
        final OpsContext opsContext = opsContextBuilder.buildOpsContext(activeJob);
        final ServiceType serviceType = activeJob.getServiceType();
        final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
        try {
            return OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {

                @Override
                public Object call() throws Exception {
                    log.info("Starting job");
                    activeJob.setState(JobState.RUNNING);
                    ItemBase item;
                    ManagedItemRepository repository = opsSystem.getManagedItemRepository();
                    try {
                        boolean fetchTags = true;
                        item = repository.getManagedItem(targetItemKey, fetchTags, SecretProvider.from(project));
                    } catch (RepositoryException e) {
                        throw new OpsException("Error reading item from repository", e);
                    }
                    if (item == null) {
                        throw new WebApplicationException(404);
                    }
                    List<Object> scopeItems = Lists.newArrayList();
                    addActionScopeItems(action, item, scopeItems);
                    Object controller = serviceProvider.getController(item);
                    scopeItems.add(item);
                    scopeItems.add(action);
                    BindingScope scope = BindingScope.push(scopeItems);
                    opsContext.recurseOperation(scope, controller);
                    // TODO: Should we run a verify operation before -> ACTIVE??
                    // (we need to fix the states as well)
                    ManagedItemState newState = finishAction(action, scope);
                    if (newState != null) {
                        repository.changeState(targetItemKey, newState);
                        item.state = newState;
                    }
                    log.info("Job finished with SUCCESS");
                    activeJob.setState(JobState.SUCCESS);
                    return null;
                }

                private ManagedItemState finishAction(Action action, BindingScope scope) throws OpsException {
                    ManagedItemState newState = null;
                    if (action instanceof ConfigureAction) {
                        newState = ManagedItemState.ACTIVE;
                    }
                    if (action instanceof ValidateAction) {
                    // TODO: Change state to healthy??
                    }
                    if (action instanceof DeleteAction) {
                        newState = ManagedItemState.DELETED;
                    }
                    if (action instanceof BackupAction) {
                        BackupContext backupContext = scope.getInstance(BackupContext.class);
                        backupContext.writeDescriptor();
                    }
                    return newState;
                }

                private void addActionScopeItems(Action action, ItemBase item, List<Object> scopeItems) throws OpsException {
                    if (action instanceof BackupAction) {
                        // TODO: Don't hard-code this
                        BackupHelpers backupHelpers = opsSystem.getInjector().getInstance(BackupHelpers.class);
                        BackupContext backupContext = backupHelpers.createBackupContext(item);
                        scopeItems.add(backupContext);
                    }
                }
            });
        } catch (Throwable e) {
            log.warn("Error running operation", e);
            log.warn("Job finished with FAILED");
            // boolean isDone = false; // We will retry
            activeJob.setState(JobState.FAILED);
            TimeSpan retry = null;
            HasRetryInfo retryInfo = ExceptionHelpers.findRetryInfo(e);
            if (retryInfo != null) {
                retry = retryInfo.getRetry();
            }
            if (retry == null) {
                // TODO: Eventually give up??
                retry = ApplicationMode.isDevelopment() ? TimeSpan.ONE_MINUTE : TimeSpan.FIVE_MINUTES;
            }
            // TODO: State transition??
            // managedItem.setState(ManagedItemState.ACTIVE, true);
            log.warn("Scheduling retry in " + retry);
            activeJob.enqueueRetry(retry);
            return null;
        } finally {
            try {
                activeJob.recordJobEnd();
            } catch (OpsException e) {
                log.error("Error recording job in registry", e);
            }
        }
    } finally {
        IoUtils.safeClose(rename);
    }
}
Also used : ValidateAction(org.platformlayer.core.model.ValidateAction) ConfigureAction(org.platformlayer.core.model.ConfigureAction) DeleteAction(org.platformlayer.core.model.DeleteAction) BackupAction(org.platformlayer.core.model.BackupAction) Action(org.platformlayer.core.model.Action) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) BackupHelpers(org.platformlayer.ops.backups.BackupHelpers) ManagedItemRepository(org.platformlayer.xaas.repository.ManagedItemRepository) OpsContext(org.platformlayer.ops.OpsContext) TimeSpan(com.fathomdb.TimeSpan) BackupAction(org.platformlayer.core.model.BackupAction) ServiceType(org.platformlayer.ids.ServiceType) BackupContext(org.platformlayer.ops.backups.BackupContext) HasRetryInfo(org.platformlayer.exceptions.HasRetryInfo) List(java.util.List) BindingScope(org.platformlayer.ops.BindingScope) ConfigureAction(org.platformlayer.core.model.ConfigureAction) ItemBase(org.platformlayer.core.model.ItemBase) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) DeleteAction(org.platformlayer.core.model.DeleteAction) ValidateAction(org.platformlayer.core.model.ValidateAction) ManagedItemState(org.platformlayer.core.model.ManagedItemState)

Example 30 with RepositoryException

use of org.platformlayer.RepositoryException in project platformlayer by platformlayer.

the class OpsContextBuilder method buildOpsContext.

public OpsContext buildOpsContext(ActiveJobExecution activeJob) throws OpsException {
    ServiceType serviceType = activeJob.getServiceType();
    ProjectAuthorization projectAuthz = activeJob.getProjectAuthorization();
    List<ProjectAuthorization> projects = Lists.newArrayList();
    // .getProject();
    ProjectAuthorization runAsProject = projectAuthz;
    projects.add(runAsProject);
    MultitenantConfiguration multitenant = opsSystem.getMultitenantConfiguration();
    if (multitenant != null) {
        ProjectAuthorization masterProject = multitenant.getMasterProject();
        if (runAsProject.getName().equals(masterProject.getName())) {
            // We're in the master project
            multitenant = null;
        } else {
            runAsProject = masterProject;
            projects.add(runAsProject);
        }
    }
    TypedPlatformLayerClient defaultClient = buildClient(runAsProject);
    FederationConfiguration federationMapConfig = FederatedPlatformLayerClient.buildFederationConfiguration(defaultClient);
    FederationMap federationMap = new FederationMap(httpStrategy, mapper, federationMapConfig);
    if (multitenant != null) {
        // .getProject();
        ProjectAuthorization localProject = projectAuthz;
        TypedPlatformLayerClient localClient = buildClient(localProject);
        FederationKey host = FederationKey.LOCAL;
        ProjectId project = localClient.getProject();
        FederationMapping mapKey = new FederationMapping(host, project);
        federationMap.addMapping(mapKey, localClient);
        for (PlatformLayerKey mappedService : multitenant.getMappedItems()) {
            FederationMap.Rule rule = new FederationMap.Rule();
            rule.mappedItems = mappedService;
            rule.targetKey = mapKey;
            federationMap.addRule(rule);
        }
    }
    ProjectId runAsProjectId = new ProjectId(runAsProject.getName());
    PlatformLayerClient platformLayerClient;
    if (federationMap.isEmpty()) {
        platformLayerClient = defaultClient;
    } else {
        federationMap.addDefault(defaultClient);
        platformLayerClient = FederatedPlatformLayerClient.build(runAsProjectId, federationMap);
    }
    ServiceConfiguration serviceConfiguration = new ServiceConfiguration(runAsProjectId, serviceType);
    ServiceAuthorization serviceAuthorization;
    try {
        serviceAuthorization = serviceAuthorizationService.findServiceAuthorization(serviceType, runAsProjectId);
        // }
        if (serviceAuthorization == null) {
            serviceAuthorization = new ServiceAuthorization();
            serviceAuthorization.serviceType = serviceConfiguration.getServiceType().getKey();
        }
    } catch (RepositoryException e) {
        throw new OpsException("Error reading from repository", e);
    }
    // OpsConfig opsConfig = OpsConfig.build(serviceAuthorization);
    // UserInfo userInfo = new SimpleUserInfo(auth, opsConfig);
    OpsContext opsContext = new OpsContext(opsSystem, activeJob, serviceConfiguration, platformLayerClient, projects);
    return opsContext;
}
Also used : TypedPlatformLayerClient(org.platformlayer.TypedPlatformLayerClient) OpsException(org.platformlayer.ops.OpsException) ProjectId(org.platformlayer.ids.ProjectId) FederationMap(org.platformlayer.federation.FederationMap) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) OpsContext(org.platformlayer.ops.OpsContext) MultitenantConfiguration(org.platformlayer.ops.MultitenantConfiguration) FederationKey(org.platformlayer.ids.FederationKey) ServiceAuthorization(org.platformlayer.xaas.model.ServiceAuthorization) DirectPlatformLayerClient(org.platformlayer.ops.DirectPlatformLayerClient) FederatedPlatformLayerClient(org.platformlayer.federation.FederatedPlatformLayerClient) PlatformLayerClient(org.platformlayer.PlatformLayerClient) TypedPlatformLayerClient(org.platformlayer.TypedPlatformLayerClient) FederationConfiguration(org.platformlayer.federation.model.FederationConfiguration) ServiceConfiguration(org.platformlayer.ops.ServiceConfiguration) ServiceType(org.platformlayer.ids.ServiceType) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) FederationMapping(org.platformlayer.federation.FederationMapping)

Aggregations

RepositoryException (org.platformlayer.RepositoryException)56 JdbcTransaction (com.fathomdb.jdbc.JdbcTransaction)30 SQLException (java.sql.SQLException)30 OpsException (org.platformlayer.ops.OpsException)18 ProjectId (org.platformlayer.ids.ProjectId)14 ItemBase (org.platformlayer.core.model.ItemBase)10 CryptoKey (com.fathomdb.crypto.CryptoKey)8 PlatformLayerKey (org.platformlayer.core.model.PlatformLayerKey)7 ManagedItemId (org.platformlayer.ids.ManagedItemId)7 OpsContext (org.platformlayer.ops.OpsContext)7 ServiceProvider (org.platformlayer.xaas.services.ServiceProvider)7 IOException (java.io.IOException)6 AesCryptoKey (com.fathomdb.crypto.AesCryptoKey)5 PublicKey (java.security.PublicKey)4 JAXBException (javax.xml.bind.JAXBException)4 Tag (org.platformlayer.core.model.Tag)4 ServiceType (org.platformlayer.ids.ServiceType)4 JobData (org.platformlayer.jobs.model.JobData)4 JoinedQueryResult (com.fathomdb.jpa.impl.JoinedQueryResult)3 X509Certificate (java.security.cert.X509Certificate)3