Top Banner
Amazon Simple Queue Service Developer Guide API Version 2009-02-01
78
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: sqs-dg

Amazon SimpleQueue Service

Developer Guide

API Version 2009-02-01

Page 2: sqs-dg

Amazon Simple Queue Service Developer Guide

Amazon Simple Queue Service: Developer GuideCopyright © 2009 Amazon Web Services LLC or its affiliates. All rights reserved.

Page 3: sqs-dg

Amazon Simple Queue Service Developer Guide

Table of ContentsWelcome ............................................................................................................................................................ 1What's New ....................................................................................................................................................... 4Introduction to Amazon SQS ............................................................................................................................ 5

Overview of Amazon SQS .................................................................................................................... 5Features ................................................................................................................................................. 6Architectural Overview ........................................................................................................................... 6How SQS Queues Work ....................................................................................................................... 7

About SQS Queues ..................................................................................................................... 7Properties of Distributed Queues ................................................................................................. 8Queue and Message Identifiers ................................................................................................... 9Resources Required to Process Messages ............................................................................... 10Visibility Timeout ........................................................................................................................ 10Message Lifecycle ...................................................................................................................... 12

Programming Guide ........................................................................................................................................ 14Query Requests .................................................................................................................................. 15SOAP Requests .................................................................................................................................. 18Request Authentication ....................................................................................................................... 21

What Is Authentication? ............................................................................................................. 21Your AWS Account .................................................................................................................... 22Your AWS Identifiers ................................................................................................................. 22Viewing Your AWS Identifiers .................................................................................................... 23HMAC-SHA Signatures .............................................................................................................. 24

Required Authentication Information ................................................................................ 25Basic Authentication Process ........................................................................................... 25About the String to Sign ................................................................................................... 27About the Time Stamp ..................................................................................................... 27Java Sample Code for Base64 Encoding ........................................................................ 28Java Sample Code for Calculating HMAC-SHA1 Signatures ........................................... 28

Query Request Authentication ................................................................................................... 29SOAP Request Authentication ................................................................................................... 32

SOAP with WS-Security ................................................................................................... 32SOAP without WS-Security .............................................................................................. 37

Responses ........................................................................................................................................... 39Shared Queues ................................................................................................................................... 40Programming Languages .................................................................................................................... 42Endpoints ............................................................................................................................................. 42

Appendix: The Access Policy Language ........................................................................................................ 44Overview .............................................................................................................................................. 45

When to Use Access Control .................................................................................................... 45Key Concepts ............................................................................................................................. 45Architectural Overview ............................................................................................................... 48Using the Access Policy Language ........................................................................................... 49Evaluation Logic ......................................................................................................................... 50Basic Use Cases for Access Control ........................................................................................ 53

How to Write a Policy ......................................................................................................................... 56Basic Policy Structure ................................................................................................................ 56Element Descriptions ................................................................................................................. 57Supported Data Types ............................................................................................................... 63

Amazon SQS Policy Examples ........................................................................................................... 65Special Information for SQS Policies .................................................................................................. 68

Glossary .......................................................................................................................................................... 69Document Conventions ................................................................................................................................... 71Index ................................................................................................................................................................ 74

Page 4: sqs-dg

Amazon Simple Queue Service Developer GuideAudience

API Version 2009-02-011

Welcome

Topics

• Audience (p. 1)

• Reader Feedback (p. 2)

• How This Guide Is Organized (p. 2)

• Amazon SQS Resources (p. 2)

This is the Amazon Simple Queue Service Developer Guide. This section describes who should readthis guide, how the guide is organized, and other resources related to the Amazon Simple QueueService (Amazon SQS).

The Amazon Simple Queue Service will occasionally be referred to within this guide as simply "SQS";all copyrights and legal protections still apply.

AudienceThis guide is intended for developers who are building distributed web-enabled applications. Anapplication could typically use Amazon SQS to move data between distributed application componentsperforming different tasks, without losing messages or requiring each component to be alwaysavailable.

To use SQS, you must have an AWS account and be signed up to use SQS. For more information, goto the Amazon Simple Queue Service Getting Started Guide .

Required Knowledge and SkillsUse of this guide assumes you are familiar with the following:

• XML (for an overview, go to W3 Schools XML Tutorial )

• Basic understanding of web services (for an overview, go to W3 Schools Web Services Tutorial )

• A programming language for consuming a web service and any related tools

You should also have read the Amazon Simple Queue Service Getting Started Guide, which includes atutorial showing you how to perform basic functions with a queue.

Page 5: sqs-dg

Amazon Simple Queue Service Developer GuideReader Feedback

API Version 2009-02-012

Reader FeedbackThe online version of this guide provides a link that enables you to enter feedback about this guide. Westrive to make our guides as complete, error free, and easy to read as possible. You can help by givingus feedback. Thank you in advance!

How This Guide Is OrganizedThis guide is organized into several major sections described in the following table.

Information Relevant Sections

Updates and Changes to the Version • What's New (p. 4)

General information about AmazonSQS

• Introduction to Amazon SQS (p. 5)

Conceptual information about AmazonSQS

• How SQS Queues Work (p. 7)

• Properties of Distributed Queues (p. 8)

• Shared Queues (p. 40)

How to create requests, authenticaterequests, and understand responses

• Programming Guide (p. 14)

Access Control Policy Reference • Appendix: The Access Policy Language (p. 44)

In addition, there is a glossary and an overview of our typographical conventions. Each section iswritten to stand on its own, so you should be able to look up the information you need and go back towork. However, you can also read through the major sections sequentially to get in-depth knowledgeabout Amazon SQS.

Amazon SQS ResourcesThe following table lists related resources that you'll find useful as you work with this service.

Resource Description

Amazon Simple Queue ServiceGetting Started Guide

The getting started guide provides a quick tutorial ofthe service based on a simple use case. Examples andinstructions in multiple programming languages areincluded.

Amazon Simple Queue Service APIReference

The API reference gives the WSDL location; completedescriptions of the API actions, parameters, and data types;and a list of errors that the service returns.

Amazon SQS Schema Documentation The release notes give a high-level overview of thecurrent release. They specifically note any new features,corrections, and known issues.

Page 6: sqs-dg

Amazon Simple Queue Service Developer GuideAmazon SQS Resources

API Version 2009-02-013

Resource Description

Amazon SQS Release Notes The release notes give a high-level overview of thecurrent release. They specifically note any new features,corrections, and known issues.

AWS Developer Resource Center A central starting point to find documentation, codesamples, release notes, and other information to help youbuild innovative applications with AWS.

Discussion Forums A community-based forum for developers to discusstechnical questions related to Amazon SQS.

AWS Support Center The home page for AWS Technical Support, includingaccess to our Developer Forums, Technical FAQs, ServiceStatus page, and AWS Premium Support (if you aresubscribed to this program).

AWS Premium Support Information The primary web page for information about AWS PremiumSupport, a one-on-one, fast-response support channel tohelp you build and run applications on AWS InfrastructureServices.

Product information for Amazon SQS The primary web page for information about Amazon SQS.

Contact Us A central contact point for inquiries concerning AWS billing,account, events, abuse etc.

Conditions of Use Detailed information about the copyright and trademarkusage at Amazon.com and other topics.

Page 7: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-014

What's New

This What's New is associated with the 2009-02-01 release of the Amazon Simple Queue Service. Thisguide was last updated on 01 December 2009.

The following table describes the important changes since the last release of the Amazon SimpleQueue Service Developer Guide.

Change Description Release Date

New Endpointand Section

Created a new US endpoint for Amazon SQS. For moreinformation, see the new Endpoints (p. 42) section.

2 December2009

AWS SDKfor .NET

AWS now provides libraries, sample code, tutorials, and otherresources for software developers who prefer to build applicationsusing .NET language-specific APIs instead of REST or SOAP. Formore information, see Programming Languages (p. 42).

11 November2009

New Guide Created a separate API Reference for Amazon SQS. 28 September2009

Enhancement Added ability to share queues, including support for anonymousaccess. For more information, see Shared Queues (p. 40).Also added an appendix to explain access policy language. Formore information, see Appendix: The Access Policy Language (p.44).

7 April 2009

Enhancement The SQS schema is now inline in the WSDL. There is no longer aseparate URL for the schema.

7 April 2009

Page 8: sqs-dg

Amazon Simple Queue Service Developer GuideOverview of Amazon SQS

API Version 2009-02-015

Introduction to Amazon SQS

Topics

• Overview of Amazon SQS (p. 5)

• Features (p. 6)

• Architectural Overview (p. 6)

• How SQS Queues Work (p. 7)

This introduction to Amazon SQS is intended to give you a detailed summary of this web service. Afterreading this section, you should have a good idea of what SQS offers and how it can fit in with yourbusiness.

Overview of Amazon SQSAmazon SQS is a distributed queue system that enables web service applications to quickly andreliably queue messages that one component in the application generates to be consumed by anothercomponent. A queue is a temporary repository for messages that are awaiting processing.

Using Amazon SQS, you can decouple the components of an application so they run independently,with Amazon SQS easing message management between components. Any component of adistributed application can store any type of data in a fail-safe queue. Any other component can thenlater receive the data programmatically using the SQS API.

The queue acts as a buffer between the component producing and saving data, and the componentreceiving the data for processing. This means the queue resolves issues that arise if the produceris producing work faster than the consumer can process it, or if the producer or consumer are onlyintermittently connected to the network.

SQS ensures delivery of each message at least once, and supports multiple readers and writersinteracting with the same queue. A single queue can be used simultaneously by many distributedapplication components, with no need for those components to coordinate with each other to share thequeue.

Amazon SQS is engineered to always be available and deliver messages. One of the resultingtradeoffs is that SQS does not guarantee first in, first out delivery of messages. For many distributedapplications, each message can stand on its own, and as long as all messages are delivered, the orderis not important. If your system requires that order be preserved, you can place sequencing informationin each message, so that you can reorder the messages when the queue returns them.

Page 9: sqs-dg

Amazon Simple Queue Service Developer GuideFeatures

API Version 2009-02-016

Be sure to read about distributed queues, which will help you understand how to design an applicationthat works correctly with Amazon SQS. For more information, see Properties of Distributed Queues (p.8).

FeaturesAmazon SQS provides the following major features:

• Redundant infrastructure—Guarantees delivery of your messages at least once, highly concurrentaccess to messages, and high availability for sending and retrieving messages

• Multiple writers and readers—Multiple parts of your system can send or receive messages at thesame time

SQS locks the message during processing, keeping other parts of your system from processing themessage simultaneously.

• Configurable settings per queue—All of your queues don't have to be exactly alike

For example, one queue can be optimized for messages that require a longer processing time thanothers.

• Variable message size—Your messages can be up to 8 KB in size

For even larger messages, you can store the contents of the message using the Amazon SimpleStorage Service (Amazon S3) or Amazon SimpleDB and use Amazon SQS to hold a pointer to theAmazon S3 or Amazon SDB object. Alternately, you can split the larger message into smaller ones.

For more information about the services, go to the Amazon S3 detail page and the AmazonSimpleDB detail page.

• Unlimited queues and messages—You can have as many queues and messages in the AmazonSQS system as you want

• Access control—You can control who can send messages to a queue, and who can receivemessages from a queue

Architectural OverviewThere are three main actors in the overall system:

• The components of your distributed system

• Queues

• Messages in the queues

In the following diagram, your system has several components that send messages to the queue andreceive messages from the queue. The diagram shows that a single queue, which has its messages(labeled A-E), is redundantly saved across multiple SQS servers.

Page 10: sqs-dg

Amazon Simple Queue Service Developer GuideHow SQS Queues Work

API Version 2009-02-017

How SQS Queues WorkTopics

• About SQS Queues (p. 7)

• Properties of Distributed Queues (p. 8)

• Queue and Message Identifiers (p. 9)

• Resources Required to Process Messages (p. 10)

• Visibility Timeout (p. 10)

• Message Lifecycle (p. 12)

This section describes the basic properties of Amazon SQS queues, identifiers for queues andmessages, how you determine the general size of the queue, and how you manage the messages in aqueue.

About SQS QueuesYou can have as many queues with as many messages as you like in the Amazon SQS system. Aqueue can be empty if you haven't sent any messages to it or if you have deleted all the messagesfrom it.

You assign a name to each of your queues (for more information, see Queue URLs (p. 9)). Youcan get a list of all your queues or a subset of your queues that share the same initial characters intheir names (for example, you could get a list of all your queues whose names start with "T3").

You can delete a queue at any time, whether it is empty or not. You should be aware that queues havea time limit; SQS deletes messages that have been in the queue for more than 4 days.

We reserve the right to delete a queue without notification if one of the following actions hasn't beenperformed on it for 30 consecutive days: SendMessage, ReceiveMessage, DeleteMessage,GetQueueAttributes, SetQueueAttributes, AddPermission, and RemovePermission.

Important

It is a violation of the intended use of Amazon SQS if you repeatedly create queues and thenleave them inactive.

Page 11: sqs-dg

Amazon Simple Queue Service Developer GuideProperties of Distributed Queues

API Version 2009-02-018

The following table lists the API actions to use.

To do this... Use this action

Create a queue CreateQueue

List your queues ListQueues

Delete a queue DeleteQueue

Properties of Distributed QueuesThe following information can help you design your application to work with Amazon SQS correctly.

Message Order

SQS makes a best effort to preserve order in messages, but due to the distributed nature of the queue,we cannot guarantee you will receive messages in the exact order you sent them. If your systemrequires that order be preserved, we recommend you place sequencing information in each messageso you can reorder the messages upon receipt.

