amazon-s3 - 无服务器 s3 上传访问被拒绝

标签 amazon-s3 serverless-framework serverless access-denied

我正在尝试使用无服务器框架将图像上传到 S3 存储桶。当我在部署后调用端点时,代码失败并显示拒绝访问错误。我究竟做错了什么?
使用“无服务器日志 -f fileDownload”的错误:

ERROR   Unhandled Promise Rejection     {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"AccessDenied: Access Denied","reason":{"errorType":"AccessDenied","errorMessage":"Access Denied","code":"AccessDenied","message":"Access Denied","region":null,"time":"2020-05-08T14:06:11.767Z","requestId":"874D7C86A4C6BE45","extendedRequestId":"r8xyvcrK9su5c+slhX5L/uh4/Y/sdFnUgPcebHpSTNpbnf39EnAZJET750P8t0iXy8UR81SiYZc=","statusCode":403,"retryable":false,"retryDelay":17.606445772028543,"stack":
["AccessDenied: Access Denied"
,"    at Request.extractError (/var/task/node_modules/aws-sdk/lib/services/s3.js:835:35)"
,"    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:106:20)"
,"    at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:78:10)"
,"    at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:683:14)"
,"    at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)"
,"    at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)"
,"    at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10"
,"    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)"
,"    at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:685:12)"
,"    at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:116:18)"
]}
,"promise":{},"stack":
["Runtime.UnhandledPromiseRejection: AccessDenied: Access Denied"
,"    at process.<anonymous> (/var/runtime/index.js:35:15)"
,"    at process.emit (events.js:310:20)"
,"    at process.EventEmitter.emit (domain.js:482:12)"
,"    at processPromiseRejections (internal/process/promises.js:209:33)"
,"    at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
serverless.yml:
service: serverless-resize-image-s3

custom:
  # This line should create the bucket. Strange though that I don't see the bucket when
  # I login to the AWS console. Even stranger is that when I tried to create the bucket
  # using the console I get an error saying the bucket exists, even though its invisible.
  bucket: files
  region: us-east-1
  default_stage: prod
  apigwBinary: 
    types:
      - '*/*'

plugins:
  - serverless-apigw-binary
  - serverless-apigwy-binary
  # Offline is needed to run the thing in a docker container and test using minio
  # This is the only part of the code that actually works at the moment.
  - serverless-offline

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, self:custom.default_stage}
  # I've seen a number of variations on this theme, so far no configuration I've tried
  # has resulted in the AccessDenied error disappearing
  iamRoleStatements:
    - Effect: 'Allow'
      Action:
        # I don't explicitly list anything but I read somewhere that a 404 can turn into a
        # 403 if this right doesn't exist
        - 's3:ListBucket'
      # Found somebody saying that the arn should not have the '/*' for ListBucket, I guess that
      # does make sense
      Resource: "arn:aws:s3:::*"
    - Effect: 'Allow'
      Action:
        - 's3:PutObject'
        - 's3:GetObject'
      # Found somebody saying that a reference to somewhere else in the yml didn't work for him
      # And somebody else suggested just replacing the whole thing with a *
      Resource: "arn:aws:s3:::*/*"
      #Resource: "arn:aws:s3:::files/*"
      #Resource: "arn:aws:s3:::${self:custom.bucket}/*"

package:
  excludeDevDependencies: true
  exclude:
# I thought that excluding aws-sdk would be necessary in order to use the global
# one instead. But even with this line here I still get my AccessDenied errors.
    - node_modules/aws-sdk

# If I ignore everything in node_modules I get 'Cannot find module' errors
# But allowing each individual module can take a while. A dir list shows 268
# entries.
#    - node_modules/**
#    - '!node_modules/serverless-http/**'
#    - '!node_modules/express/**'
#    - '!node_modules/depd/**'
#    - '!node_modules/merge-descriptors/**'

functions:
  fileUpload:
    handler: upload.app
    events:
      - http: put /v1/upload
  fileDownload:
    handler: download.app
    events:
      # This is the endpoint I'm testing the s3 query with, its simpler than v2.
      - http: get /v1/download
      - http:
          method: get
          path: /v2/download
          # This is the part I actually want to test, found a post somewhere that said the
          # serverless-apigwy-binary plugin will use this to turn my base64 data into binary.
          # Hopefully that will allow me to see my image in the browser
          contentHandling: CONVERT_TO_BINARY
  imageResize:
    handler: image.app
    events:
      - http: get /v1/image
download.js 的来源:
'use strict';

const serverless = require('serverless-http');
const express = require('express');
const AWS = require('aws-sdk');
const fs = require('fs');

const app = express();
const s3 = new AWS.S3();

app.get('/v1/download', async (req, res, cb) => {
    var fileKey = req.query['id'];

    const data = await s3.getObject({ Bucket: 'files', Key: fileKey }).promise();

    res.setHeader('Content-Type', 'image/png')
    res.end(data.toString('base64'));
});

module.exports.app = serverless(app);
任何帮助,将不胜感激。似乎我不允许发布问题,直到有更多文本而不仅仅是代码。

最佳答案

要上传到存储桶,我只是使用这种方式:

iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:PutObject
      Resource: "arn:aws:s3:::my-bucket/*"
我看到你正在使用两个 - Effect: Allow ,也许问题就在那里。尝试仅使用一种。或者您可以尝试使用先上传的效果,仅用于测试:
 iamRoleStatements:
    - Effect: 'Allow'
      Action:
        - 's3:PutObject'
        - 's3:GetObject'
      Resource: "arn:aws:s3:::*/*"
    - Effect: 'Allow'
      Action:
        - 's3:ListBucket'
      Resource: "arn:aws:s3:::*"
我假设您的用户权限已启用。如果没有,那是肯定的。在 AWS IAM 上启用权限。

关于amazon-s3 - 无服务器 s3 上传访问被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61681230/

相关文章:

javascript - 如何 stub 一个使用 HTTP 响应进行响应的函数?

hadoop - 如何从 Sqoop 导入中捕获已处理记录的计数?

aws-lambda - 为什么只有某些部署目标才会出现错误 "Code uncompressed size is greater than max allowed size of 272629760"?

amazon-web-services - 现有 S3 的无服务器触发器因后缀重叠而失败

aws-cloudformation - 无服务器框架错误 策略语句必须包含操作

amazon-web-services - AWS s3 - 触发对象创建,函数被连续调用

node.js - 无法使用 SES/Lambda 发送电子邮件,但代码可以在容器上运行

amazon-sns - 创建订阅时,无服务器 SNS filterPolicy 不会设置过滤器

node.js - DynamoDB BatchGet 总是给出 "The provided key element does not match the schema"

python - boto3.resource(s3) 相当于 boto3.client(s3) get_object_tagging 方法?