S3 clock skew tested at +/- 5, 15, and 20 minutes

You start a batch backup job on an older virtual machine or an edge IoT device, and every upload fails instantly with HTTP 403 Forbidden. The error body reads RequestTimeTooSkewed. Nothing is wrong with your access keys, bucket permissions, or network routing. The host's system clock has simply drifted away from real time.

In AWS Signature Version 4 (SigV4), the client timestamp is not just an informational header. It is cryptographically bound into the canonical request hash and the signing key derivation. But how far off can your clock actually be before the storage gateway rejects your request? To find out, we generated exact SigV4 requests at 11 deliberate offsets between -20 minutes and +20 minutes and tested them against both AWS S3 and tport.space.

1. The 15-minute rule in Signature Version 4

Whenever an S3 client sends a standard authenticated request using the Authorization header, it must provide a timestamp via the x-amz-date header (or a standard HTTP Date header) in ISO 8601 basic format: YYYYMMDDTHHMMSSZ (for example, 20261123T081500Z).

  • Replay attack defense: If S3 accepted requests with arbitrary timestamps, an eavesdropper capturing an authenticated payload could replay that exact request days or weeks later. Restricting valid requests to a tight time window ensures that signed URLs and headers cannot be reused indefinitely.
  • Credential scope binding: The date portion (`YYYYMMDD`) forms the first branch of the SigV4 credential derivation (`AWS4-HMAC-SHA256` key hierarchy: `kDate -> kRegion -> kService -> kSigning`). The date in the credential scope string must match the date of the request timestamp.
  • The 900-second threshold: S3 enforces a maximum clock skew of exactly 900 seconds (15 minutes or 900,000 milliseconds). If your client timestamp differs from the storage cluster's authoritative time by more than 15 minutes in either direction, the request is refused before credential verification begins.

2. Testing clock drift: the 900-second cliff measured

We constructed a test harness that builds compliant SigV4 canonical requests, hashes, and HMAC-SHA256 signatures offline, but varies the timestamp offset injected into x-amz-date and the credential scope. We tested offsets across both s3.us-east-1.amazonaws.com and s3.tport.space. Using dummy credentials lets us isolate the exact stage where evaluation halts: when the timestamp is accepted, S3 advances to credential lookup and returns InvalidAccessKeyId. When the timestamp fails, it halts immediately with RequestTimeTooSkewed.

OffsetClient Clock vs ServerHTTP StatusS3 Error CodeEvaluation Result
-1200s20 min slow (past)403 ForbiddenRequestTimeTooSkewedRejected (> 900s)
-910s15 min 10s slow403 ForbiddenRequestTimeTooSkewedRejected (> 900s)
-900s15 min 00s slow403 ForbiddenRequestTimeTooSkewedRejected (boundary)
-890s14 min 50s slow403 ForbiddenInvalidAccessKeyIdAccepted (within 900s)
-300s5 min slow403 ForbiddenInvalidAccessKeyIdAccepted (within 900s)
0sSynchronized (NTP)403 ForbiddenInvalidAccessKeyIdAccepted (baseline)
+300s5 min fast403 ForbiddenInvalidAccessKeyIdAccepted (within 900s)
+890s14 min 50s fast403 ForbiddenInvalidAccessKeyIdAccepted (within 900s)
+900s15 min 00s fast403 ForbiddenInvalidAccessKeyIdAccepted (boundary)
+910s15 min 10s fast403 ForbiddenRequestTimeTooSkewedRejected (> 900s)
+1200s20 min fast (future)403 ForbiddenRequestTimeTooSkewedRejected (> 900s)

The boundary is razor-sharp. At -890 seconds (14 minutes, 50 seconds behind server time), the timestamp passes without friction. Ten seconds past the 15-minute mark (-910 seconds), S3 returns RequestTimeTooSkewed. In the error response body, AWS returns explicit details showing the exact window limit:

xml
<?xml version="1.0" encoding="UTF-8"?>
<Error>
  <Code>RequestTimeTooSkewed</Code>
  <Message>The difference between the request time and the current time is too large.</Message>
  <RequestTime>20261123T075800Z</RequestTime>
  <ServerTime>2026-11-23T08:18:02Z</ServerTime>
  <MaxAllowedSkewMilliseconds>900000</MaxAllowedSkewMilliseconds>
  <RequestId>P07HS58EDNZ80C05</RequestId>
  <HostId>5NNj5AJsX6ugSPVyGNRUCv7qHwY8lQ211crhnNcMniszTq8fTcPiymMSc3s8tOa+gxpjJgFptcS9bslR2bbfat52M6svc1R4</HostId>
