Skip to content

Commit

Permalink
Leverage If-None-Match when updating issues
Browse files Browse the repository at this point in the history
If `If-None-Match` is specified and it doesn’t match latest hash, then fail with `412 Precondition failed`.

Always return the updated `ETag` header.

Fixes #23653
  • Loading branch information
vboctor committed Nov 25, 2017
1 parent 4aec7f9 commit cb2a453
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
16 changes: 14 additions & 2 deletions api/rest/restcore/issues_rest.php
Expand Up @@ -253,6 +253,17 @@ function rest_issue_update( \Slim\Http\Request $p_request, \Slim\Http\Response $
return $p_response->withStatus( HTTP_STATUS_BAD_REQUEST, $t_message );
}

# Calculate etag for issue. This will work even if issue doesn't exist.
$t_etag = bug_hash( $t_issue_id );

if( $p_request->hasHeader( HEADER_IF_NONE_MATCH ) ) {
$t_match_etag = $p_request->getHeaderLine( HEADER_IF_NONE_MATCH );
if( $t_etag != $t_match_etag ) {
return $p_response->withStatus( HTTP_STATUS_PRECONDITION_FAILED, 'Precondition Failed' )
->withHeader( HEADER_ETAG, bug_hash( $t_issue_id ) );
}
}

# Load the latest issue state from the db to merge with the provided fields to patch
$t_original_issue = mc_issue_get( /* username */ '', /* password */ '', $t_issue_id );

Expand All @@ -272,6 +283,7 @@ function rest_issue_update( \Slim\Http\Request $p_request, \Slim\Http\Response $

$t_updated_issue = mc_issue_get( /* username */ '', /* password */ '', $t_issue_id );

return $p_response->withStatus( HTTP_STATUS_SUCCESS, "Issue with id $t_issue_id Updated" )->
withJson( array( 'issue' => $t_updated_issue ) );
return $p_response->withStatus( HTTP_STATUS_SUCCESS, "Issue with id $t_issue_id Updated" )
->withHeader( HEADER_ETAG, bug_hash( $t_issue_id ) )
->withJson( array( 'issue' => $t_updated_issue ) );
}
9 changes: 7 additions & 2 deletions core/bug_api.php
Expand Up @@ -987,11 +987,14 @@ function bug_text_clear_cache( $p_bug_id = null ) {
* @return string The hash.
*/
function bug_hash( $p_bug_id, $p_user_id = null ) {
# This is needed for cases where a bug has been updated, and a new hash is to be calculated.
bug_clear_cache( $p_bug_id );

# Change this version when it is desired to force clients to refresh issues.
$t_version = 'v1';

if( auth_is_user_authenticated() ) {
$t_user_id = $p_user_id ?: auth_get_current_user_id();
$t_user_id = $p_user_id ? (int)$p_user_id : auth_get_current_user_id();
} else {
$t_user_id = $p_user_id ?: '';
}
Expand All @@ -1003,7 +1006,9 @@ function bug_hash( $p_bug_id, $p_user_id = null ) {
$t_last_updated = '';
}

$t_str_to_hash = $p_bug_id . '_' . $t_last_updated . '_' . $t_user_id . '_' . $t_version;
$t_bug_id = (int)$p_bug_id;

$t_str_to_hash = $t_bug_id . '_' . $t_last_updated . '_' . $t_user_id . '_' . $t_version;
return hash( 'sha256', $t_str_to_hash );
}

Expand Down

0 comments on commit cb2a453

Please sign in to comment.