At-Least-Once Delivery

SQS stores copies of your messages on multiple servers for redundancy and high availability. On rareoccasions, one of the servers storing a copy of a message might be unavailable when you receive ordelete the message. If that occurs, the copy of the message will not be deleted on that unavailableserver, and you might get that message copy again when you receive messages. Because of this, youmust design your application to be idempotent (i.e., it must not be adversely affected if it processes thesame message more than once).

Message Sample

When you retrieve messages from the queue, SQS samples a subset of the servers (based on aweighted random distribution) and returns messages from just those servers. This means that aparticular receive request might not return all your messages. Or, if you have a small number ofmessages in your queue (less than 1000), it means a particular request might not return any of yourmessages, whereas a subsequent request will. If you keep retrieving from your queues, SQS willsample all of the servers, and you will receive all of your messages.

The following figure shows messages being returned after one of your system components makes areceive request. SQS samples several of the servers (in gray) and returns the messages from thoseservers (Message A, C, D, and B). Message E is not returned to this particular request, but it would bereturned to a subsequent request.

Page 12: sqs-dg

Amazon Simple Queue Service Developer GuideQueue and Message Identifiers

API Version 2009-02-019

Queue and Message Identifiers

SQS uses the following three identifiers that you need to be familiar with:

• Queue URL

• Message ID

• Receipt handle

Queue URLsWhen creating a new queue, you must provide a queue name that is unique within the scope of all yourqueues. If you create queues using both the 2008-01-01 WSDL and a previous version, you still have asingle namespace for all your queues. SQS assigns each queue you create an identifier called a queueURL, which includes the queue name and other components that SQS determines. Whenever youwant to perform an action on a queue, you provide its queue URL.

The following is the queue URL for a queue named "queue2" owned by a person with the AWSaccount number "123456789012".

http://queue.amazonaws.com/123456789012/queue2

Important