</Error>

Notice <MaxAllowedSkewMilliseconds>900000</MaxAllowedSkewMilliseconds>. 900,000 milliseconds equals exactly 15 minutes. Both AWS S3 and tport.space execute this evaluation before any object or key lookup is performed.

3. Header-based requests vs. presigned URL expiry

Presigned URLs behave differently than header-signed requests because they are intended to be shared and executed asynchronously. A presigned URL carries its parameters in the query string: X-Amz-Date defines when the URL was minted, and X-Amz-Expires defines its lifetime in seconds (from 1 second up to 7 days / 604,800 seconds).

ScenarioHeader SigV4Presigned URL (Expires=900s)Presigned URL (Expires=1800s)
Clock 20 min slow (-1200s)RequestTimeTooSkewedAccessDenied: Request has expiredValid (elapsed 20m < 30m)
Clock 5 min slow (-300s)ValidValid (10m usable life left)Valid (25m usable life left)
Clock 5 min fast (+300s)ValidValid (server allows future drift)Valid
Clock 20 min fast (+1200s)RequestTimeTooSkewedAccessDenied: Request is not yet validAccessDenied: Request is not yet valid

For presigned URLs, past drift eats directly into the URL's lifetime. If a client's clock is 10 minutes slow when it generates a presigned URL with X-Amz-Expires=900 (15 minutes), the server calculates that 10 minutes have already elapsed the instant it receives the request. The user gets only 5 minutes of real validity instead of 15. If the clock is 20 minutes slow, the URL is dead on arrival (Request has expired).

Conversely, if the client clock is in the future, S3 tolerates up to 15 minutes of future drift. If X-Amz-Date is more than 15 minutes ahead of the server (+910s or +1200s), the gateway rejects the request with AccessDenied: Request is not yet valid.

4. Offline signature math vs. online server validation

A common point of confusion is why SDKs and client libraries do not warn you about clock skew when you call generate_presigned_url() or sign a request. The reason is architectural: SigV4 signature calculation is purely mathematical and entirely offline.

To sign a request, the client hashes strings and runs standard HMAC-SHA256 calculations against your secret access key. It does not open a network socket, query an NTP server, or ping the S3 gateway. If your local system clock is set to the year 1999 or 2035, the signature algorithm will happily produce a mathematically valid hexadecimal signature. The mismatch only surfaces when the HTTP bytes arrive at the gateway and the server compares x-amz-date against its own hardware clock.

5. Detecting and correcting clock skew from the 403 Date header

When running inside restricted Docker containers, serverless environments, or edge devices where your process does not have root permissions (CAP_SYS_TIME) to alter the host clock, you cannot simply run chronyd or timedatectl. Fortunately, every HTTP answer from S3—including a 403 error—carries the server's exact timestamp in the standard Date header.

Here is a complete, standalone Python implementation that catches RequestTimeTooSkewed, calculates the skew delta from the Date header, and automatically re-signs the request:

python
import datetime
import email.utils
import hashlib
import hmac
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET

def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()

def get_signature_key(key, date_stamp, region_name, service_name):
    k_date = sign(("AWS4" + key).encode("utf-8"), date_stamp)
    k_region = sign(k_date, region_name)
    k_service = sign(k_region, service_name)
    return sign(k_service, "aws4_request")

