Search in sources :

Example 21 with ResponseCode

use of edu.umass.cs.gnscommon.ResponseCode in project GNS by MobilityFirst.

the class NSUpdateSupport method executeUpdateLocal.

/**
   * Executes a local updateEntireValuesMap operation.
   *
   * @param header
   * @param commandPacket
   * @param guid
   * @param field
   * @param writer
   * @param signature
   * @param message
   * @param timestamp
   * @param operation
   * @param updateValue
   * @param oldValue
   * @param argument
   * @param userJSON
   * @param app
   * @param doNotReplyToClient
   * @return an NSResponseCode
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   * @throws SignatureException
   * @throws JSONException
   * @throws IOException
   * @throws FailedDBOperationException
   * @throws RecordNotFoundException
   * @throws FieldNotFoundException
   * @throws edu.umass.cs.gnscommon.exceptions.server.InternalRequestException
   */
public static ResponseCode executeUpdateLocal(InternalRequestHeader header, CommandPacket commandPacket, String guid, String field, String writer, String signature, String message, Date timestamp, UpdateOperation operation, ResultValue updateValue, ResultValue oldValue, int argument, ValuesMap userJSON, GNSApplicationInterface<String> app, boolean doNotReplyToClient) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, JSONException, IOException, FailedDBOperationException, RecordNotFoundException, FieldNotFoundException, InternalRequestException {
    ResponseCode errorCode = ResponseCode.NO_ERROR;
    assert (header != null);
    // No checks for local non-auth commands like verifyAccount or for mutual auth
    if (!GNSProtocol.INTERNAL_QUERIER.toString().equals(writer) && !commandPacket.getCommandType().isMutualAuth()) {
        if (!header.verifyInternal()) {
            // This the standard auth check for most updates
            if (field != null) {
                errorCode = NSAuthentication.signatureAndACLCheck(header, guid, field, null, writer, signature, message, MetaDataTypeName.WRITE_WHITELIST, app);
            } else if (userJSON != null) {
                errorCode = NSAuthentication.signatureAndACLCheck(header, guid, null, userJSON.getKeys(), writer, signature, message, MetaDataTypeName.WRITE_WHITELIST, app);
            } else {
                ClientSupportConfig.getLogger().log(Level.FINE, "Name {0} key={1} : ACCESS_ERROR", new Object[] { guid, field });
                return ResponseCode.ACCESS_ERROR;
            }
        } else {
            // This ACL check will be only used for active code remote query 
            if (field != null) {
                assert (header.getQueryingGUID() != null) : guid + ":" + field + ":" + writer + "::" + header.getOriginatingGUID();
                errorCode = NSAuthentication.aclCheck(header, guid, field, header.getQueryingGUID(), MetaDataTypeName.WRITE_WHITELIST, app).getResponseCode();
            } else if (userJSON != null) {
                List<String> fields = userJSON.getKeys();
                for (String aField : fields) {
                    AclCheckResult aclResult = NSAuthentication.aclCheck(header, guid, aField, header.getQueryingGUID(), MetaDataTypeName.WRITE_WHITELIST, app);
                    if (aclResult.getResponseCode().isExceptionOrError()) {
                        errorCode = aclResult.getResponseCode();
                    }
                }
            }
        }
    }
    // Check for stale commands.
    if (timestamp != null) {
        if (timestamp.before(DateUtils.addMinutes(new Date(), -Config.getGlobalInt(GNSConfig.GNSC.STALE_COMMAND_INTERVAL_IN_MINUTES)))) {
            errorCode = ResponseCode.STALE_COMMAND_VALUE;
        }
    }
    // Return an error code if one of the checks doesn't pass
    if (errorCode.isExceptionOrError()) {
        return errorCode;
    }
    if (!operation.equals(UpdateOperation.CREATE_INDEX)) {
        // Handle usual case
        NameRecord nameRecord = getNameRecord(guid, field, operation, app.getDB());
        updateNameRecord(header, nameRecord, guid, field, operation, updateValue, oldValue, argument, userJSON, app.getDB(), app.getActiveCodeHandler());
        return ResponseCode.NO_ERROR;
    } else // Handle special case of a create index
    if (!updateValue.isEmpty() && updateValue.get(0) instanceof String) {
        ClientSupportConfig.getLogger().log(Level.FINE, "Creating index for {0} {1}", new Object[] { field, updateValue });
        app.getDB().createIndex(field, (String) updateValue.get(0));
        return ResponseCode.NO_ERROR;
    } else {
        ClientSupportConfig.getLogger().log(Level.SEVERE, "Invalid index value:{0}", updateValue);
        return ResponseCode.UPDATE_ERROR;
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) NameRecord(edu.umass.cs.gnsserver.gnsapp.recordmap.NameRecord) JSONObject(org.json.JSONObject) List(java.util.List) Date(java.util.Date)

Example 22 with ResponseCode

use of edu.umass.cs.gnscommon.ResponseCode in project GNS by MobilityFirst.

the class CommandUtils method checkResponse.

/**
   *
   * @param command
   *
   * @param responsePacket
   * @return Response as a string.
   * @throws ClientException
   */
public static ResponsePacket checkResponse(ResponsePacket responsePacket, CommandPacket command) throws ClientException {
    ResponseCode code = responsePacket.getErrorCode();
    String returnValue = responsePacket.getReturnValue();
    // wants to return a null value.
    if (code.isOKResult()) {
        return (returnValue.startsWith(GNSProtocol.NULL_RESPONSE.toString())) ? null : //returnValue;
        responsePacket;
    }
    // else error
    String errorSummary = code + ": " + returnValue + //+ ": " + responsePacket.getSummary()
    (command != null ? " for command " + command.getSummary() : "");
    switch(code) {
        case SIGNATURE_ERROR:
            throw new EncryptionException(code, errorSummary);
        case BAD_GUID_ERROR:
        case BAD_ACCESSOR_ERROR:
        case BAD_ACCOUNT_ERROR:
            throw new InvalidGuidException(code, errorSummary);
        case FIELD_NOT_FOUND_ERROR:
            throw new FieldNotFoundException(code, errorSummary);
        case ACCESS_ERROR:
            throw new AclException(code, errorSummary);
        case VERIFICATION_ERROR:
            throw new VerificationException(code, errorSummary);
        case ALREADY_VERIFIED_EXCEPTION:
            throw new VerificationException(code, errorSummary);
        case DUPLICATE_ID_EXCEPTION:
            //case DUPLICATE_NAME_EXCEPTION:
            throw new DuplicateNameException(code, errorSummary);
        case DUPLICATE_FIELD_EXCEPTION:
            throw new InvalidFieldException(code, errorSummary);
        case ACTIVE_REPLICA_EXCEPTION:
            throw new InvalidGuidException(code, errorSummary);
        case NONEXISTENT_NAME_EXCEPTION:
            throw new InvalidGuidException(code, errorSummary);
        case TIMEOUT:
        case RECONFIGURATION_EXCEPTION:
            throw new ClientException(code, errorSummary);
        default:
            throw new ClientException(code, "Error received with an unknown response code: " + errorSummary);
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) DuplicateNameException(edu.umass.cs.gnscommon.exceptions.client.DuplicateNameException) InvalidGuidException(edu.umass.cs.gnscommon.exceptions.client.InvalidGuidException) EncryptionException(edu.umass.cs.gnscommon.exceptions.client.EncryptionException) FieldNotFoundException(edu.umass.cs.gnscommon.exceptions.client.FieldNotFoundException) VerificationException(edu.umass.cs.gnscommon.exceptions.client.VerificationException) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException) AclException(edu.umass.cs.gnscommon.exceptions.client.AclException) InvalidFieldException(edu.umass.cs.gnscommon.exceptions.client.InvalidFieldException)

Example 23 with ResponseCode

use of edu.umass.cs.gnscommon.ResponseCode in project GNS by MobilityFirst.

the class AccountAccess method addAlias.

/**
   * Add a new human readable name (alias) to an account.
   * <p>
   * These records will be added:<br>
   * HRN: "_GNS_GUID" -- GUID<br>
   *
   * @param header
   * @param commandPacket
   *
   * @param accountInfo
   * @param alias
   * @param writer
   * @param signature
   * @param message
   * @param timestamp
   * @param handler
   * @return status result
   */
public static CommandResponse addAlias(InternalRequestHeader header, CommandPacket commandPacket, AccountInfo accountInfo, String alias, String writer, String signature, String message, Date timestamp, ClientRequestHandlerInterface handler) {
    // insure that that name does not already exist
    try {
        ResponseCode returnCode;
        JSONObject jsonHRN = new JSONObject();
        jsonHRN.put(HRN_GUID, accountInfo.getGuid());
        if ((returnCode = handler.getInternalClient().createOrExists(new CreateServiceName(alias, jsonHRN.toString()))).isExceptionOrError()) {
            // roll this back
            accountInfo.removeAlias(alias);
            return new CommandResponse(returnCode, GNSProtocol.BAD_RESPONSE.toString() + " " + returnCode.getProtocolCode() + " " + alias + " " + returnCode.getMessage());
        }
        accountInfo.addAlias(alias);
        accountInfo.noteUpdate();
        if (updateAccountInfo(header, commandPacket, accountInfo.getGuid(), accountInfo, writer, signature, message, timestamp, handler, true).isExceptionOrError()) {
            // back out if we got an error
            handler.getInternalClient().deleteOrNotExists(alias, true);
            return new CommandResponse(ResponseCode.UPDATE_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.UPDATE_ERROR.toString());
        } else {
            return new CommandResponse(ResponseCode.NO_ERROR, GNSProtocol.OK_RESPONSE.toString());
        }
    } catch (JSONException e) {
        return new CommandResponse(ResponseCode.JSON_PARSE_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.JSON_PARSE_ERROR.toString() + " " + e.getMessage());
    } catch (ClientException ce) {
        return new CommandResponse(ce.getCode(), GNSProtocol.BAD_RESPONSE.toString() + " " + ce.getCode() + " " + alias + " " + ce.getMessage());
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) CreateServiceName(edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException)

Example 24 with ResponseCode

use of edu.umass.cs.gnscommon.ResponseCode in project GNS by MobilityFirst.

the class AccountAccess method removeGuidInternal.

/**
   * Remove a guid. If ignoreAccountGuid is true we're deleting
   * the account guid as well so we don't have to check or
   * update that info.
   * The accountInfo parameter can be null in which case we
   * look it up.
   *
   * @param header
   * @param commandPacket
   * @param guidInfo
   * @param accountInfo - can be null in which case we look it up
   * @param ignoreAccountGuid
   * @param handler
   * @return the command response
   */
// This can be called from the context of an account guid deleting one if it's
// subguids or a guid deleting itself. The difference being who signs the command,
// but that's outside of this function
private static CommandResponse removeGuidInternal(InternalRequestHeader header, CommandPacket commandPacket, GuidInfo guidInfo, AccountInfo accountInfo, boolean ignoreAccountGuid, ClientRequestHandlerInterface handler) {
    GNSConfig.getLogger().log(Level.FINE, "REMOVE: GUID INFO: {0} ACCOUNT INFO: {1}", new Object[] { guidInfo, accountInfo });
    // (unless we're sure it's not because we're deleting an account guid)
    if (!ignoreAccountGuid) {
        if (lookupAccountInfoFromGuidAnywhere(header, guidInfo.getGuid(), handler) != null) {
            return new CommandResponse(ResponseCode.BAD_GUID_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.BAD_GUID.toString() + " " + guidInfo.getGuid() + " is an account guid");
        }
    }
    // Fill in a missing account info
    if (accountInfo == null) {
        String accountGuid = AccountAccess.lookupPrimaryGuid(header, guidInfo.getGuid(), handler, true);
        // should not happen unless records got messed up in GNS
        if (accountGuid == null) {
            return new CommandResponse(ResponseCode.BAD_ACCOUNT_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.BAD_ACCOUNT.toString() + " " + guidInfo.getGuid() + " does not have a primary account guid");
        }
        if ((accountInfo = lookupAccountInfoFromGuidAnywhere(header, accountGuid, handler)) == null) {
            return new CommandResponse(ResponseCode.BAD_ACCOUNT_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + GNSProtocol.BAD_ACCOUNT.toString() + " " + guidInfo.getGuid() + " cannot find primary account guid for " + accountGuid);
        }
    }
    // Step 1 - remove any group links
    ResponseCode removedGroupLinksResponseCode;
    try {
        removedGroupLinksResponseCode = GroupAccess.removeGuidFromGroups(header, commandPacket, guidInfo.getGuid(), handler);
    } catch (IOException | InternalRequestException | JSONException e) {
        removedGroupLinksResponseCode = ResponseCode.UPDATE_ERROR;
    } catch (ClientException e) {
        removedGroupLinksResponseCode = e.getCode();
    }
    // Step 2 - update the account info record unless this is part of an account guid delete
    ResponseCode accountInfoResponseCode;
    if (!ignoreAccountGuid) {
        accountInfo.removeGuid(guidInfo.getGuid());
        accountInfo.noteUpdate();
        accountInfoResponseCode = updateAccountInfoNoAuthentication(header, commandPacket, accountInfo, handler, true);
    } else {
        accountInfoResponseCode = ResponseCode.NO_ERROR;
    }
    // Step 3 - delete the HRN record
    ResponseCode deleteNameResponseCode;
    try {
        deleteNameResponseCode = handler.getInternalClient().deleteOrNotExists(guidInfo.getName(), true);
    } catch (ClientException e) {
        deleteNameResponseCode = e.getCode();
    }
    if ((removedGroupLinksResponseCode.isExceptionOrError() || accountInfoResponseCode.isExceptionOrError()) || deleteNameResponseCode.isExceptionOrError()) {
        // Don't really care who caused the error, other than for debugging.
        return new CommandResponse(ResponseCode.UPDATE_ERROR, GNSProtocol.BAD_RESPONSE.toString() + " " + (removedGroupLinksResponseCode.isOKResult() ? "" : "; failed to remove group links") + (accountInfoResponseCode.isOKResult() ? "" : "; failed to update account info " + accountInfo.getGuid()) + (deleteNameResponseCode.isOKResult() ? "" : "; failed to delete " + guidInfo.getName()));
    } else {
        // Step 3.5 - delete the cache entry
        GUID_INFO_CACHE.invalidate(guidInfo.getGuid());
        // Step 4 - If all the above stuff worked we delete the guid record
        ResponseCode deleteGuidResponseCode;
        try {
            deleteGuidResponseCode = handler.getInternalClient().deleteOrNotExists(guidInfo.getGuid(), true);
        } catch (ClientException e) {
            return new CommandResponse(e.getCode(), GNSProtocol.BAD_RESPONSE.toString() + " Failed to delete " + guidInfo.getGuid());
        }
        if (deleteGuidResponseCode.isOKResult()) {
            return new CommandResponse(ResponseCode.NO_ERROR, GNSProtocol.OK_RESPONSE.toString());
        } else {
            return new CommandResponse(deleteGuidResponseCode, GNSProtocol.BAD_RESPONSE.toString() + " Failed to delete " + guidInfo.getGuid());
        }
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) InternalRequestException(edu.umass.cs.gnscommon.exceptions.server.InternalRequestException) JSONException(org.json.JSONException) RandomString(edu.umass.cs.gnscommon.utils.RandomString) IOException(java.io.IOException) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException)

Example 25 with ResponseCode

use of edu.umass.cs.gnscommon.ResponseCode in project GNS by MobilityFirst.

the class AccountAccess method addAccountInternal.

/**
   * Create a new GNS user account.
   *
   * THIS CAN BYPASS THE EMAIL VERIFICATION if you set emailVerify to false;
   *
   * <p>
   * This adds three records to the GNS for the account:<br>
   * GNSProtocol.NAME.toString(): "_GNS_GUID" -- guid<br>
   * GUID: "_GNS_ACCOUNT_INFO" -- {account record - an AccountInfo object
   * stored as JSON}<br>
   * GUID: "_GNS_GUID_INFO" -- {guid record - a GuidInfo object stored as
   * JSON}<br>
   *
   * @param header
   *
   * @param name
   * @param guid
   * @param publicKey
   * @param password
   * @param emailVerify
   * @param verifyCode
   * @param handler
   * @return status result
   * @throws IOException
   */
public static CommandResponse addAccountInternal(InternalRequestHeader header, String name, String guid, String publicKey, String password, boolean emailVerify, String verifyCode, ClientRequestHandlerInterface handler) throws IOException {
    try {
        ResponseCode returnCode;
        // First try to createField the HRN record to make sure this name
        // isn't already registered
        JSONObject jsonHRN = new JSONObject();
        jsonHRN.put(HRN_GUID, guid);
        returnCode = handler.getInternalClient().createOrExists(new CreateServiceName(name, jsonHRN.toString()));
        String boundGUID = null;
        if (!returnCode.isExceptionOrError() || (guid.equals(boundGUID = HRNMatchingGUIDExists(header, handler, returnCode, name, guid)))) {
            // if that's cool then add the entry that links the guid to the
            // username and public key
            // this one could fail if someone uses the same public key to
            // register another one... that's a nono
            // Note that password here is base64 encoded
            AccountInfo accountInfo = new AccountInfo(name, guid, password);
            accountInfo.noteUpdate();
            // if email verifications are off we just set it to verified
            if (!emailVerify) {
                accountInfo.setVerified(true);
            } else {
                accountInfo.setVerificationCode(verifyCode);
            }
            JSONObject json = new JSONObject();
            json.put(ACCOUNT_INFO, accountInfo.toJSONObject());
            GuidInfo guidInfo = new GuidInfo(name, guid, publicKey);
            json.put(GUID_INFO, guidInfo.toJSONObject());
            // set up ACL to look like this
            // "_GNS_ACL": {
            // "READ_WHITELIST": {"+ALL+": {"MD": "+ALL+"]}}}
            JSONObject acl = createACL(GNSProtocol.ENTIRE_RECORD.toString(), Arrays.asList(GNSProtocol.EVERYONE.toString()), null, null);
            // prefix is the same for all acls so just pick one to use here
            json.put(MetaDataTypeName.READ_WHITELIST.getPrefix(), acl);
            // set up the default read access
            returnCode = handler.getInternalClient().createOrExists(new CreateServiceName(guid, json.toString()));
            String boundHRN = null;
            assert (returnCode != null);
            if (!returnCode.isExceptionOrError() || name.equals(boundHRN = GUIDMatchingHRNExists(header, handler, returnCode, name, // all good if here
            guid))) {
                return CommandResponse.noError();
            }
            if (// try to delete the record we added above
            returnCode.equals(ResponseCode.DUPLICATE_ID_EXCEPTION)) {
                return rollback(handler, ResponseCode.CONFLICTING_GUID_EXCEPTION.setMessage(" Existing GUID " + guid + " has HRN " + boundHRN + " and can not be associated with the HRN " + name), name, guid);
            }
        } else if (returnCode.equals(ResponseCode.DUPLICATE_FIELD_EXCEPTION) && !guid.equals(boundGUID)) {
            return new CommandResponse(ResponseCode.CONFLICTING_GUID_EXCEPTION, GNSProtocol.BAD_RESPONSE.toString() + " " + ResponseCode.CONFLICTING_GUID_EXCEPTION.getProtocolCode() + " " + name + "(" + guid + ")" + " " + (returnCode.getMessage() != null ? returnCode.getMessage() + " " : "") + "; HRN " + name + " is already bound to GUID " + boundGUID + " != " + guid);
        }
        // else the first HRN creation likely failed
        return new CommandResponse(returnCode, GNSProtocol.BAD_RESPONSE.toString() + " " + returnCode.getProtocolCode() + " " + name + "(" + guid + ") " + returnCode.getMessage());
    } catch (JSONException e) {
        return CommandResponse.toCommandResponse(e);
    } catch (ClientException ce) {
        return new CommandResponse(ce.getCode(), GNSProtocol.BAD_RESPONSE.toString() + " " + ce.getCode() + " " + name + " " + ce.getMessage() + " (" + name + " may have gotten created despite this exception)");
    }
}
Also used : ResponseCode(edu.umass.cs.gnscommon.ResponseCode) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) CreateServiceName(edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName) RandomString(edu.umass.cs.gnscommon.utils.RandomString) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException)

Aggregations

ResponseCode (edu.umass.cs.gnscommon.ResponseCode)40 JSONObject (org.json.JSONObject)28 Date (java.util.Date)18 CommandResponse (edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.CommandResponse)16 JSONException (org.json.JSONException)14 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)13 ResultValue (edu.umass.cs.gnsserver.utils.ResultValue)8 FailedDBOperationException (edu.umass.cs.gnscommon.exceptions.server.FailedDBOperationException)7 InternalRequestException (edu.umass.cs.gnscommon.exceptions.server.InternalRequestException)7 IOException (java.io.IOException)7 MetaDataTypeName (edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.MetaDataTypeName)6 RandomString (edu.umass.cs.gnscommon.utils.RandomString)5 ValuesMap (edu.umass.cs.gnsserver.utils.ValuesMap)5 GuidInfo (edu.umass.cs.gnsserver.gnsapp.clientCommandProcessor.commandSupport.GuidInfo)4 CreateServiceName (edu.umass.cs.reconfiguration.reconfigurationpackets.CreateServiceName)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 InvalidKeyException (java.security.InvalidKeyException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 SignatureException (java.security.SignatureException)3 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)3