In your system, always store the entire queue URL as Amazon SQS returned it to you whenyou created the queue (for example, http://queue.amazonaws.com/123456789012/queue2). Don't build the queue URL from its separate components each time you need tospecify the queue URL in a request because Amazon SQS could change the components thatmake up the queue URL.

You can also get the queue URL for a queue by listing your queues. Even though you have a singlenamespace for all your queues, the list of queues returned depends on the WSDL you use for therequest. For more information, see ListQueues .

Message IDsIn versions of Amazon SQS prior to 2009-02-01, each message received a system-assigned identifierthat you needed in order to delete the message from the queue. SQS still returns this message ID

Page 13: sqs-dg

Amazon Simple Queue Service Developer GuideResources Required to Process Messages

API Version 2009-02-0110

to you in the SendMessage response, but you can no longer use the message ID to delete themessage. Instead you need a receipt handle.

Receipt Handles

Each time you receive a message from a queue, you receive a receipt handle for that message. Thehandle is associated with the act of receiving the message, not with the message itself. To delete themessage or to change the message visibility, you must provide the receipt handle and not the messageID. This means you must always receive a message before you can delete it (you can't put a messageinto the queue and then recall it).

Important

If you receive a message more than once, each time you receive it, you get a different receipthandle. You must provide the most recently received receipt handle when you request todelete the message or the message might not be deleted.

Following is an example of a receipt handle.

MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+CwLj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QEauMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0=

Resources Required to Process MessagesTo help you estimate the amount of resources needed to process your queued messages, AmazonSQS can provide you with an approximate number of messages in a queue. You can view thenumber of messages that are visible or you can view the number of messages that are not visible.Messages that are not visible are messages in a queue that are not timed-out and not deleted. Formore information about visibility, see Visibility Timeout (p. 10).

Important

Because of the distributed architecture of SQS, the result is not an exact count of the numberof messages in a queue. In most cases it should be close to the actual number of messages inthe queue, but you should not rely on the count being precise.

The following table lists the API action to use.

To do this... Use this action

Get the approximate number of messages in the queue GetQueueAttributes

Get the approximate number of messages in the queue thatare not visible

GetQueueAttributes

Visibility TimeoutTopics

• General Recommendations for Visibility Timeout (p. 11)

• Extending a Message's Visibility Timeout (p. 11)

• Terminating a Message's Visibility Timeout (p. 12)

• API Actions Related to Visibility Timeout (p. 12)

Page 14: sqs-dg

Amazon Simple Queue Service Developer GuideVisibility Timeout

API Version 2009-02-0111

When a consuming component in your system receives and processes a message from the queue, themessage remains in the queue. Why doesn't Amazon SQS automatically delete it?

Because your system is distributed, there's no guarantee that the component will actually receivethe message (it's possible the connection could break or the component could fail before receivingthe message). Therefore, Amazon SQS does not delete the message, and instead, your consumingcomponent must delete the message from the queue after receiving and processing it.

Immediately after the component receives the message, the message is still in the queue. However,you don't want other components in the system receiving and processing the message again.Therefore, Amazon SQS blocks them with a visibility timeout, which is a period of time during whichAmazon SQS prevents other consuming components from receiving and processing that message.The following figure and discussion illustrate the concept.

General Recommendations for Visibility Timeout

The visibility timeout clock starts ticking once Amazon SQS returns the message. During that time,the component processes and deletes the message. But what happens if the component fails beforedeleting the message? If your system doesn't call DeleteMessage for that message before thevisibility timeout expires, the message again becomes visible to the ReceiveMessage calls placedby the components in your system and it will be received again. If a message should only be receivedonce, your system should delete it within the duration of the visibility timeout.

Each queue starts with a default setting of 30 seconds for the visibility timeout. You can change thatsetting for the entire queue. Typically, you'll set the visibility timeout to the average time it takes toprocess and delete a message from the queue. When receiving messages, you can also set a specialvisibility timeout for the returned messages without changing the overall queue timeout.

We recommend that if you have a system that produces messages that require varying amounts oftime to process and delete, you create multiple queues, each with a different visibility timeout setting.Your system can then send all messages to a single queue that forwards each message to anotherqueue with the appropriate visibility timeout based on the expected processing and deletion time forthat message.

Extending a Message's Visibility Timeout

When you receive a message from the queue, you might find the visibility timeout for the queue isinsufficient to fully process and delete that message. Amazon SQS allows you to extend the visibilitytimeout for that particular message. When you extend the visibility timeout, Amazon SQS overwritesthe original timeout value and the new value begins at the time you changed it.

For example, let's say the timeout for the queue is 30 seconds, and you receive a message. Onceyou're 20 seconds into the timeout for that message (i.e., you have 10 seconds left), you extend it by60 seconds by calling ChangeMessageVisibility with VisibilityTimeoutset to 60 seconds. Youhave then changed the remaining visibility timeout from 10 seconds to 60 seconds.

Page 15: sqs-dg

Amazon Simple Queue Service Developer GuideMessage Lifecycle

API Version 2009-02-0112

The extension you request is not stored in memory for that message. If for some reason you don'tdelete the message and the message is received again, the visibility timeout for the message the nexttime it's received is the overall value for the queue and not the extended value you previously set.

Terminating a Message's Visibility Timeout

When you receive a message from the queue, you might find that you actually don't want to processand delete that message. Amazon SQS allows you to terminate the visibility timeout for a specificmessage, which immediately makes the message visible to other components in the system toprocess. To do this, you call ChangeMessageVisibility with VisibilityTimeout=0 seconds.

API Actions Related to Visibility Timeout

The following table lists the API actions to use to manipulate the visibility timeout.

To do this... Use this action

Set the visibility timeout for a queue ???

Get the visibility timeout for a queue ???

Set the visibility timeout for the received messages withoutaffecting the queue's visibility timeout

??? and set the VisibilityTimeoutparameter to the value you want

Extending or terminating a message's visibility timeout ???

Message LifecycleThe following diagram and process describe the lifecycle of an Amazon SQS message, calledMessage A, from creation to deletion. Assume that a queue already exists.

Page 16: sqs-dg

Amazon Simple Queue Service Developer GuideMessage Lifecycle

API Version 2009-02-0113

Message Lifecycle

Component 1 sends Message A to a queue and the message is redundantly distributedacross the SQS servers.

When Component 2 is ready to process a message, it retrieves messages from thequeue, and Message A is returned. While Message A is being processed, it remainsin the queue and is not returned to subsequent receive requests for the duration of thevisibility timeout.

Component 2 deletes Message A from the queue to avoid the message being receivedand processed again once the visibility timeout expires.

Note

SQS automatically deletes messages that have been in a queue for more than 4 days.

Page 17: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0114

Programming Guide

Topics

• Query Requests (p. 15)

• SOAP Requests (p. 18)

• Request Authentication (p. 21)

• Responses (p. 39)

• Shared Queues (p. 40)

• Programming Languages (p. 42)

• Endpoints (p. 42)

This section describes how to make requests to Amazon SQS. The various topics acquaint you withthe basic differences between the interfaces, the components of a request, how to authenticate arequest, and the content of responses.

Page 18: sqs-dg

Amazon Simple Queue Service Developer GuideQuery Requests

API Version 2009-02-0115

Query RequestsTopics

• Structure of a GET Request (p. 15)

• Structure of a POST Request (p. 16)

• Related Topics (p. 17)

Amazon SQS supports Query requests for calling service actions. Query requests are simple HTTP orHTTPS requests, using the GET or POST method. Query requests must contain an Action parameterto indicate the action to be performed. The response is an XML document that conforms to a schema.You might use Query requests when a SOAP toolkit is not available for your platform, or when Queryrequests are easier to make than a heavier SOAP equivalent.

Structure of a GET RequestThis guide presents the Amazon SQS GET requests as URLs, which can be used directly in a browser.The URL consists of:

• Endpoint—The resource the request is acting on (in the case of SQS, the endpoint is a queue)

• Action—The action you want to perform on the endpoint; for example: sending a message

• Parameters—Any request parameters

The following is an example GET request to send a message to an SQS queue.

http://queue.amazonaws.com/123456789012/queue1?Action=SendMessage&MessageBody=Your%20Message%20Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12:00:00Z&Signature=lBP67vCvGlDMBQ1dofZxg8E8SUEXAMPLE&SignatureVersion=2&SignatureMethod=HmacSHA256

Important

Because the GET requests are URLs, you must URL encode the parameter values. Forexample, in the preceding example request, the value for the MessageBody parameter isactually Your Message Text. However, spaces are not allowed in URLs, so each space isURL encoded as "%20". The rest of the example has not been URL encoded to make it easierfor you to read.

To make the GET examples even easier to read, this guide presents them in the following parsedformat.

http://queue.amazonaws.com/123456789012/queue1?Action=SendMessage&MessageBody=Your%20Message%20Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12:00:00Z&Signature=lBP67vCvGlDMBQ1dofZxg8E8SUEXAMPLE&SignatureVersion=2&SignatureMethod=HmacSHA256

Page 19: sqs-dg

Amazon Simple Queue Service Developer GuideStructure of a POST Request

API Version 2009-02-0116

Note

In the example Query requests we present in this guide, we use a false AWS Access KeyID and false signature, each with EXAMPLE appended. We do this to indicate that youshouldn't expect the signature in the example to be accurate based on the request parameterspresented in the example. The one exception to this is in the instructions for creating Queryrequest signatures. The example there shows a real signature based on a particular AWSAccess Key ID we specify and the request parameters in the example (for more information,see Query Request Authentication (p. 29)).

In SQS, all parameters except MessageBody always have values that have no spaces. The value youprovide for MessageBody in SendMessage requests can have spaces. In this guide, any exampleSendMessage Query requests with a MessageBody that includes spaces is displayed with the spacesURL encoded (as %20). For clarity, the rest of the URL is not displayed in a URL encoded format.

The first line represents the endpoint of the request. This is the resource the request acts on. Thepreceding example acts on a queue, so the request's endpoint is the queue's identifier, known as thequeue URL. For more details about the queue URL, see Queue URLs (p. 9).

After the endpoint is a question mark (?), which separates the endpoint from the parameters. Eachparameter is separated by an ampersand (&).

The Action parameter indicates the action to perform (for a list of the actions, see API Actions inthe Amazon SQS API Reference). For a list of the other parameters that are common to all Queryrequests, see Request Parameters Common to All Actions in the Amazon SQS API Reference.

Structure of a POST RequestSQS also accepts POST requests. With a POST request, you send the query parameters as a form inthe HTTP request body as described in the following procedure.

To create a POST request

1. Assemble the query parameter names and values into a form.

This means you put the parameters and values together like you would for a GET request (withan ampersand separating each name-value pair). The following example shows a SendMessagerequest with the line breaks we use in this guide to make the information easier to read.

Action=SendMessage&MessageBody=Your Message Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12:00:00Z&SignatureVersion=2&SignatureMethod=HmacSHA256

2. Form-URL-encode the form according to the Form Submission section of the HTML specification(for more information, go to http://www.w3.org/MarkUp/html-spec/html-spec_toc.html#SEC8.2.1).

Action=SendMessage&MessageBody=Your+Message+Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256

3. Add the request signature to the form (for more information, see Query Request Authentication (p.29)).

Page 20: sqs-dg

Amazon Simple Queue Service Developer GuideRelated Topics

API Version 2009-02-0117

Action=SendMessage&MessageBody=Your+Message+Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256&Signature=lBP67vCvGlDMBQ1dofZxg8E8SUEXAMPLE

4. Provide the resulting form as the body of the POST request.

5. Include the Content-Type HTTP header with the value set to application/x-www-form-urlencoded.

The following example shows the final POST request.

POST /queue1 HTTP/1.1Host: queue.amazonaws.comContent-Type: application/x-www-form-urlencoded

Action=SendMessage&MessageBody=Your+Message+Text&AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256&Signature=lBP67vCvGlDMBQ1dofZxg8E8SUEXAMPLE

SQS requires no other HTTP headers in the request besides Content-Type. The authenticationsignature you provide is the same signature you would provide if you sent a GET request (forinformation about the signature, see Query Request Authentication (p. 29)).

Note

Your HTTP client typically adds other items to the HTTP request as required by the version ofHTTP the client uses. We don't include those additional items in the examples in this guide.

Related Topics• Query Request Authentication (p. 29)

• Responses (p. 39)

Page 21: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Requests

API Version 2009-02-0118

SOAP RequestsAmazon SQS supports the SOAP message protocol for calling service actions over an HTTPSconnection only. The easiest way to use the SOAP interface with your application is to use a SOAPtoolkit appropriate for your programming platform. SOAP toolkits are available for most popularprogramming languages and platforms.

The service's Web Services Description Language (WSDL) file describes the actions along with theformat and data types of the actions' requests and responses. Your SOAP toolkit interprets the WSDLfile to provide your application access to the actions. For most toolkits, your application calls a serviceaction using routines and classes provided or generated by the toolkit. For more information about theWSDL, see ???.

The API reference in this guide describes the request parameters for each action and their values. Formore information, see ???. You might find it useful to refer to the WSDL and schema files directly tosee how the parameters appear in the XML of the request generated by your toolkit, and to understandhow your toolkit makes the actions available to your application code.

Structure of a SOAP RequestA SOAP request is an XML data structure that your SOAP toolkit generates and sends to the service.SQS recognizes that the request is a SOAP request by the presence of the optional SOAPActionheader. If no SOAPAction header appears in the request, then the content type of the first (or only)message part must be one of the following:

• text/xml

• text-xml-SOAP

• application/soap+xml

As described by the service WSDL, the root element of the XML structure is named after the action.You include the parameters for the request inside the root element, according to the SQS schema.

If you're using SOAP without WS-Security, you must include the authentication information in theSOAP header using the AWSAccessKeyId, Timestamp, and Signature parameters. For moreinformation, see Request Authentication (p. 21) and SOAP without WS-Security (p. 37).

Page 22: sqs-dg

Amazon Simple Queue Service Developer GuideSpecifying the Resource

API Version 2009-02-0119

Example SOAP Request

The following example shows the XML for a SOAP message that calls the CreateQueue action.Although you probably won't build the SOAP message for a service request manually, it is useful tosee what your SOAP toolkit tries to produce when provided with the appropriate values. Many SOAPtoolkits require you to build a request data structure similar to the XML to make a request.

The CreateQueue element contains the operation-specific QueueName parameter.

<?xml version="1.0" encoding="UTF-8" ?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header xmlns:aws="http://security.amazonaws.com/doc/2007-01-01/"> <aws:AWSAccessKeyId>1D9FVRAYCP1VJS767E02EXAMPLE</aws:AWSAccessKeyId> <aws:Timestamp>2008-02-10T23:59:59Z</aws:Timestamp> <aws:Signature>SZf1CHmQ/nrZbsrC13hCZS061ywsEXAMPLE</aws:Signature> </soapenv:Header> <soapenv:Body> <CreateQueue xmlns="http://queue.amazonaws.com/doc/2009-02-01"> <QueueName>MyQueue</QueueName> </CreateQueue> </soapenv:Body></soapenv:Envelope>

Specifying the ResourceAmazon SQS is a resource-based service, which means you specify the resource (the queue) youwant to work with in the URI of the HTTPS request.

For example, the following SOAP request sends a message to the queue named MyQueue. Notice thatthe name of the queue appears in the URI of the request, and not in the SOAP message body itself(where the action and other action-specific information is specified).

POST /MyQueue HTTP/1.1Host: queue.amazonaws.com <other HTTP headers here...> <?xml version="1.0" encoding="UTF-8" ?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Header xmlns:aws="http://security.amazonaws.com/doc/2007-01-01/"> <aws:AWSAccessKeyId>1D9FVRAYCP1VJS767E02EXAMPLE</aws:AWSAccessKeyId> <aws:Timestamp>2008-02-10T23:59:59Z</aws:Timestamp> <aws:Signature>SZf1CHmQ/nrZbsrC13hCZS061ywsEXAMPLE</aws:Signature> </soapenv:Header> <soapenv:Body> <SendMessage xmlns="http://queue.amazonaws.com/doc/2009-02-01"> <MessageBody>This is my message</MessageBody> </SendMessage> </soapenv:Body></soapenv:Envelope>

Page 23: sqs-dg

Amazon Simple Queue Service Developer GuideRelated Topics

API Version 2009-02-0120

Related Topics• SOAP Request Authentication (p. 32)

• Responses (p. 39)

Page 24: sqs-dg

Amazon Simple Queue Service Developer GuideRequest Authentication

API Version 2009-02-0121

Request AuthenticationTopics

• What Is Authentication? (p. 21)

• Your AWS Account (p. 22)

• Your AWS Identifiers (p. 22)

• Viewing Your AWS Identifiers (p. 23)

• HMAC-SHA Signatures (p. 24)

• Query Request Authentication (p. 29)

• SOAP Request Authentication (p. 32)

The topics in this section describe how Amazon SQS authenticates your requests. In this section youcan learn about the basics of authentication, how your AWS account and identifiers are used to supportauthentication, and how to create an HMAC-SHA1 signature. This section also covers the requestauthentication requirements for Query and SOAP requests.

What Is Authentication?Authentication is a process for identifying and verifying who is sending a request. The followingdiagram shows a simplified version of an authentication process.

General Process of Authentication

The sender obtains the necessary credential.

Page 25: sqs-dg

Amazon Simple Queue Service Developer GuideYour AWS Account

API Version 2009-02-0122

The sender sends a request with the credential to the recipient.

The recipient uses the credential to verify the sender truly sent the request.

If yes, the recipient processes the request. If no, the recipient rejects the request andresponds accordingly.

During authentication, AWS verifies both the identity of the sender and whether the sender isregistered to use services offered by AWS. If either test fails, the request is not processed further.

For further discussion of authentication, go to the techencylopedia.com entry for authentication. Fordefinitions of common industry terms related to authentication, go to the RSA Laboratories Glossary.

The subsequent sections describe how SQS implements authentication to protect your data.

Your AWS AccountTo access any web services offered by AWS, you must first create an AWS account at http://aws.amazon.com. An AWS account is simply an Amazon.com account that is enabled to use AWSproducts; you can use an existing Amazon.com account login and password when creating the AWSaccount.

Alternately, you could create a new AWS-enabled Amazon.com account by using a new login andpassword. The e-mail address you provide as the account login must be valid. You'll be asked toprovide a credit card or other payment method to cover the charges for any AWS products you use.

From your AWS account you can view your AWS account activity, view usage reports, and manageyour AWS account access identifiers.

Related Topics• Your AWS Identifiers (p. 22)

Your AWS IdentifiersWhen you create an AWS account, AWS assigns you a pair of related identifiers:

• Access Key ID (a 20-character, alphanumeric sequence)For example: 022QF06E7MXBSH9DHM02

• Secret Access Key (a 40-character sequence)For example: kWcrlUX5JEDGM/LtmEENI/aVmYvHNif5zB+d9+ct

These are your AWS access key identifiers.

Caution

Your Secret Access Key is a secret and only you and AWS should know it. It is important tokeep it confidential to protect your account. Never include it in your requests to AWS, andnever e-mail it to anyone. Do not share it outside your organization, even if an inquiry appearsto come from AWS or Amazon.com. No one who legitimately represents Amazon will ever askyou for your Secret Access Key.

The Access Key ID is associated with your AWS account. You include it in AWS service requests toidentify yourself as the sender of the request.

Page 26: sqs-dg

Amazon Simple Queue Service Developer GuideViewing Your AWS Identifiers

API Version 2009-02-0123

The Access Key ID is not a secret, and anyone could use your Access Key ID in requests to AWS. Toprovide proof that you truly are the sender of the request, you must also include a digital signature. Forall requests except those using SOAP with WS-Security, you calculate the signature using your SecretAccess Key. AWS uses the Access Key ID in the request to look up your Secret Access Key andthen calculates a digital signature with the key. If the signature AWS calculates matches the signatureyou sent, the request is considered authentic. Otherwise, the request fails authentication and is notprocessed.

Related Topics• HMAC-SHA Signatures (p. 24)

• Query Request Authentication (p. 29)

• SOAP without WS-Security (p. 37)

Viewing Your AWS IdentifiersYour Access Key ID and Secret Access Key are displayed to you when you create your AWS account.They are not e-mailed to you. If you need to see them again, you can view them at any time from yourAWS account.

To view your AWS access identifiers

1. Go to the Amazon Web Services web site at http://aws.amazon.com.

2. Point to Your Account and click Access Identifiers.

3. Log in to your AWS account.

Your AWS account number is displayed in the top right side of the screen, below your name.

Your Access Key ID and Secret Access Key are displayed on the resulting Access Identifiers page.Following is an example of this page.

Page 27: sqs-dg

Amazon Simple Queue Service Developer GuideHMAC-SHA Signatures

API Version 2009-02-0124

Related Topics• Your AWS Account (p. 22)

• Your AWS Identifiers (p. 22)

HMAC-SHA SignaturesTopics

• Required Authentication Information (p. 25)

• Basic Authentication Process (p. 25)

Page 28: sqs-dg

Amazon Simple Queue Service Developer GuideHMAC-SHA Signatures

API Version 2009-02-0125

• About the String to Sign (p. 27)

• About the Time Stamp (p. 27)

• Java Sample Code for Base64 Encoding (p. 28)

• Java Sample Code for Calculating HMAC-SHA1 Signatures (p. 28)

The topics in this section describe how Amazon SQS uses HMAC-SHA signatures to authenticateQuery requests and SOAP requests that don't use WS-Security.

Required Authentication Information

When accessing Amazon SQS using Query or using SOAP without WS-Security, you must provide thefollowing items so the request can be authenticated:

• AWS Access Key ID—Your AWS account is identified by your Access Key ID, which AWS uses tolook up your Secret Access Key.

• Signature—Each request must contain a valid HMAC-SHA request signature, or the request isrejected.

You calculate the request signature by using your Secret Access Key, which is a shared secretknown only to you and AWS.

• Date—Each request must contain the time stamp of the request.

Depending on the API you're using (Query or SOAP), you can provide an expiration date and timefor the request instead of or in addition to the time stamp. For details of what is required and allowedfor each API, see the authentication topic for the particular API.

Related Topics

• Your AWS Identifiers (p. 22)

Basic Authentication Process

Following is the series of tasks required to authenticate requests to AWS using an HMAC-SHA requestsignature. It is assumed you have already created an AWS account and received an Access Key IDand Secret Access Key. For more information about those, see Your AWS Account (p. 22) and YourAWS Identifiers (p. 22).

You perform the first three tasks.

Page 29: sqs-dg

Amazon Simple Queue Service Developer GuideHMAC-SHA Signatures

API Version 2009-02-0126

Process for Authentication: Tasks You Perform

You construct a request to AWS.

You calculate a keyed-hash message authentication code (HMAC-SHA) signature usingyour Secret Access Key (for information about HMAC, go to http://www.faqs.org/rfcs/rfc2104.html)

You include the signature and your Access Key ID in the request, and then send therequest to AWS.

AWS performs the next three tasks.

Page 30: sqs-dg

Amazon Simple Queue Service Developer GuideHMAC-SHA Signatures

API Version 2009-02-0127

Process for Authentication: Tasks AWS Performs

AWS uses the Access Key ID to look up your Secret Access Key.

AWS generates a signature from the request data and the Secret Access Key using thesame algorithm you used to calculate the signature you sent in the request.

If the signature generated by AWS matches the one you sent in the request, the requestis considered authentic. If the comparison fails, the request is discarded, and AWSreturns an error response.

About the String to SignEach AWS request you send must include an HMAC-SHA request signature calculated with yourSecret Access Key (except for SOAP requests using WS-Security). The string you use to calculate thesignature (the string to sign) varies depending on the API you're using (Query or SOAP). The detailsare covered in the following topics:

• Query Request Authentication (p. 29)

• SOAP without WS-Security (p. 37)

About the Time StampThe time stamp (or expiration time) you use in the request must be a dateTime object, with thecomplete date plus hours, minutes, and seconds (for more information, go to http://www.w3.org/TR/xmlschema-2/#dateTime). For example: 2007-01-31T23:59:59Z. Although it is not required, we

Page 31: sqs-dg

Amazon Simple Queue Service Developer GuideHMAC-SHA Signatures

API Version 2009-02-0128

recommend you provide the time stamp in the Coordinated Universal Time (Greenwich Mean Time)time zone.

If you specify a time stamp (instead of an expiration time), the request automatically expires 15 minutesafter the time stamp (in other words, AWS does not process a request if the request time stamp ismore than 15 minutes earlier than the current time on AWS servers). Make sure your server's time isset correctly.

Important

If you are using .NET you must not send overly specific time stamps, due to differentinterpretations of how extra time precision should be dropped. To avoid overly specific timestamps, manually construct dateTime objects with no more than millisecond precision.

Java Sample Code for Base64 EncodingRequest signatures must be base64 encoded. The following Java sample code shows how to performbase64 encoding.

package amazon.webservices.common;/*** This class defines common routines for encoding data in AWS requests.*/public class Encoding {/*** Performs base64-encoding of input bytes.** @param rawData * Array of bytes to be encoded.* @return * The base64 encoded string representation of rawData.*/public static String EncodeBase64(byte[] rawData) {return Base64.encodeBytes(rawData);}}

Java Sample Code for Calculating HMAC-SHA1 SignaturesThe following Java code sample shows how to calculate an HMAC request signature.

package amazon.webservices.common;

import java.security.SignatureException;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;

/*** This class defines common routines for generating* authentication signatures for AWS requests.*/public class Signature {private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

/*** Computes RFC 2104-compliant HMAC signature.* * @param data* The data to be signed.* @param key* The signing key.

Page 32: sqs-dg

Amazon Simple Queue Service Developer GuideQuery Request Authentication

API Version 2009-02-0129

* @return* The Base64-encoded RFC 2104-compliant HMAC signature.* @throws* java.security.SignatureException when signature generation fails*/public static String calculateRFC2104HMAC(String data, String key)throws java.security.SignatureException{String result;try {

// get an hmac_sha1 key from the raw key bytesSecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

// get an hmac_sha1 Mac instance and initialize with the signing keyMac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);mac.init(signingKey);

// compute the hmac on input data bytesbyte[] rawHmac = mac.doFinal(data.getBytes());

// base64-encode the hmacresult = Encoding.EncodeBase64(rawHmac);

} catch (Exception e) {throw new SignatureException("Failed to generate HMAC : " + e.getMessage());}return result;}}

Query Request AuthenticationYou can send Query requests over either HTTP or HTTPS. Regardless of which protocol you use, youmust include a signature in every Query request. This section describes how to create the signature.The method described in the following procedure is known as signature version 2.

Caution

If you are currently using signature version 1: Version 1 is deprecated, and you should moveto signature version 2 immediately. For information about the deprecation schedule and thedifferences between signature version 2 and version 1, go to Making Secure Requests toAmazon Web Services.

To create the signature

1. Create the canonicalized query string that you need later in this procedure:

a. Sort the UTF-8 query string components by parameter name with natural byte ordering.

The parameters can come from the GET URI or from the POST body (when Content-Typeis application/x-www-form-urlencoded).

b. URL encode the parameter name and values according to the following rules:

• Do not URL encode any of the unreserved characters that RFC 3986 defines.

These unreserved characters are A-Z, a-z, 0-9, hyphen ( - ), underscore ( _ ), period ( . ),and tilde ( ~ ).

Page 33: sqs-dg

Amazon Simple Queue Service Developer GuideQuery Request Authentication

API Version 2009-02-0130

• Percent encode all other characters with %XY, where X and Y are hex characters 0-9 anduppercase A-F.

• Percent encode extended UTF-8 characters in the form %XY%ZA....

• Percent encode the space character as %20 (and not +, as common encoding schemesdo).

Note

Currently all AWS service parameter names use unreserved characters, so you don'tneed to encode them. However, you might want to include code to handle parameternames that use reserved characters, for possible future use.

c. Separate the encoded parameter names from their encoded values with the equals sign ( = )(ASCII character 61), even if the parameter value is empty.

d. Separate the name-value pairs with an ampersand ( & ) (ASCII code 38).

2. Create the string to sign according to the following pseudo-grammar (the "\n" represents anASCII newline).

StringToSign = HTTPVerb + "\n" + ValueOfHostHeaderInLowercase + "\n" + HTTPRequestURI + "\n" + CanonicalizedQueryString <from the preceding step>

The HTTPRequestURI component is the HTTP absolute path component of the URI up to, but notincluding, the query string. If the HTTPRequestURI is empty, use a forward slash ( / ).

3. Calculate an RFC 2104-compliant HMAC with the string you just created, your Secret Access Keyas the key, and SHA256 or SHA1 as the hash algorithm.

For more information, go to http://www.ietf.org/rfc/rfc2104.txt.

4. Convert the resulting value to base64.

5. Use the resulting value as the value of the Signature request parameter.

Important

The final signature you send in the request must be URL encoded as specified in RFC 3986(for more information, go to http://www.ietf.org/rfc/rfc3986.txt). If your toolkit URL encodesyour final request, then it handles the required URL encoding of the signature. If your toolkitdoesn't URL encode the final request, then make sure to URL encode the signature before youinclude it in the request. Most importantly, make sure the signature is URL encoded only once.A common mistake is to URL encode it manually during signature formation, and then againwhen the toolkit URL encodes the entire request.

Page 34: sqs-dg

Amazon Simple Queue Service Developer GuideQuery Request Authentication

API Version 2009-02-0131

Example SetQueueAttributes Request

https://queue.amazonaws.com/770098461991/queue2?Action=SetQueueAttributes&Attribute.Name=VisibilityTimeout&Attribute.Value=90&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256&AWSAccessKeyId=<Your AWS Access Key ID>

Following is the string to sign.

GET\nqueue.amazonaws.com\n/770098461991/queue2\nAWSAccessKeyId=<Your AWS Access Key ID>&Action=SetQueueAttributes&Attribute.Name=VisibilityTimeout&Attribute.Value=90&Expires=2008-02-10T12%3A00%3A00Z&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2009-02-01

Following is the signed request.

https://queue.amazonaws.com/770098461991/queue2?Action=SetQueueAttributes&Attribute.Name=VisibilityTimeout&Attribute.Value=35&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&Signature=<URLEncode(Base64Encode(Signature))>&SignatureVersion=2&SignatureMethod=HmacSHA256&AWSAccessKeyId=<Your AWS Access Key ID>

Page 35: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0132

Example SendMessage Request Using POST

POST /queue2 HTTP/1.1Host: queue.amazonaws.comContent-Type: application/x-www-form-urlencoded Action=SendMessage&MessageBody=Your+Message+Text&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256&AWSAccessKeyId=<Your AWS Access Key ID>

Following is the string to sign. Notice that you encode the spaces as %20 (and not plus signs) whenyou form the string to sign.

POST\nqueue.amazonaws.com\n/queue2\nAWSAccessKeyId=<Your AWS Access Key ID>&Action=SendMessage&Expires=2008-02-10T12%3A00%3A00Z&MessageBody=Your%20Message%20Text&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2009-02-01

Following is the signed request.

POST /queue2 HTTP/1.1Host: queue.amazonaws.comContent-Type: application/x-www-form-urlencoded

Action=SendMessage&MessageBody=Your+Message+Text&Version=2009-02-01&Expires=2008-02-10T12%3A00%3A00Z&SignatureVersion=2&SignatureMethod=HmacSHA256&AWSAccessKeyId=<Your AWS Access Key ID>&Signature=URLEncode(Base64Encode(Signature))

SOAP Request AuthenticationTopics

• SOAP with WS-Security (p. 32)

• SOAP without WS-Security (p. 37)

Amazon SQS accepts SOAP requests sent over an HTTPS connection only. You can authenticatethe requests with WS-Security version 1.0 or without WS-Security. WS-Security is the more securemethod. The main factor affecting whether you choose to use WS-Security is whether your currentSOAP toolkit supports WS-Security.

SOAP with WS-SecurityWS-Security, which is officially called Web Services Security: SOAP Message Security, is an openstandard published by OASIS that defines mechanisms for signing and encrypting SOAP messages.

Page 36: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0133

Amazon SQS supports version 1.0 of the WS-Security specification. For more information and a link tothe WS-Security 1.0 specification, go to the OASIS-Open web site for WS-Security.

Tip

The easiest way to comply with the WS-Security requirements is to use a SOAP toolkit thatsupports WS-Security 1.0 and X.509 certificates. If you know your current SOAP toolkit doesn'tsupport WS-Security, we recommend you pursue the non-WS-Security method (for moreinformation, see SOAP without WS-Security (p. 37)).

HTTPS

For the purposes of request security and integrity, you must send all SOAP requests over HTTPS.

X.509 Certificates

When using SOAP with WS-Security, you must use an X.509 certificate for authentication (as opposedto your AWS Secret Access Key). An X.509 certificate is a security token designed to carry a public keyand bind that key to an identity. X.509 certificates are used in a public key infrastructure (PKI), which isa framework for allowing trusted third parties to vouch for a party's identity. PKIs are commonly used insituations that require authentication. For more information about PKIs and X.509 certificates, go to thetechencyclopedia.com entries for digital certificate and PKI.

Note

AWS does not implement a full public key infrastructure. The certificate information is usedonly to authenticate requests to AWS. AWS uses X.509 certificates only as carriers for publickeys and does not trust or use in any way any identity binding that might be included in anX.509 certificate.

The WS-Security 1.0 specification requires you to sign the SOAP message with the private keyassociated with the X.509 certificate and include the X.509 certificate in the SOAP message header.Specifically, you must represent the X.509 certificate as a BinarySecurityToken as described in theWS-Security X.509 token profile (also available if you go to the OASIS-Open web site).

You can use your own X.509 certificate or one generated by AWS. Following are the procedures foruploading your own certificate to AWS and obtaining an AWS-generated certificate. To obtain an X.509certificate generated by an external certificate authority, follow the instructions provided by that CA.

Using Your Own Certificate

If you have an X.509 certificate you want to use, you can upload the certificate to AWS (without theprivate key value). Uploading the certificate automatically associates it with your AWS account.

AWS accepts any syntactically and cryptographically valid X.509 certificate. Certificates can be self-signed or signed by any key. The certificate must be in Privacy Enhanced Mail (PEM) format andinclude a base64 encoded Distinguished Encoding Rules (DER) certificate body.

Important

When you upload the certificate, AWS checks the certificate's contents to confirm that thecertificate has not expired. AWS doesn't check certificate revocation lists (CRLs) to determineif the certificate has been revoked, nor does AWS validate the certificate with a certificateauthority (CA) or any trusted third parties.

To upload your own X.509 certificate

1. Go to the Amazon Web Services web site at http://aws.amazon.com.

Page 37: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0134

2. Point to Your Web Services Account to display a list of options.

3. Click View Access Key Identifiers and log in to your AWS account.The AWS Access Key Identifiers page is displayed.

4. Scroll down to the X.509 Certificate area of the page and click Upload.

5. Follow the instructions on the subsequent pages to upload your certificate.

Using a Certificate Generated by AWS

If you don't already have an X.509 certificate, or if you want a new certificate to use with AWS, you canhave AWS generate one and automatically associate it with your AWS account. Certificates generatedby AWS are signed by an AWS internal certificate authority.

To have AWS create an X.509 certificate for you

1. Go to the Amazon Web Services web site at http://aws.amazon.com.

2. Point to Your Web Services Account to display a list of options.

3. Click View Access Key Identifiers and log in to your AWS account.The AWS Access Key Identifiers page is displayed.

4. Scroll down to the X.509 Certificate area of the page and click Create New.The Create a New Certificate page is displayed.

5. Read the information on the page and click Yes to create your certificate.The Create Success page is displayed.

6. Download your private key file and X.509 certificate file.

What Needs to Be Signed

Each SOAP request must be signed with the private key associated with the X.509 certificate. Tocreate the signature, you sign the Timestamp element, and if you're using WS-Addressing, werecommend you also sign the Action header element. In addition, you can optionally sign the Bodyand the To header element.

Message Expiration

AWS requires request messages to expire so they can't be used in malicious replay attacks. Thebest practice for specifying the expiration of SOAP/WS-Security requests is to include a Timestampelement with an Expires child element. In this case, the message expires at the time established inthe Expires element.

If no Timestamp element is present in the request, the request is rejected as invalid. If you includea Timestamp element with a Created child element but no Expires child element, the messageexpires 15 minutes after the value of the Created element.

Example Request to Use When Troubleshooting

The following example shows the initial portion of a SOAP request that uses WS-Security with anX.509 certificate. If you're using a SOAP toolkit that supports WS-Security and X.509 certificates, thetoolkit constructs the request automatically for you, so you don't have to create a request like thisyourself. The example is included here as a reference to use if you're troubleshooting authenticationissues with your SOAP requests. Several requirements are listed following the example; the numbershighlight where in the example the requirements are satisfied.

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header>

Page 38: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0135

<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">

<wsse:BinarySecurityToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"

EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"

ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="CertId-1064304">

[Your base64 encoded X.509 certificate…] </wsse:BinarySecurityToken>

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo>

<ds:CanonicalizationMethod http://www.w3.org/2001/10/xml-exc-c14n#"></ds:CanonicalizationMethod>

<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></ds:SignatureMethod>

<ds:Reference URI="#id-17984263"> <ds:Transforms>

<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod> <ds:DigestValue>0pjZ1+TvgPf6uG7o+Yp3l2YdGZ4=</ds:DigestValue> </ds:Reference>

<ds:Reference URI="#id-15778003"> <ds:Transforms>

<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"></ds:Transform> </ds:Transforms>

<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></ds:DigestMethod> <ds:DigestValue>HhRbxBBmc2OO348f8nLNZyo4AOM=</ds:DigestValue> </ds:Reference>

</ds:SignedInfo>

<ds:SignatureValue>bmVx24Qom4kd9QQtclxWIlgLk4QsQBPaKESi79x479xgbO9PEStXMiHZuBAi9luuKdNTcfQ8UE/d jjHKZKEQRCOlLVy0Dn5ZL1RlMHsv+OzJzzvIJFTq3LQKNrzJzsNe</ds:SignatureValue>

<ds:KeyInfo Id="KeyId-17007273">

<wsse:SecurityTokenReference

Page 39: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0136

xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-22438818"> <wsse:Reference URI="#CertId-1064304" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"> </wsse:Reference> </wsse:SecurityTokenReference> </ds:KeyInfo>

</ds:Signature>

<wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"

wsu:Id="id-17984263"> <wsu:Created>2006-06-09T10:57:35Z</wsu:Created> <wsu:Expires>2006-06-09T11:02:35Z</wsu:Expires> </wsu:Timestamp>

</wsse:Security></SOAP-ENV:Header>

Requirements for BinarySecurityToken and Signatures

The EncodingType attribute for the BinarySecurityToken element must be http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary.The ValueType attribute for the BinarySecurityToken element must be http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3 or http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1.The BinarySecurityToken element must contain the base64 encoding of the leaf X.509certificate if the ValueType is #X509v3, or it must contain the base64 encoding of the full X.509certificate chain if the ValueType is #X509PKIPathv1.The Algorithm attribute of the CanonicalizationMethod element must be http://www.w3.org/2001/10/xml-exc-c14n#.The Algorithm attribute of the SignatureMethod element must be http://www.w3.org/2000/09/xmldsig#rsa-sha1.The Algorithm attribute of the Transform element for each Reference element must be eitherhttp://www.w3.org/2001/10/xml-exc-c14n# or http://www.w3.org/TR/2001/REC-xml-c14n-20010315.The Algorithm attribute of the DigestMethod element for each Reference element must behttp://www.w3.org/2000/09/xmldsig#sha1.The KeyInfo element must contain a SecurityTokenReference element. TheSecurityTokenReference element must contain a Reference element with a URI attribute.The URI attribute must use a local particle reference to identify the BinarySecurityTokenelement that contains the X.509 certificate (for example: the URI attribute equals#CertId-1064304 in the preceding example request).You must include a wsu:Id attribute in any message elements that you sign. You can sign anySOAP header and the entire SOAP Body. Do not sign any other elements (such as children of theBody element). AWS ignores those elements for the purposes of signature validation, even if youinclude a wsu:ID attribute in them. If you sign elements that shouldn't be signed, the signaturevalidation will fail.

Page 40: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0137

SOAP without WS-SecurityThis section describes how to authenticate SOAP requests without using WS-Security. The topicsdescribe the basic requirements, the required authentication information, and where to place theinformation in the SOAP request.

General Requirements

If you plan to use SOAP without WS-Security:

• You can use either SOAP 1.1 or SOAP 1.2

• You must use HTTPS with your requests

Note

Before API version 2008-01-01, SQS supported only SOAP 1.1.

Required Authentication Information

Authentication of SOAP requests without WS-Security uses your AWS identifiers and an HMAC-SHA1signature. The request must include the parameters listed in the following table.

Parameter Description

AWSAccessKeyId Your AWS Access Key ID. For more information, see Your AWSIdentifiers (p. 22).

Timestamp This must be a dateTime object with the complete date plus hours,minutes, and seconds (for more information, see ??? and look at theTimestamp parameter, or go to http://www.w3.org/TR/xmlschema-2/#dateTime). Although it is not required, we recommend you provide thetime stamp in the Coordinated Universal Time time zone (UTC, also knownas Greenwich Mean Time). The request expires 15 minutes after the timestamp.

Note

Due to different interpretations regarding how extra time precisionshould be dropped, .NET users should take care not to sendoverly specific time stamps. You can do this by manuallyconstructing dateTime objects with no more than millisecondprecision.

Signature The HMAC-SHA1 signature calculated from the concatenation of theAction and Timestamp parameters, using your AWS Secret Access Keyas the key (for information about authentication with HMAC signatures, seeHMAC-SHA Signatures (p. 24)). For example, for a request to createa queue, the value of the Signature element would be the HMAC-SHA1digest of a string like this: CreateQueue2008-02-10T00:00:00Z

To calculate the signature

1. Concatenate the values of the Action and Timestamp request parameters, in that order.The string you've just created is the string you'll use when generating the signature.

2. Calculate an RFC 2104-compliant HMAC-SHA1 signature, using the string you just created andyour Secret Access Key as the key.

Page 41: sqs-dg

Amazon Simple Queue Service Developer GuideSOAP Request Authentication

API Version 2009-02-0138

3. Convert the resulting value to base64.

4. Pass this final value in the Signature parameter of the SOAP request.

Location of Authentication Information in the Request

With version 2009-02-01, you must provide the authentication information as elements in the SOAPheader (using the namespace http://security.amazonaws.com/doc/2007-01-01/), as in the followingexample.

<?xml version="1.0"?><soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Header xmlns:aws="http://security.amazonaws.com/doc/2007-01-01/"> <aws:AWSAccessKeyId>1D9FVRAYCP1VJS767E02EXAMPLE</aws:AWSAccessKeyId> <aws:Timestamp>2008-02-10T23:59:59Z</aws:Timestamp> <aws:Signature>SZf1CHmQnrZbsrC13hCZS061ywsEXAMPLE</aws:Signature></soap:Header>...</soap:Envelope>

Page 42: sqs-dg

Amazon Simple Queue Service Developer GuideResponses

API Version 2009-02-0139

ResponsesTopics

• Structure of a Successful Response (p. 39)

• Structure of an Error Response (p. 39)

• Related Topics (p. 40)

In response to an action request, SQS returns an XML data structure that contains the results of therequest. This data conforms to the SQS schema.

Other than the use of a message envelope in the case of SOAP, the schema for the results is thesame for Query and SOAP responses. The SOAP WSDL imports an XSD file to define the responsemessages, and Query users can access the XSD file directly. For more information, see WSDLLocation and API Version in the Amazon SQS API Reference.

Structure of a Successful ResponseIf the request succeeded, the main response element is named after the action, but with "Response"appended. For example, CreateQueueResponse is the response element returned for a successfulCreateQueue request. This element contains the following child elements:

• ResponseMetadata, which contains the RequestId child element

• An optional element containing action-specific results; for example, the CreateQueueResponseelement includes an element called CreateQueueResult

The XML schema describes the XML response message for each SQS action.

The following is an example of a successful response.

<CreateQueueResponse xmlns=http://queue.amazonaws.com/doc/2009-02-01/ xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:type=CreateQueueResponse> <CreateQueueResult> <QueueUrl> http://queue.amazonaws.com/770098461991/queue2 </QueueUrl> </CreateQueueResult> <ResponseMetadata> <RequestId>cb919c0a-9bce-4afe-9b48-9bdf2412bb67</RequestId> </ResponseMetadata></CreateQueueResponse>

Structure of an Error ResponseIf a request is unsuccessful, the main response element is called ErrorResponse regardless of theaction that was called. This element contains an Error element and a RequestId element. EachError includes:

• A Type element that identifies whether the error was a receiver or sender error

• A Code element that identifies the type of error that occurred

• A Message element that describes the error condition in a human-readable form

Page 43: sqs-dg

Amazon Simple Queue Service Developer GuideRelated Topics

API Version 2009-02-0140

• A Detail element that might give additional details about the error or might be empty

The following is an example of an error response.

<ErrorResponse> <Error> <Type> Sender </Type> <Code> InvalidParameterValue </Code> <Message> Value (quename_nonalpha) for parameter QueueName is invalid. Must be an alphanumeric String of 1 to 80 in length </Message> </Error> <RequestId> 42d59b56-7407-4c4a-be0f-4c88daeea257 </RequestId></ErrorResponse>

Related Topics• Query Requests (p. 15)

• SOAP Requests (p. 18)

Shared QueuesTopics

• Simple API for Shared Queues (p. 40)

• Advanced API for Shared Queues (p. 41)

• Understanding Permissions (p. 41)

• Granting Anonymous Access to a Queue (p. 42)

Amazon SQS includes methods to share your queues so others can use them, using permissions setin an access control policy. A permission gives access to another person to use your queue in someparticular way. A policy is the actual document that contains the permissions you've granted.

Amazon SQS offers two methods for setting a policy: a simple API and an advanced API. In the simpleAPI, SQS generates an access control policy for you. In the advanced API, you create the accesscontrol policy.

Simple API for Shared QueuesThe simple API for sharing a queue has two operations:

• AddPermission

• RemovePermission

With the Simple API, Amazon SQS writes the policy in the required language for you based on theinformation you include in the AddPermission operation. However, the policy that Amazon SQSgenerates is limited in scope. You can grant permissions to principals, but you can't specify restrictions.

Page 44: sqs-dg

Amazon Simple Queue Service Developer GuideAdvanced API for Shared Queues

API Version 2009-02-0141

Advanced API for Shared QueuesWith the advanced API, you write the policy yourself directly in the access policy language and uploadthe policy with the SetQueueAttributes operation. The advanced API allows you to deny access or toapply finer access restrictions (for example, based on time or based on IP address).

If you choose to write your own policies, you need to understand how policies are structured. Forcomplete reference information about policies, see Appendix: The Access Policy Language (p. 44).For examples of policies, see Amazon SQS Policy Examples (p. 65).

Understanding PermissionsA permission is the type of access you give to a principal (the user receiving the permission). Yougive each permission a label that identifies that permission. If you want to delete that permission inthe future, you use that label to identify the permission. If you want to see what permissions are on aqueue, use the GetQueueAttributes operation. Amazon SQS returns the entire policy (containing all thepermissions).

Amazon SQS supports the permission types shown in the following table.

Permission Description

* This permission type grants the following actions to a principal on a sharedqueue: receive messages, send messages, delete messages, change amessage's visibility, get a queue's attributes.

ReceiveMessage This grants permission to receive messages in the queue.

SendMessage This grants permission to send messages to the queue.

DeleteMessage This grants permission to delete messages from the queue.

ChangeMessageVisibility This grants permission to extend or terminate the read lock timeout ofa specified message. For more information about visibility timeout, seeVisibility Timeout (p. 10). For more information about this permission type,see the ChangeMessageVisibility operation.

GetQueueAttributes This grants permission to receive all of the queue attributes except thepolicy, which can only be accessed by the queue's owner. For moreinformation, see the GetQueueAttributes operation..

Permissions for each of the different permission types are considered separate permissions byAmazon SQS, even though * includes the access provided by the other permission types. Forexample, it is possible to grant both * and SendMessage permissions to a user, even though a *includes the access provided by SendMessage.

This concept applies when you remove a permission. If a principal has only a * permission, requestingto remove a SendMessage permission does not leave the principal with an "everything but"permission. Instead, the request does nothing, because the principal did not previously possess anexplicit SendMessage permission.

If you want to remove * and leave the principal with just the ReceiveMessage permission, first add theReceiveMessage permission, then remove the * permission.

Tip

You give each permission a label that identifies that permission. If you want to delete thatpermission in the future, you use that label to identify the permission.

Page 45: sqs-dg

Amazon Simple Queue Service Developer GuideGranting Anonymous Access to a Queue

API Version 2009-02-0142

Note

If you want to see what permissions are on a queue, use the GetQueueAttributes operation.The entire policy (containing all the permissions) is returned.

Granting Anonymous Access to a QueueYou can allow shared queue access to anonymous users. Such access requires no signature orAccess Key ID.

To allow anonymous access you must write your own policy, setting the Principal to *. Forinformation about writing your own policies, see Appendix: The Access Policy Language (p. 44).

Caution

Keep in mind that the queue owner is responsible for all costs related to the queue. Thereforeyou probably want to limit anonymous access in some other way (by time or IP address, forexample).

Programming LanguagesAWS provides libraries, sample code, tutorials, and other resources for software developers who preferto build applications using language-specific APIs instead of Amazon SQS's SOAP and Query APIs.These libraries provide basic functions (not included in Amazon SQS's SOAP and Query APIs), suchas request authentication, request retries, and error handling so that it's easier to get started. Librariesand resources are available for the following languages:

• Java

• PHP

• Ruby

• Windows and .NET

For libraries and sample code in all languages, go to Sample Code & Libraries.

EndpointsTo improve latency and to store data in a location that meets your requirements, Amazon SQS enablesyou to select different Region endpoints.

Amazon SQS supports the following endpoints:

• queue.amazonaws.com—The endpoint for the US-East (Northern Virginia) Region

• us-west-1.queue.amazonaws.com—The endpoint for the US-West (Northern California) Region

• eu-west-1.queue.amazonaws.com —The endpoint for the EU (Ireland) Region

For example, to create a queue in Europe, you would generate a Query request similar to the following:

http://eu-west-1.queue.amazonaws.com/ ?Action=CreateQueue &DefaultVisibilityTimeout=40

Page 46: sqs-dg

Amazon Simple Queue Service Developer GuideEndpoints

API Version 2009-02-0143

&QueueName=testQueue &Version=2009-02-01 &SignatureMethod=HmacSHA256 &Expires=2009-04-18T22%3A52%3A43PST &AWSAccessKeyId=0GS7553JW74RRM612K02EXAMPLE &SignatureVersion=2 &Signature=Dqlp3Sd6ljTUA9Uf6SGtEExwUQEXAMPLE

Each Amazon SQS endpoint is entirely independent. For example, if you have two queues called"MyQueue," one in queue.amazonaws.com and one in eu-west-1.queue.amazonaws.com, they arecompletely independent and do not share any data.

Page 47: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0144

Appendix: The Access PolicyLanguage

Topics

• Overview (p. 45)

• How to Write a Policy (p. 56)

• Amazon SQS Policy Examples (p. 65)

• Special Information for SQS Policies (p. 68)

This appendix is for Amazon SQS users who want to write their own access control policies. Youdon't need to write your own policies if you want to allow access based only on AWS account ID andbasic permissions (e.g., SendMessage, ReceiveMessage). In that case, you can just use the SQSAddPermission action. If you want to explicitly deny access or allow it based on finer conditions (likethe time the request comes in or the IP address of the requester), you need to write your own policiesand upload them to the AWS system using the SQS SetQueueAttributes action.

Note

To write your own policies, you must be familiar with JSON. For more information, go to http://json.org.

The main portion of this appendix includes basic concepts you need to understand, how to write apolicy, and the logic AWS uses to evaluate policies and decide whether to give the requester accessto the resource. Although most of the information in this appendix is service-agnostic, there aresome SQS-specific details you need to know. For more information, see Special Information for SQSPolicies (p. 68).

Page 48: sqs-dg

Amazon Simple Queue Service Developer GuideOverview

API Version 2009-02-0145

OverviewTopics

• When to Use Access Control (p. 45)

• Key Concepts (p. 45)

• Architectural Overview (p. 48)

• Using the Access Policy Language (p. 49)

• Evaluation Logic (p. 50)

• Basic Use Cases for Access Control (p. 53)

This section describes basic concepts you need to understand to use the access policy language towrite policies. It also describes the general process for how access control works with the access policylanguage, and how policies are evaluated.

When to Use Access ControlYou have a great deal of flexibility in how you grant or deny access to a resource. However, the typicaluse cases are fairly simple:

• You want to grant another AWS account a particular type of access to your queue (e.g.,SendMessage). For more information, see Use Case 1 (p. 53).

• You want to grant another AWS account access to your queue for a specific period of time. For moreinformation, see Use Case 2 (p. 53).

• You want to grant another AWS account access to your queue only if the requests come from yourEC2 instances. For more information, see Use Case 3 (p. 54).

• You want to deny another AWS account access to your queue. For more information, see Use Case4 (p. 54).

Key ConceptsThe following sections describe the concepts you need to understand to use the access policylanguage. They're presented in a logical order, with the first terms you need to know at the top of thelist.

Permission

A permission is the concept of allowing or disallowing access to a particular resource. Permissionsessentially follow this form: "A is/isn't allowed to do B to C where D applies." For example, Jane (A)has permission to receive messages (B) from John's Amazon SQS queue (C), as long as she asks toreceive them before midnight on May 30, 2009 (D). Whenever Jane sends a request to Amazon SQSto use John's queue, the service checks to see if she has permission and if the request satisfies theconditions John set forth in the permission.

Statement

A statement is the formal description of a single permission, written in the access policy language. Youalways write a statement as part of a broader container document known as a policy (see the nextconcept).

Page 49: sqs-dg

Amazon Simple Queue Service Developer GuideKey Concepts

API Version 2009-02-0146

PolicyA policy is a document (written in the access policy language) that acts as a container for one or morestatements. For example, a policy could have two statements in it: one that states that Jane can useJohn's queue, and another that states that Bob cannot use John's queue. As shown in the followingfigure, an equivalent scenario would be to have two policies, one containing the statement that Janecan use John's queue, and another containing the statement that Bob cannot use John's queue.

The AWS service implementing access control (e.g., Amazon SQS) uses the information in thestatements (whether they're contained in a single policy or multiple) to determine if someonerequesting access to a resource should be granted that access. This appendix often uses the termpolicy interchangeably with statement, as they generally represent the same concept (an entity thatrepresents a permission).

IssuerThe issuer is the person who writes a policy to grant permissions for a resource. The issuer (bydefinition) is always the resource owner. AWS does not permit AWS service users to create policies forresources they don't own. If John is the resource owner, AWS authenticates John's identity when hesubmits the policy he's written to grant permissions for that resource.

PrincipalThe principal is the person or persons who receive the permission in the policy. The principal is A inthe statement "A has permission to do B to C where D applies." In a policy, you can set the principalto "anyone" (i.e., you can specify a wildcard to represent all people). You might do this, for example,if you don't want to restrict access based on the actual identity of the requester, but instead on someother identifying characteristic such as the requester's IP address.

ActionThe action is the activity the principal has permission to perform. The action is B in the statement "Ahas permission to do B to C where D applies." Typically, the action is just the operation in the requestto AWS. For example, Jane sends a request to Amazon SQS with Action=ReceiveMessage.

ResourceThe resource is the object the principal is requesting access to. The resource is C in the statement "Ahas permission to do B to C where D applies."

Conditions and KeysThe conditions are any restrictions or details about the permission. The condition is D in the statement"A has permission to do B to C where D applies." The part of the policy that specifies the conditionscan be the most detailed and complex of all the parts. Typical conditions are related to:

Page 50: sqs-dg

Amazon Simple Queue Service Developer GuideKey Concepts

API Version 2009-02-0147

• Date and time (e.g., the request must arrive in the next 15 minutes)

• IP address (e.g., the requester's IP address must be part of a particular CIDR range)

A key is the specific characteristic that is the basis for access restriction. For example, the date andtime of request.

You use both conditions and keys together to express the restriction. The easiest way to understandhow you actually implement a restriction is with an example: If you want to restrict access tobefore noon on April 1, 2009, you use the condition called DateLessThan. You use the key calledAWS:CurrentTime and set it to the value 2009-04-01T12:00:00Z. AWS defines the conditionsand keys you can use. The AWS service itself (e.g., Amazon SQS) might also define service-specifickeys. For more information about conditions, see Condition (p. 59). For more information about theavailable keys, see Available Keys (p. 63).

RequesterThe requester is the person who sends a request to an AWS service and asks for access to aparticular resource. The requester sends a request to AWS that essentially says: "Will you allow me todo B to C where D applies?"

EvaluationEvaluation is the process the AWS service uses to determine if an incoming request should be deniedor allowed based on the applicable policies. For information about the evaluation logic, see EvaluationLogic (p. 50).

EffectThe effect is the desired result that you (as the policy writer) wants a statement in a policy to returnat evaluation time. You specify this value when you write the statements in a policy, and the possiblevalues are deny and allow.

For example, you could write a policy that has a statement that denies all requests that come fromAntarctica (effect=deny given that the request uses an IP address allocated to Antarctica). Alternately,you could write a policy that has a statement that allows all requests that don't come from Antarctica(effect=allow, given that the request doesn't come from Antarctica). Although the two statementssound like they do the same thing, in the access policy language logic, they are different. For moreinformation, see Evaluation Logic (p. 50).

Although there are only two possible values you can specify for the effect (allow or deny), there can bethree different results at policy evaluation time: allow, soft deny, or hard deny. For more information,see the following concepts and Evaluation Logic (p. 50).

AllowAn allow results from a statement that has effect=allow. Example: Allow requests received before 1:00p.m. on April 30, 2010. An allow overrides all soft denies, but never a hard deny.

Hard DenyA hard deny results from a statement that has effect=deny. Example: Deny all requests fromAntarctica. Any request that comes from Antarctica will always be denied no matter what any otherpolicies might allow.

Soft DenyA soft deny results from a policy that logically produces a denial at evaluation time but can't actuallyreturn a deny because effect=allow in the statement. Example: Allow all requests that don't come from

Page 51: sqs-dg

Amazon Simple Queue Service Developer GuideArchitectural Overview

API Version 2009-02-0148

Antarctica. If a request comes from Antarctica, the policy results in a soft deny (for more information,see Evaluation Logic (p. 50)).

Architectural OverviewThe following figure and table describe the main components that interact to provide access control foryour resources.

You, the resource owner.

Your resources (contained within the AWS service; e.g., SQS queues).

Your policies.

Typically you have one policy per resource, although you could have multiple. The AWSservice itself provides an API you use to upload and manage your policies. For informationabout the content of the policies, see How to Write a Policy (p. 56).

Requesters and their incoming requests to the AWS service.

The access policy language evaluation code.

This is the set of code within the AWS service that evaluates incoming requests against theapplicable policies and determines whether the requester is allowed access to the resource.For information about how the service makes the decision, see Evaluation Logic (p. 50).

For the typical process of how the components work together, see Using the Access PolicyLanguage (p. 49).

Page 52: sqs-dg

Amazon Simple Queue Service Developer GuideUsing the Access Policy Language

API Version 2009-02-0149

Using the Access Policy LanguageThe following figure and table describe the general process of how access control works with theaccess policy language.

Process for Using Access Control with the Access Policy Language

1 You write a policy for your resource.

For example, you write a policy to specify permissions for your Amazon SQS queues. Formore information, see How to Write a Policy (p. 56).

2 You upload your policy to AWS.

The AWS service itself provides an API you use to upload your policies. For example, you usethe Amazon SQS SetQueueAttributes action to upload a policy for a particular AmazonSQS queue.

3 Someone sends a request to use your resource.

For example, a user sends a request to SQS to use one of your queues.

4 The AWS service determines which policies are applicable to the request.

For example, SQS looks at all the available SQS policies and determines which ones areapplicable (based on what the resource is, who the requester is, etc.).

5 The AWS service evaluates the policies.

For example, SQS evaluates the policies and determines if the requester is allowed to useyour queue or not. For information about the decision logic, see Evaluation Logic (p. 50).

6 The AWS service either denies the request or continues to process it.

For example, based on the policy evaluation result, SQS either returns an "Access denied"error to the requester or continues to process the request.

Related Topics

• Architectural Overview (p. 48)

Page 53: sqs-dg

Amazon Simple Queue Service Developer GuideEvaluation Logic

API Version 2009-02-0150

Evaluation LogicThe goal at evaluation time is to decide whether a given request from someone other than you (theresource owner) should be allowed or denied. The evaluation logic follows several basic rules:

• By default, all requests to use your resource coming from anyone but you are denied

• The order in which the policies are evaluated is not important

• An explicit deny (hard deny) overrides any allows

• An allow overrides any soft denies

The following flow chart and discussion describe in more detail how the decision is made.

By default, the decision starts at "deny."

The enforcement code then evaluates all the policies that are applicable to the request (basedon the resource, principal, action, and conditions).

The order in which the enforcement code evaluates the policies is not important.

Page 54: sqs-dg

Amazon Simple Queue Service Developer GuideEvaluation Logic

API Version 2009-02-0151

In all those policies, the enforcement code looks for an explicit "deny" instruction that wouldapply to the request.

If it finds even one, the enforcement point returns a decision of "deny" and the processis finished. Because there was an explicit deny, this is considered a hard deny (for moreinformation, see Hard Deny (p. 47)).

If no explicit deny is found, the enforcement code looks for any explicit "allow" instructions thatwould apply to the request.

If it finds even one, the enforcement code returns a decision of "allow" and the process is done(the service continues to process the request).

If no explicit allow is found, then the final decision is "deny." Because there was no explicitdeny or allow, this is considered a soft deny (for more information, see Soft Deny (p. 47)).

Note

The order of evaluation is irrelevant to the decision-making process; one explicit denyoverrides any allows that might be present in the policies.

The Interplay of Hard and Soft Denials

A hard deny results from a policy that has effect=deny. A soft deny results from a policy that wouldlogically return a deny, but can't because effect=allow in the policy. The distinction between a soft andhard deny is important because a soft deny can be overridden by an allow, but a hard deny can't. Thefollowing example illustrates this.

In this example, you create two policies:

• Policy A—Based on the time of the request

• Policy B—Based on the location of the request (i.e., where it comes from)

You want to allow requests that arrive on January 1, 2009, but deny requests that come fromAntarctica.

To illustrate the interplay of hard and soft denials, we'll compare what happens if you write Policy Bwith effect=allow (Scenario 1 in the following diagram) versus effect=deny (Scenario 2).

For both Scenario 1 and Scenario 2, you create Policy A to allow requests received on 1/1/2009.

For Scenario 1, you create Policy B1 to allow requests that don't come from Antarctica.

For Scenario 2, you create Policy B2 to deny requests that come from Antarctica.

Although Policy B1 and Policy B2 look like they do the same thing, the outcomes of Scenario 1 andScenario 2 are different when a request comes in from Antarctica on January 1, 2009. The followingfigure and discussion explain why.

Page 55: sqs-dg

Amazon Simple Queue Service Developer GuideEvaluation Logic

API Version 2009-02-0152

In both scenarios, Policy A returns an allow because the policy (by definition) allows requests thatcome in on January 1, 2009.

In Scenario 1, Policy B1 returns a soft deny, because (by definition) the policy only allows requestsif they don't come from Antarctica. This request does come from Antarctica. But, Policy B1 is onlydesigned to return an allow when the condition is met. The condition isn't met, so the policy returns asoft deny by default.

In Scenario 2, Policy B2 returns a hard deny, because by definition the policy denies requests thatcome from Antarctica. The condition is met, so the result is deny (a hard deny, because effect=deny).

A policy that returns an allow overrides any other policy that returns a soft deny. But a policy thatreturns a hard deny always overrides any other policy that returns an allow or soft deny. So, yourresults vary depending on how you write Policy B.

Page 56: sqs-dg

Amazon Simple Queue Service Developer GuideBasic Use Cases for Access Control

API Version 2009-02-0153

Basic Use Cases for Access ControlThis section gives a few examples of typical use cases for access control.

Use Case 1

Let's say you have a set of queues in the Amazon SQS system. In the simplest case, you wantto allow one or more AWS accounts a particular type of access to a queue (e.g., SendMessage,ReceiveMessage).

You can do this by simply using the Amazon SQS API action AddPermission. It takes a few inputparameters and automatically creates a policy in the SQS system for that queue. For this use case,you don't need to read this appendix or learn how to write a policy yourself, because SQS canautomatically create the policy for you.

The following example shows a policy that gives AWS account ID 1234-5678-9012 permission tosend and receive from a queue you own named queue2. In this example, your AWS account ID is9876-5432-1000.

{ "Version":"2008-10-17", "Id":"UseCase1", "Statement" : [ { "Sid":"1", "Effect":"Allow", "Principal" : { "AWS": "123456789012" }, "Action":["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321000/queue2", } ]}

Use Case 2

In this use case, you want to allow one or more AWS accounts access to your queues only for aspecific time period.

You need to know how to write your own policy for the queue because the SQS AddPermissionaction doesn't let you specify a time restriction when granting someone access to your queue.In this case, you would write your own policy and then upload it to the AWS system with theSetQueueAttributes action. Effectively the action sets your policy as an attribute of the queue.

The following example is the same as in use case 1, except it also includes a condition that restrictsaccess to before June 30, 2009, at noon (UTC).

{ "Version":"2008-10-17", "Id":"UseCase2", "Statement" : [ { "Sid":"1", "Effect":"Allow", "Principal" : { "AWS": "123456789012" },

Page 57: sqs-dg

Amazon Simple Queue Service Developer GuideBasic Use Cases for Access Control

API Version 2009-02-0154

"Action":["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321000/queue2", "Condition" : { "DateLessThan" : { "AWS:CurrentTime":"2009-06-30T12:00Z" } } } ]}

Use Case 3

In this use case, you want to allow access to your queues only if the requests come from your AmazonEC2 instances.

Again, you need to know how to write your own policy because the SQS AddPermission actiondoesn't let you specify an IP address restriction when granting access to your queue.

The following example builds on the example in use case 2, and also includes a condition that restrictsaccess to the IP address range 10.52.176.0/24. So in this example, a request from AWS account1234-5678-9012 to send or receive messages from queue2 would be allowed only if it came in beforenoon on June 30, 2009, and it came from the 10.52.176.0/24 address range.

{ "Version":"2008-10-17", "Id":"UseCase3", "Statement" : [ { "Sid":"1", "Effect":"Allow", "Principal" : { "AWS": "123456789012" }, "Action":["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321000/queue2", "Condition" : { "DateLessThan" : { "AWS:CurrentTime":"2009-06-30T12:00Z" }, "IpAddress" : { "AWS:SourceIp":"10.52.176.0/24" } } } ]}

Use Case 4

In this use case, you want to specifically deny a certain AWS account access to your queues.

Again, you need to know how to write your own policy because the SQS AddPermission actiondoesn't let you deny access to a queue; it only lets you grant access.

The following example is the same as in the original use case (#1), except it denies access to thespecified AWS account.

{

Page 58: sqs-dg

Amazon Simple Queue Service Developer GuideBasic Use Cases for Access Control

API Version 2009-02-0155

"Version":"2008-10-17", "Id":"UseCase4", "Statement" : [ { "Sid":"1", "Effect":"Deny", "Principal" : { "AWS": "123456789012" }, "Action":["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321000/queue2", } ]}

From these use cases, you can see that if you want to restrict access based on special conditionsor deny someone access entirely, you need to read this appendix and learn how to write your ownpolicies. You can also see that the policies themselves are not that complex and the access policylanguage is straightforward.

Page 59: sqs-dg

Amazon Simple Queue Service Developer GuideHow to Write a Policy

API Version 2009-02-0156

How to Write a PolicyTopics

• Basic Policy Structure (p. 56)

• Element Descriptions (p. 57)

• Supported Data Types (p. 63)

This section describes how to write policies and gives reference information about each policy element.

Basic Policy StructureEach policy is a JSON document. As illustrated in the following figure, a policy includes:

• Optional policy-wide information (at the top of the document)

• One or more individual statements

Each statement includes the core information about a single permission. If a policy includes multiplestatements, we apply a logical OR across the statements at evaluation time. If multiple policies areapplicable to a request, we apply a logical OR across the policies at evaluation time.

The information in a statement is contained within a series of elements. For information about theseelements, see Element Descriptions (p. 57).

Page 60: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0157

Example

The following simple policy allows an AWS developer with account ID 1234-5678-9012 to sendand read from the Amazon SQS queue named queue2 (owned by the developer with account ID9876-5432-1000), given that the request comes from the 10.52.176.0/24 address range, and therequest comes in before noon on June 30, 2009 (UTC).

{ "Version":"2008-10-17", "Id":"cd3ad3d9-2776-4ef1-a904-4c229d1642ee", "Statement" : [ { "Sid":"1", "Effect":"Allow", "Principal" : { "AWS": "123456789012" }, "Action":["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321000/queue2", "Condition" : { "IpAddress" : { "AWS:SourceIp":"10.52.176.0/24" }, "DateLessThan" : { "AWS:CurrentTime":"2009-06-30T12:00Z" } } } ]}

Element DescriptionsTopics

• Version (p. 57)

• Id (p. 58)

• Statement (p. 58)

• Sid (p. 58)

• Effect (p. 58)

• Principal (p. 58)

• Action (p. 59)

• Resource (p. 59)

• Condition (p. 59)

This section describes the elements you can use in a policy and its statements. The elements are listedhere in the general order you use them in a policy. The Id, Version, and Statement are top-levelpolicy elements; the rest are statement-level elements. JSON examples are provided.

All elements are optional for the purposes of parsing the policy document itself. The order of theelements doesn't matter (e.g., the Action element can come before the Principal element).Conditions are optional.

VersionThe Version is the access policy language version. This is an optional element, and currently the onlyallowed value is 2008-10-17.

Page 61: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0158

"Version":"2008-10-17"

IdThe Id is an identifier for the policy. We recommend you use a UUID for the value, or incorporate aUUID as part of the ID to ensure uniqueness.

Important

The AWS service (e.g., SQS) implementing the access policy language might require thiselement and have uniqueness requirements for it. For service-specific information aboutwriting policies, see Special Information for SQS Policies (p. 68).

"Id":"cd3ad3d9-2776-4ef1-a904-4c229d1642ee"

StatementThe Statement is the main element for a statement. It can include multiple elements (see thesubsequent sections in this guide).

The Statement element contains an array of individual statements. Each individual statement is adistinct JSON block enclosed in curly brackets { }.

"Statement":[{...},{...},{...}]

SidThe Sid (statement ID) is an optional identifier you provide for the policy statement. Essentially it is justa sub-ID of the policy document's ID.

Important

The AWS service (e.g., SQS) implementing the access policy language might require thiselement and have uniqueness requirements for it. For service-specific information aboutwriting policies, see Special Information for SQS Policies (p. 68).

"Sid" : "1"

EffectThe Effect is an optional element that indicates whether you want the statement to result in an allowor a hard deny (for more information, see Hard Deny (p. 47)). If no Effect is present in the policydocument, we assume a soft deny (for more information, see Soft Deny (p. 47)).

Valid values for Effect are Allow and Deny.

"Effect":"Allow"

PrincipalThe Principal is the person or persons who receive or are denied permission according to thepolicy. You must specify the principal by using the principal's AWS account ID (e.g., 1234-5678-9012,with or without the hyphens). You can specify multiple principals, or a wildcard (*) to indicateall possible users. You can view your account ID by logging in to your AWS account at http://aws.amazon.com and clicking Account Activity.

In JSON, you use "AWS": as a prefix for the principal's AWS account ID. In the following example, twoprincipals are included in the statement.

Page 62: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0159

"Principal":[ "AWS": "123456789012", "AWS": "999999999999"]

ActionThe Action is the specific type or types of access allowed or denied (for example, read or write). Youcan specify multiple values for this element. The values are free-form but must match values the AWSservice expects (for more information, see Special Information for SQS Policies (p. 68)). You canuse a wildcard (*) to give the principal access to all the actions the specific AWS service lets you sharewith other developers. For example, Amazon SQS lets you share only a particular subset of all thepossible SQS actions. So, using the wildcard doesn't give someone full control of the queue; it onlygives access to that particular subset of actions.

"Action":["SQS:SendMessage","SQS:ReceiveMessage"]

ResourceThe Resource is the object or objects the policy covers. The value can include a multi-charactermatch wildcard (*) or a single-character match wildcard (?) anywhere in the string. The values arefree-form, but must follow the format the AWS service (e.g., Amazon SQS) expects. For example, forAmazon SQS, you specify a queue in the following format: /<account ID of queue owner>/<queue name>. For example: /987654321012/queue1.

"Resource":"/987654321000/queue2"

ConditionThis section describes the Condition element and the information you can use inside the element.

The Condition Block

The Condition element is the most complex part of the policy statement. We refer to it as thecondition block, because although it has a single Condition element, it can contain multipleconditions, and each condition can contain multiple key-value pairs. The following figure illustrates this.Unless otherwise specified for a particular key, all keys can have multiple values.

When creating a condition block, you specify the name of each condition, and at least one key-value pair for each condition. AWS defines the conditions and keys you can use (they're listed in the

Page 63: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0160

subsequent sections). An example of a condition is NumericEquals. Let's say you have a fictionalresource, and you want to let John use it only if some particular numeric value foo equals either A orB, and another numeric value bar equals C. Then you would create a condition block that looks like thefollowing figure.

Let's say you also want to restrict John's access to after January 1, 2009. Then you would add anothercondition, DateGreaterThan, with a date equal to January 1, 2009. The condition block would thenlook like the following figure.

As illustrated in the following figure, we always apply a logical AND to the conditions within a conditionblock, and to the keys within a condition. We always apply a logical OR to the values for a single key.All conditions must be met to return an allow or a hard deny decision.

Page 64: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0161

As mentioned, AWS defines the conditions and keys you can use (for example, one of the keys isAWS:CurrentTime, which lets you restrict access based on the date and time). The AWS serviceitself (e.g., Amazon SQS) can also define its own service-specific keys. For a list of available keys, seeAvailable Keys (p. 63).

For a concrete example that uses real keys, let's say you want to let John access your Amazon SQSqueue under the following three conditions:

• The time is after 12:00 noon on 4/16/2009

• The time is before 3:00 p.m. on 4/16/2009

• The request comes from an IP address within the 192.168.176.0/24 range or the 192.168.143.0/24range

Your condition block has three separate conditions, and all three of them must be met for John to haveaccess to your queue.

The following shows what the condition block looks like in your policy.

"Condition" : { "DateGreaterThan" : { "AWS:CurrentTime" : "2009-04-16T12:00:00Z" } "DateLessThan": { "AWS:CurrentTime" : "2009-04-16T15:00:00Z" } "IpAddress" : { "AWS:SourceIp" : ["10.52.176.0/24","192.168.143.0/24"] }}

Condition Types

These are the general types of conditions you can specify:

• String

• Numeric

• Date and time

• Boolean

• IP address

String Conditions

String conditions let you constrain using string matching rules. The actual data type you use is a string.

Condition Description

StringEquals Strict matching

Short version: streq

StringNotEquals Strict negated matching

Short version: strneq

StringEqualsIgnoreCase Strict matching, ignoring case

Short version: streqi

StringNotEqualsIgnoreCase Strict negated matching, ignoring case

Short version: strneqi

Page 65: sqs-dg

Amazon Simple Queue Service Developer GuideElement Descriptions

API Version 2009-02-0162

Condition Description

StringLike Loose case-insensitive matching. The values can include a multi-character match wildcard (*) or a single-character match wildcard(?) anywhere in the string.

Short version: strl

StringNotLike Negated loose case-insensitive matching. The values can includea multi-character match wildcard (*) or a single-character matchwildcard (?) anywhere in the string.

Short version: strnl

Numeric Conditions

Numeric conditions let you constrain using numeric matching rules. You can use both whole integers ordecimal numbers. Fractional or irrational syntax is not supported.

Condition Description

NumericEquals Strict matching

Short version: numeq

NumericNotEquals Strict negated matching

Short version: numneq

NumericLessThan "Less than" matching

Short version: numlt

NumericLessThanEquals "Less than or equals" matching

Short version: numlteq

NumericGreaterThan "Greater than" matching

Short version: numgt

NumericGreaterThanEquals "Greater than or equals" matching

Short version: numgteq

Date Conditions

Date conditions let you constrain using date and time matching rules. You must specify all date/timevalues with one of the W3C implementations of the ISO 8601 date formats (for more information, go tohttp://www.w3.org/TR/NOTE-datetime). You use these conditions with the AWS:CurrentTime key torestrict access based on request time.

Note

Wildcards are not permitted for date conditions.

Condition Description

DateEquals Strict matching

Short version: dateeq

DateNotEquals Strict negated matching

Short version: dateneq

Page 66: sqs-dg

Amazon Simple Queue Service Developer GuideSupported Data Types

API Version 2009-02-0163

Condition Description

DateLessThan A point in time at which a key stops taking effect

Short version: datelt

DateLessThanEquals A point in time at which a key stops taking effect

Short version: datelteq

DateGreaterThan A point in time at which a key starts taking effect

Short version: dategt

DateGreaterThanEquals A point in time at which a key starts taking effect

Short version: dategteq

Boolean Conditions

Condition Description

Bool Strict Boolean matching

IP Address

IP address conditions let you constrain based on IP address matching rules. You use these with theAWS:SourceIp key. The value must be in the standard CIDR format (for example, 10.52.176.0/24).For more information, go to RFC 4632. The /32 netmask is the default, so you can omit the slash if youwant to specify an exact IP address match.

Condition Description

IpAddress Whitelisting based on the IP address or range

NotIpAddress Blacklisting based on the IP address or range

Available Keys

AWS provides a set of common keys supported by all AWS services that adopt the access policylanguage for access control. These keys are:

• AWS:CurrentTime (for date/time conditions)

• AWS:SecureTransport (Boolean representing whether the request was sent using SSL)

• AWS:SourceIp (the requester's IP address, for use with IP address conditions)

• AWS:UserAgent (information about the requester's client application, for use with string conditions)

Each AWS service that uses the access policy language might also provide service-specific keys. For alist of any service-specific keys you can use, see Special Information for SQS Policies (p. 68).

Supported Data TypesThis appendix lists the set of data types the access policy language supports. The language doesn'tsupport all types for each policy element (for the supported data types for each element, see ElementDescriptions (p. 57)).

The access policy language supports the following data types:

Page 67: sqs-dg

Amazon Simple Queue Service Developer GuideSupported Data Types

API Version 2009-02-0164

• Strings

• Numbers (Ints and Floats)

• Boolean

• Null

• Lists

• Maps

• Structs (which are just nested Maps)

The following table maps each data type to the serialization. Note that all policies must be in UTF-8.For information about the JSON data types, go to RFC 4627.

Type JSON

String String

Integer Number

Float Number

Boolean true false

Null null

Date String adhering to the W3C Profile of ISO 8601

IpAddress String adhering to RFC 4632

List Array

Object Object

Page 68: sqs-dg

Amazon Simple Queue Service Developer GuideAmazon SQS Policy Examples

API Version 2009-02-0165

Amazon SQS Policy ExamplesThis section shows example policies for common Amazon SQS use cases.

The following example policy gives the developer with AWS account number 123456789012 theSendMessage permission for the queue named 987654321098/queue1.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_SendMessage", "Effect": "Allow", "Principal": { "AWS": "123456789012" }, "Action": "SQS:SendMessage", "Resource": "/987654321098/queue1" }}

The following example policy gives the developer with AWS account number 123456789012 both theSendMessage and ReceiveMessage permission for the queue named 987654321098/queue1.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_Send_Receive", "Effect": "Allow", "Principal": { "AWS": "123456789012" }, "Action": ["SQS:SendMessage","SQS:ReceiveMessage"], "Resource": "/987654321098/queue1" }}

The following example policy gives two different developers (with AWS account numbers123456789012 and 555566667777) permission to use all actions that SQS allows shared access forthe queue named 987654321098/queue1.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_AllActions", "Effect": "Allow", "Principal": { "AWS": ["123456789012","555566667777"] }, "Action": "SQS:*", "Resource": "/987654321098/queue1" }}

Page 69: sqs-dg

Amazon Simple Queue Service Developer GuideAmazon SQS Policy Examples

API Version 2009-02-0166

The following example policy gives all users ReceiveMessage permission for the queue named987654321098/queue1.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_AnonymousAccess_ReceiveMessage", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:ReceiveMessage", "Resource": "/987654321098/queue1" }}

The following example policy gives all users ReceiveMessage permission for the queue named987654321098/queue1, but only between noon and 3:00 p.m. on January 31, 2009.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_AnonymousAccess_ReceiveMessage_TimeLimit", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:ReceiveMessage", "Resource": "/987654321098/queue1", "Condition" : { "DateGreaterThan" : { "AWS:CurrentTime":"2009-01-31T12:00Z" }, "DateLessThan" : { "AWS:CurrentTime":"2009-01-31T15:00Z" } } }}

The following example policy gives all users permission to use all possible SQS actions that canbe shared for the queue named 987654321098/queue1, but only if the request comes from the192.168.143.0/24 range.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": { "Sid":"Queue1_AnonymousAccess_AllActions_WhitelistIP", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:*", "Resource": "/987654321098/queue1",

Page 70: sqs-dg

Amazon Simple Queue Service Developer GuideAmazon SQS Policy Examples

API Version 2009-02-0167

"Condition" : { "IpAddress" : { "AWS:SourceIp":"192.168.143.0/24" } } }}

The following example policy has two statements:

• One that gives all users in the 192.168.143.0/24 range (except for 192.168.143.188) permission touse the SendMessage action for the queue named 987654321098/queue1.

• One that blacklists all users in the 10.1.2.0/24 range from using the queue.

{ "Version": "2008-10-17", "Id": "Queue1_Policy_UUID", "Statement": [ { "Sid":"Queue1_AnonymousAccess_SendMessage_IPLimit", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "SQS:SendMessage", "Resource": "/987654321098/queue1", "Condition" : { "IpAddress" : { "AWS:SourceIp":"192.168.143.0/24" }, "NotIpAddress" : { "AWS:SourceIp":"192.168.143.188/32" } } }, { "Sid":"Queue1_AnonymousAccess_AllActions_IPLimit_Deny", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "SQS:*", "Resource": "/987654321098/queue1", "Condition" : { "IpAddress" : { "AWS:SourceIp":"10.1.2.0/24" } } } ]}

Page 71: sqs-dg

Amazon Simple Queue Service Developer GuideSpecial Information for SQS Policies

API Version 2009-02-0168

Special Information for SQS PoliciesThe following list gives information specific to the SQS implementation of access control.

• SQS allows you to share only certain types of permissions (for more information, see UnderstandingPermissions (p. 41))

• Each policy must cover only a single queue (when writing a policy, don't include statements thatcover different queues)

• Each policy must have a unique policy ID (Id)

• Each statement in a policy must have a unique statement ID (sid)

• SQS does not implement any special keys to use when you write conditions; the only keys availableare the general AWS-wide keys.

Page 72: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0169

Glossary

Access Key ID An identifier associated with your Secret Access Key. Used forrequest authentication. For more information, see Your AWSIdentifiers (p. 22).

action The action is the activity the principal has permission to perform.The action is B in the statement "A has permission to do B to Cwhere D applies." The action is just the operation in the requestto SQS. For example, Jane sends a request to Amazon SQS withAction=ReceiveMessage. For more information, see SharedQueues (p. 40).

conditions The conditions are any restrictions or details about the permission.The condition is D in the statement "A has permission to do B toC where D applies." Following are some of the common types ofconditions:

issuer The issuer is the person who writes a policy to grant permissions toa resource. The issuer (by definition) is always the resource owner.AWS does not permit SQS users to create policies for resourcesthey don't own. If John is the resource owner, AWS authenticatesJohn's identity when he submits the policy he's written to grantpermissions for that resource.

message ID An identifier you get when you send a message to the queue.

permission A permission allows or disallows access to a particular resource.You can state any permission like this: "A has permission to do Bto C where D applies." For example, Jane (A) has permission toread messages (B) from John's Amazon SQS queue (C), as longas she asks to receive only a maximum of 10 messages from thequeue at a time (D). Whenever Jane sends a request to AmazonSQS to use John's queue, the service checks to see if she haspermission and if the request satisfies the conditions John set forthin the permission. For more information, see Shared Queues (p.40).

queue URL The URL uniquely identifying a queue.

policy A policy is the formal description of the permissions for a resource.The Access Policy Language distinguishes between a policy and

Page 73: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0170

a statement. A policy is the complete document that can containmany different permissions for a given resource. A statement isthe description of an individual permission. Therefore a policy cancontain multiple statements. For example, a policy could specifythat Jane can use John's queue (one statement), and Bob cannotuse John's queue (another statement).

principal The principal is the person or persons who receive the permissionin the policy. The principal is A in the statement "A has permissionto do B to C where D applies." In a policy, you may set the principalto "anyone" (i.e., you can specify a wildcard to represent allpeople). You might do this, for example, if you don't want to restrictaccess based on the actual identity of the requester, but insteadon some other identifying characteristic such as the requester's IPaddress.

Query This is a type of HTTP request that generally uses only the GET orPOST HTTP method and a query string with parameters.

receipt handle An identifier you get when you receive a message from the queue.You must provide this identifier when deleting the message fromthe queue.

requester The requester is the person who sends a request to an AWSservice and asks for access to a particular resource. The requestersends a request to AWS that essentially says: "Can A do B to Cwhere D applies?" In this question, the requester is A.

resource The resource is the object the principal is requesting access to.The resource is C in the statement "A has permission to do B to Cwhere D applies."

Secret Access Key A key that Amazon Web Services (AWS) assigns to you when yousign up for an AWS account. Used for request authentication. Formore information, see Your AWS Account (p. 22).

visibility timeout The length of time (in seconds) that a message that has beenreceived from a queue will be invisible to other receivingcomponents when they ask to receive messages. During thevisibility timeout, the component that received the message usuallyprocesses the message and then deletes it from the queue. Formore information, see Visibility Timeout (p. 10).

Page 74: sqs-dg

Amazon Simple Queue Service Developer GuideTypographical Conventions

API Version 2009-02-0171

Document Conventions

This section lists the common typographical and symbol use conventions for AWS technicalpublications.

Typographical ConventionsThis section describes common typographical use conventions.

Convention Description/Example

Call-outs A call-out is a number in the body text to give you a visual reference. Thereference point is for further discussion elsewhere.

You can use this resource regularly.

Code in text Inline code samples (including XML) and commands are identified with aspecial font.

You can use the command java -version.

Code blocks Blocks of sample code are set apart from the body and markedaccordingly.

# ls -l /var/www/html/index.html-rw-rw-r-- 1 root root 1872 Jun 21 09:33 /var/www/html/index.html# dateWed Jun 21 09:33:42 EDT 2006

Emphasis Unusual or important words and phrases are marked with a special font.

You must sign up for an account before you can use the service.

Internal crossreferences

References to a section in the same document are marked.

For more information, see Document Conventions (p. 71).

Logical values,constants, and regularexpressions, abstracta

A special font is used for expressions that are important to identify, but arenot code.

If the value is null, the returned response will be false.

Page 75: sqs-dg

Amazon Simple Queue Service Developer GuideTypographical Conventions

API Version 2009-02-0172

Convention Description/Example

Product and featurenames

Named AWS products and features are identified on first use.

Create an Amazon Machine Image (AMI).

Operations In-text references to operations.

Use the GetHITResponse operation.

Parameters In-text references to parameters.

The operation accepts the parameter AccountID.

Response elements In-text references to responses.

A container for one CollectionParent and one or moreCollectionItems.

Technical publicationreferences

References to other AWS publications. If the reference is hyperlinked, it isalso underscored.

For detailed conceptual information, refer to the Amazon Mechanical TurkDeveloper Guide.

User entered values A special font marks text that the user types.

At the password prompt, type MyPassword.

User interface controlsand labels

Denotes named items on the UI for easy identification.

On the File menu, click Properties.

Variables When you see this style, you must change the value of the content whenyou copy the text of a sample to a command line.

% ec2-register <your-s3-bucket>/image.manifest

See also the following symbol convention.

Page 76: sqs-dg

Amazon Simple Queue Service Developer GuideSymbol Conventions

API Version 2009-02-0173

Symbol ConventionsThis section describes the common use of symbols.

Convention Symbol Description/Example

Mutuallyexclusiveparameters

(Parentheses | and| vertical | bars)

Within a code description, bar separators denote options fromwhich one must be chosen.

% data = hdfread (start | stride | edge)

Optionalparameters

XML variabletext

[square brackets] Within a code description, square brackets denote completelyoptional commands or parameters.

% sed [-n, -quiet]

Use square brackets in XML examples to differentiate themfrom tags.

<CustomerId>[ID]</CustomerId>

Variables <arrow brackets> Within a code sample, arrow brackets denote a variable thatmust be replaced with a valid value.

% ec2-register <your-s3-bucket>/image.manifest

Page 77: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0174

IndexAaccess control policies, 44access control policy, 40Access Key ID, 22authentication, 21

Query, 29signature version 2, 29SOAP, 32

Bblocking messages, 10

Ccredentials, 22

Ddeleting queues with no activity, 7

Eendpoints, 15error response structure, 39Europe, 42

GGET requests, Query, 15

Hheaders, SOAP, 18, 38hiding messages, 10HMAC signatures, 24, 29, 37HTTPS

with Query requests, 29with SOAP requests, 37with SOAP WS-Security requests, 34

Iidentifiers, 22

Llocations

data, 42locking a message (see visibility timeout)

Mmessage ID, 9messages

blocking, 10order of, 8retention time, 12size of, 6

Nname of queue, 9number of messages in queue, 10

Oorder of messages, 8

Ppolicies, 44policy, 40pop (see ReceiveMessage)POST requests, Query, 16push (see SendMessage)

QQuery

about requests, 15authentication, 29

queuesabout, 7automatic deletion, 7deleting, 7endpoints, 42names, 9queue URL, 9shared, 40size, 10visibility timeout, 10

Rreceipt handle, 10receiving messages, 8Regions, 42response structure, 39retention time for messages, 12

Sscratchpad, 29Secret Access Key, 22shared queues, 40, 44signature version 2, 29signatures, 21

Query, 29SOAP, 32

size of messages, 6size of queue, 10SOAP

about requests, 18authentication, 32headers, 18, 38WS-Security, 32

SSLwith Query requests, 29with SOAP requests, 37with SOAP WS-Security requests, 34

Page 78: sqs-dg

Amazon Simple Queue Service Developer Guide

API Version 2009-02-0175

Ttime stamp format, 27time stamps, 24, 34

UUnited States, 42URL for the queue, 9

Vvisibility

message, 10visibility timeout, 10

WWS-Security, 32

XX.509 certificates, 32