def make_s3_request(host, bucket, key_id, secret_key, region, target_time):
    """Signs and sends an S3 request with a specific target timestamp."""
    amz_date = target_time.strftime("%Y%m%dT%H%M%SZ")
    date_stamp = target_time.strftime("%Y%m%d")
    payload_hash = hashlib.sha256(b"").hexdigest()
    
    canonical_uri = f"/{bucket}"
    canonical_headers = f"host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amz_date}\n"
    signed_headers = "host;x-amz-content-sha256;x-amz-date"
    canonical_request = f"GET\n{canonical_uri}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
    
    credential_scope = f"{date_stamp}/{region}/s3/aws4_request"
    string_to_sign = f"AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()}"
    
    signing_key = get_signature_key(secret_key, date_stamp, region, "s3")
    signature = hmac.new(signing_key, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
    auth_header = f"AWS4-HMAC-SHA256 Credential={key_id}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}"
    
    headers = {
        "Host": host,
        "User-Agent": "aws-cli/2.15.0",
        "x-amz-date": amz_date,
        "x-amz-content-sha256": payload_hash,
        "Authorization": auth_header
    }
    req = urllib.request.Request(f"https://{host}/{bucket}", headers=headers)
    try:
        with urllib.request.urlopen(req) as resp:
            return resp.status, resp.headers, resp.read().decode("utf-8")
    except urllib.error.HTTPError as err:
        return err.code, err.headers, err.read().decode("utf-8", errors="replace")

def execute_with_skew_correction(host, bucket, key_id, secret_key, region="auto"):
    # Simulate a client clock that is 20 minutes slow
    simulated_skew = -1200
    local_clock = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(seconds=simulated_skew)
    print(f"Initial attempt with local clock: {local_clock.isoformat()} (20 min slow)")
    
    status, headers, body = make_s3_request(host, bucket, key_id, secret_key, region, local_clock)
    
    if status == 403 and "RequestTimeTooSkewed" in body:
        server_date_header = headers.get("Date")
        if not server_date_header:
            raise RuntimeError("403 RequestTimeTooSkewed received but no Date header present")
        
        # Parse RFC 7231 Date header: e.g. 'Mon, 23 Nov 2026 08:18:50 GMT'
        server_time = email.utils.parsedate_to_datetime(server_date_header)
        measured_drift = (server_time - local_clock).total_seconds()
        print(f"Detected clock skew: {measured_drift:+.1f}s ({measured_drift / 60:.2f} minutes)")
        
        # Compensate timestamp in-memory and re-sign
        corrected_clock = local_clock + datetime.timedelta(seconds=measured_drift)
        print(f"Retrying with corrected timestamp: {corrected_clock.isoformat()}")
        status, headers, body = make_s3_request(host, bucket, key_id, secret_key, region, corrected_clock)
    
    return status, body

When executed against s3.tport.space, the script produces clean recovery logs. The initial request with 20 minutes of negative drift fails with HTTP 403 RequestTimeTooSkewed. The script extracts Date: Mon, 23 Nov 2026 08:19:12 GMT, computes drift = +1199.7s, adjusts the time offset, and the retry request passes the timestamp check immediately.

6. How AWS SDKs handle skew behind the scenes

If you use official AWS SDKs (such as boto3 / botocore in Python, the AWS SDK for Go, or the AWS Java SDK), you may rarely see RequestTimeTooSkewed in practice. That is because modern SDKs implement the exact skew recovery pattern shown above automatically.

In botocore (specifically in botocore/handlers.py under correct_clock_skew), an event handler listens for response status 403. When it encounters RequestTimeTooSkewed, it parses either <ServerTime> from the XML body or the HTTP Date response header, calculates the drift, stores endpoint.clock_skew on the client instance, adjusts the clock for all future requests to that endpoint, and retries the failed operation.

However, this protection only works if you use high-level SDK clients. If you sign requests manually in Go (net/http), build curl commands in shell scripts, implement custom upload workers, or generate presigned URLs on an un-synced laptop, no SDK is present to rescue the call.

7. Production defenses for containers and edge workers

To prevent clock drift from breaking storage pipelines in production, adhere to four operational practices:

  • Run chrony in slew mode: On host servers and virtual machines, run chronyd -x. Slew mode adjusts time gradually rather than jumping the clock backward, preventing timestamp regressions in active database and storage logs.
  • Do not rely on containers to keep time: Docker and Kubernetes containers share the host Linux kernel clock. If the host drifts, every container on the node drifts simultaneously. Monitor host clock offset with chronyc tracking or ntpstat.
  • Pad presigned URL expirations: If you mint presigned URLs on systems with uncertain clock sync (such as mobile client devices or distributed desktop apps), add 5 to 10 minutes of buffer to X-Amz-Expires so that minor past drift does not cause premature expiration.
  • Log the Date header on 403s: When building custom S3 client libraries, always log the server's Date header alongside the error response. It immediately confirms whether an auth failure is a bad secret key or a drifted clock.