├── .all-contributorsrc ├── .github └── workflows │ ├── golangci-lint.yml │ └── test.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── Version ├── browse.go ├── browse_test.go ├── caddyfile.go ├── caddyfile_test.go ├── errors.go ├── example ├── Caddyfile ├── LOCALSTACK_EXAMPLE.md ├── awslocal │ └── populate.sh └── docker-compose.yml ├── go.mod ├── go.sum ├── s3proxy.go ├── s3proxy_test.go ├── tag.sh └── testdata ├── _404.txt ├── default_error_page.txt ├── inner └── index.html ├── test.json └── to-delete.json /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "caddy-s3-proxy", 3 | "repoType": "github", 4 | "files": [ 5 | "README.md" 6 | ], 7 | "commit": true, 8 | "imageSize": 100, 9 | "contributorsPerLine": 7, 10 | "contributorsSortAlphabetically": false, 11 | "badgeTemplate": "[![All Contributors](https://img.shields.io/badge/all_contributors-<%= contributors.length %>-orange.svg?style=flat-square)](#contributors)", 12 | "contributorTemplate": "\">\" width=\"<%= options.imageSize %>px;\" alt=\"\"/>
<%= contributor.name %>
", 13 | "skipCi": true, 14 | "contributors": [ 15 | { 16 | "login": "rayjlinden", 17 | "name": "rayjlinden", 18 | "avatar_url": "https://avatars0.githubusercontent.com/u/42587610?v=4", 19 | "profile": "https://github.com/rayjlinden", 20 | "contributions": [ 21 | "code", 22 | "doc" 23 | ] 24 | }, 25 | { 26 | "login": "gilbsgilbs", 27 | "name": "Gilbert Gilb's", 28 | "avatar_url": "https://avatars2.githubusercontent.com/u/3407667?v=4", 29 | "profile": "https://github.com/gilbsgilbs", 30 | "contributions": [ 31 | "code", 32 | "doc", 33 | "test" 34 | ] 35 | }, 36 | { 37 | "login": "christoph-kluge", 38 | "name": "Christoph Kluge", 39 | "avatar_url": "https://avatars3.githubusercontent.com/u/1446269?v=4", 40 | "profile": "https://github.com/christoph-kluge", 41 | "contributions": [ 42 | "bug", 43 | "code" 44 | ] 45 | } 46 | ], 47 | "projectOwner": "lindenlab", 48 | "repoHost": "https://github.com" 49 | } 50 | -------------------------------------------------------------------------------- /.github/workflows/golangci-lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci-lint 2 | on: 3 | push: 4 | tags: 5 | - v* 6 | branches: 7 | - master 8 | pull_request: 9 | jobs: 10 | golangci: 11 | name: lint 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/setup-go@v4 15 | with: 16 | go-version: '1.17' 17 | cache: false 18 | - uses: actions/checkout@v3 19 | - name: golangci-lint 20 | uses: golangci/golangci-lint-action@v3 21 | with: 22 | # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. 23 | version: v1.29 24 | 25 | # golangci-lint seems to be randomly slow. Increasing the timeout circumvents this issue. 26 | args: --timeout 5m 27 | 28 | # See here for more info on this action: 29 | # https://github.com/golangci/golangci-lint-action 30 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: Test 4 | jobs: 5 | test: 6 | strategy: 7 | matrix: 8 | go-version: [1.14.x, 1.15.x] 9 | runs-on: ubuntu-latest 10 | services: 11 | localstack: 12 | image: localstack/localstack:latest 13 | ports: 14 | - 4566:4566 15 | env: 16 | SERVICES: s3 17 | env: 18 | AWS_SECRET_ACCESS_KEY: dummy 19 | AWS_ACCESS_KEY_ID: dummy 20 | AWS_REGION: dummy 21 | AWS_ENDPOINT: http://localhost:4566 22 | steps: 23 | - name: Install Go 24 | uses: actions/setup-go@v2 25 | with: 26 | go-version: ${{ matrix.go-version }} 27 | - name: Checkout code 28 | uses: actions/checkout@v2 29 | - name: Test 30 | run: go test -v -cover ./... 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | caddy 2 | cover.* 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:buster-slim 2 | 3 | COPY caddy /usr/bin/caddy 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | export GO111MODULE=on 2 | VERSION := $(shell cat Version) 3 | COVER_TARGET ?= 30 4 | 5 | # Set for running tests against localstack 6 | export AWS_SECRET_ACCESS_KEY=dummy 7 | export AWS_ACCESS_KEY_ID=dummy 8 | export AWS_REGION=dummy 9 | export AWS_ENDPOINT=http://localhost:4566 10 | 11 | .PHONY: build 12 | build: caddy 13 | 14 | caddy: *.go go.mod Makefile 15 | # go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest -- install xcaddy if you don't have it 16 | xcaddy build --output caddy --with github.com/lindenlab/caddy-s3-proxy=${CURDIR} 17 | 18 | .PHONY: docker 19 | docker: caddy ## build a docker image for caddy with the s3proxy 20 | @docker build -t caddy . 21 | 22 | .PHONY: test 23 | test: ## Run go test on source base 24 | @go test --race 25 | 26 | .PHONY: cover 27 | cover: ## Generate test coverage results 28 | @go test -gcflags=-l --covermode=count -coverprofile cover.profile ${PKGS} 29 | @go tool cover -html cover.profile -o cover.html 30 | @go tool cover -func cover.profile -o cover.func 31 | @tail -n 1 cover.func | awk '{if (int($$3) >= ${COVER_TARGET}) {print "Coverage good: " $$3} else {print "Coverage is less than ${COVER_TARGET}%: " $$3; exit 1}}' 32 | 33 | .PHONY: lint 34 | lint: ## Run golint on source base 35 | @golangci-lint run ./... 36 | 37 | .PHONY: localstack 38 | localstack: ## Launch localstack to run tests against 39 | @docker-compose -f example/docker-compose.yml up -d localstack 40 | 41 | .PHONY: example 42 | example: docker ## Run docker-compose up in the example directory 43 | @docker-compose -f example/docker-compose.yml up 44 | 45 | .DEFAULT_GOAL := help 46 | .PHONY: help 47 | help: ## Display this help message 48 | @grep -E '^[ a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \ 49 | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}' 50 | 51 | .PHONY: clean 52 | clean: ## Delete any generated files 53 | @rm -f caddy 54 | 55 | .PHONY: version 56 | version: ## Show the version the Makefile will build 57 | @echo ${VERSION} 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![golangci-lint Actions Status](https://github.com/lindenlab/caddy-s3-proxy/workflows/golangci-lint/badge.svg)](https://github.com/lindenlab/caddy-s3-proxy/actions) 2 | [![Test Actions Status](https://github.com/lindenlab/caddy-s3-proxy/workflows/Test/badge.svg)](https://github.com/lindenlab/caddy-s3-proxy/actions) 3 | [![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors) 4 | 5 | # caddy-s3-proxy 6 | 7 | caddy-s3-proxy allows you to proxy requests directly from S3. 8 | 9 | S3 does have the website option, in which case, a normal reverse proxy could be used to display S3 data. 10 | However, it is sometimes inconvient to do that. This module lets you access S3 data even if website access 11 | is not configured on your bucket. 12 | 13 | ## Making a version of caddy with this plugin 14 | 15 | With caddy 2 you can use [xcaddy](https://github.com/caddyserver/xcaddy) to build a version of caddy 16 | with this plugin installed. To install xcaddy do: 17 | ``` 18 | go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest 19 | ``` 20 | 21 | This repo has a Makefile to make it easier to build a new version of caddy with this plugin. Just type: 22 | ``` 23 | make build 24 | ``` 25 | 26 | You can run ```make docker``` do build a local image you can test with. 27 | 28 | ## Configuration 29 | The Caddyfile directive would look something like this: 30 | ``` 31 | s3proxy [] { 32 | bucket 33 | region 34 | profile 35 | index 36 | endpoint 37 | root 38 | enable_put 39 | enable_delete 40 | force_path_style 41 | errors 42 | errors 43 | browse [] 44 | } 45 | ``` 46 | 47 | | option | type | required | default | help | 48 | |-----------|:------:|-----------|---------|------| 49 | | bucket | string | yes | | S3 bucket name | 50 | | region | string | yes-ish | env AWS_REGION | S3 region - if not give in the Caddyfile then AWS_REGION env var must be set.| 51 | | profile | string | no | empty string | AWS profile if using shared credentials files. | 52 | | endpoint | string | no | aws default | S3 hostname | 53 | | index | string[] | no | [index.html, index.txt] | Index files to look up for dir path | 54 | | root | string | no | | Set a "prefix" to be added to key | 55 | | enable_put | bool | no | false | Allow PUT method to be sent through proxy | 56 | | enable_delete | bool | no | false | Allow DELETE method to be sent through proxy | 57 | | force_path_style | bool | no | false | Set this to `true` to force S3 request to use path-style addressing | 58 | | use_accelerate | bool | no | false | Set this to `true` to enable S3 Accelerate feature | 59 | | errors | [int, ] string | no | | Custom error page or use "pass_through" to write nothing for errors. | 60 | | browse | [string] | no | | Turns on a directory view for partial keys, an optional path to a template can be given | 61 | 62 | ## Credentials 63 | 64 | This module uses the default providor chain to get credentials for access to S3. This provides several more 65 | secure options to provide credentials for accessing S3 without putting the credentials in the Caddyfile. 66 | The methods include (and are looked for in this order): 67 | 68 | 1) Environment variables. I.e. AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY 69 | 70 | 2) Shared credentials file. (Located at ~/.aws/credentials) 71 | (You may pass the optional profile directive to select specific credentials.) 72 | 73 | 3) If your application uses an ECS task definition or RunTask API operation, IAM role for tasks. 74 | 75 | 4) If your application is running on an Amazon EC2 instance, IAM role for Amazon EC2. 76 | 77 | For much more detail on the various options for setting AWS credentials see here: 78 | https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html 79 | 80 | ## Works with localstack! 81 | 82 | The s3 proxy works great with localstack for local testing. Just set the endpoint directive to your localstack 83 | instance. You will also want to set the `force_path_style` directive as well since localstack currently does not 84 | support virtual style addressing. In fact, all of our examples use localstack - check out the examples directory. 85 | 86 | ## Handling errors 87 | 88 | When accessing S3 you may get errors like keyNotFound, bucket does not exist, or ACL permissions problems. By default 89 | this proxy will map those errors to an http error - like 404, 403 or 500. 90 | 91 | However, with the `errors` directive you have a couple of more options. You can specify a S3 key that may contain HTML 92 | to display rather than just returning an error code. This can be done for a specific error or all errors. For example, 93 | ``` 94 | errors 403 /key/path/to/permissionerr.html 95 | errors /key/path/to/defaulterr.html 96 | ``` 97 | This will display the page permissionerr.html for any 403 errors and defaulterr.html for all other errors. 98 | 99 | There is a special option to "pass through" on an error and let the next Caddy handler deal with the request. For example, 100 | ``` 101 | errors 404 pass_through 102 | errors /key/path/to/defaulterr.html 103 | ``` 104 | 105 | Will pass 404 errors onto the next handler. All other errors will show the page defaulterr.html. 106 | 107 | Note: The `errors` direction only applies to GET method requests. PUT and DELETE errors just return the code. 108 | 109 | ## Examples you can play with 110 | 111 | In the examples directory is an example of using the s3proxy with localstack. 112 | Localstack contains a working version of S3 you can use for local development. 113 | 114 | Check out the examples [here](example/LOCALSTACK_EXAMPLE.md). 115 | You can also just run ```make example``` to build a docker image with the plugin and launch the compose example. 116 | 117 | # Contributors 118 | 119 | A big thank you to folks who have contributed to this project! 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 |

rayjlinden

Gilbert Gilb's

Christoph Kluge
131 | 132 | 133 | 134 | 135 | 136 | -------------------------------------------------------------------------------- /Version: -------------------------------------------------------------------------------- 1 | 0.5.8 2 | -------------------------------------------------------------------------------- /browse.go: -------------------------------------------------------------------------------- 1 | package caddys3proxy 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "html/template" 7 | "net/http" 8 | "net/url" 9 | "path" 10 | "strconv" 11 | "strings" 12 | "sync" 13 | 14 | "github.com/aws/aws-sdk-go/aws" 15 | "github.com/aws/aws-sdk-go/service/s3" 16 | "github.com/dustin/go-humanize" 17 | ) 18 | 19 | var bufPool = sync.Pool{ 20 | New: func() interface{} { 21 | return new(bytes.Buffer) 22 | }, 23 | } 24 | 25 | type PageObj struct { 26 | Count int64 `json:"count"` 27 | Items []Item `json:"items"` 28 | MoreLink string `json:"more"` 29 | } 30 | 31 | type Item struct { 32 | Name string `json:"name"` 33 | IsDir bool `json:"is_dir"` 34 | Key string `json:"key"` 35 | Url string `json:"url"` 36 | Size string `json:"size"` 37 | LastModified string `json:"last_modified"` 38 | } 39 | 40 | // GenerateJson generates JSON output for the PageObj 41 | func (po PageObj) GenerateJson(w http.ResponseWriter) error { 42 | buf := bufPool.Get().(*bytes.Buffer) 43 | buf.Reset() 44 | defer bufPool.Put(buf) 45 | 46 | err := json.NewEncoder(buf).Encode(po) 47 | if err != nil { 48 | return err 49 | } 50 | 51 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 52 | _, err = buf.WriteTo(w) 53 | return err 54 | } 55 | 56 | func (p S3Proxy) ConstructListObjInput(r *http.Request, key string) s3.ListObjectsV2Input { 57 | // We need to strip the first '/' from the key to make it a valid prefix 58 | prefix := strings.TrimPrefix(key, "/") 59 | 60 | input := s3.ListObjectsV2Input{ 61 | Bucket: aws.String(p.Bucket), 62 | Prefix: aws.String(prefix), 63 | Delimiter: aws.String("/"), 64 | } 65 | 66 | nextToken := r.URL.Query().Get("next") 67 | if nextToken != "" { 68 | input.ContinuationToken = aws.String(nextToken) 69 | } 70 | 71 | maxPerPage := r.URL.Query().Get("max") 72 | if maxPerPage != "" { 73 | maxKeys, err := strconv.ParseInt(maxPerPage, 10, 64) 74 | if err == nil && maxKeys > 0 && maxKeys <= 1000 { 75 | input.MaxKeys = aws.Int64(maxKeys) 76 | } 77 | } 78 | 79 | return input 80 | } 81 | 82 | // GenerateHtml generates html output for the PageObj 83 | func (po PageObj) GenerateHtml(w http.ResponseWriter, template *template.Template) error { 84 | buf := bufPool.Get().(*bytes.Buffer) 85 | buf.Reset() 86 | defer bufPool.Put(buf) 87 | 88 | err := template.Execute(buf, po) 89 | if err != nil { 90 | return err 91 | } 92 | 93 | w.Header().Set("Content-Type", "text/html; charset=utf-8") 94 | _, err = buf.WriteTo(w) 95 | return err 96 | } 97 | 98 | func (p S3Proxy) MakePageObj(result *s3.ListObjectsV2Output) PageObj { 99 | po := PageObj{} 100 | po.Count = *result.KeyCount 101 | if result.NextContinuationToken != nil { 102 | var nextUrl url.URL 103 | queryItems := nextUrl.Query() 104 | 105 | queryItems.Add("next", *result.NextContinuationToken) 106 | if result.MaxKeys != nil { 107 | queryItems.Add("max", strconv.FormatInt(*result.MaxKeys, 10)) 108 | } 109 | nextUrl.RawQuery = queryItems.Encode() 110 | po.MoreLink = nextUrl.String() 111 | } 112 | 113 | for _, dir := range result.CommonPrefixes { 114 | name := path.Base(*dir.Prefix) 115 | dirPath := "./" + name + "/" 116 | po.Items = append(po.Items, Item{ 117 | Url: dirPath, 118 | Name: name, 119 | IsDir: true, 120 | }) 121 | } 122 | for _, obj := range result.Contents { 123 | name := path.Base(*obj.Key) 124 | itemPath := "./" + name 125 | size := humanize.Bytes(uint64(*obj.Size)) 126 | timeAgo := humanize.Time(*obj.LastModified) 127 | po.Items = append(po.Items, Item{ 128 | Name: name, 129 | Key: *obj.Key, 130 | Url: itemPath, 131 | Size: size, 132 | LastModified: timeAgo, 133 | IsDir: false, 134 | }) 135 | } 136 | 137 | return po 138 | } 139 | 140 | // This is a lame ass default template - needs to get better 141 | const defaultBrowseTemplate = ` 142 | 143 | 144 |
    145 | {{- range .PageObj }} 146 |
  • 147 | {{- if .IsDir}} 148 | {{html .Name}} 149 | {{- else}} 150 | {{html .Name}} Size: {{html .Size}} Last Modified: {{html .LastModified}} 151 | {{- end}} 152 |
  • 153 | {{- end }} 154 |
155 |

number of items: {{ .Count }}

156 | {{- if .MoreLink }} 157 | more... 158 | {{- end }} 159 | 160 | ` 161 | -------------------------------------------------------------------------------- /browse_test.go: -------------------------------------------------------------------------------- 1 | package caddys3proxy 2 | 3 | import ( 4 | "net/http" 5 | "net/url" 6 | "reflect" 7 | "testing" 8 | "time" 9 | 10 | "github.com/aws/aws-sdk-go/aws" 11 | "github.com/aws/aws-sdk-go/service/s3" 12 | ) 13 | 14 | func TestConstructListObjInput(t *testing.T) { 15 | type testCase struct { 16 | name string 17 | key string 18 | bucket string 19 | queryString string 20 | expected s3.ListObjectsV2Input 21 | } 22 | 23 | testCases := []testCase{ 24 | testCase{ 25 | name: "no query options", 26 | bucket: "myBucket", 27 | key: "/mypath/", 28 | expected: s3.ListObjectsV2Input{ 29 | Bucket: aws.String("myBucket"), 30 | Delimiter: aws.String("/"), 31 | Prefix: aws.String("mypath/"), 32 | }, 33 | }, 34 | testCase{ 35 | name: "max option", 36 | bucket: "myBucket", 37 | key: "/mypath/", 38 | queryString: "?max=20", 39 | expected: s3.ListObjectsV2Input{ 40 | Bucket: aws.String("myBucket"), 41 | Delimiter: aws.String("/"), 42 | Prefix: aws.String("mypath/"), 43 | MaxKeys: aws.Int64(20), 44 | }, 45 | }, 46 | testCase{ 47 | name: "max with next", 48 | bucket: "myBucket", 49 | key: "/mypath/", 50 | queryString: "?max=20&next=FOO", 51 | expected: s3.ListObjectsV2Input{ 52 | Bucket: aws.String("myBucket"), 53 | Delimiter: aws.String("/"), 54 | Prefix: aws.String("mypath/"), 55 | MaxKeys: aws.Int64(20), 56 | ContinuationToken: aws.String("FOO"), 57 | }, 58 | }, 59 | } 60 | for _, tc := range testCases { 61 | r := http.Request{} 62 | u, _ := url.Parse(tc.queryString) 63 | r.URL = u 64 | p := S3Proxy{ 65 | Bucket: tc.bucket, 66 | } 67 | result := p.ConstructListObjInput(&r, tc.key) 68 | if !reflect.DeepEqual(tc.expected, result) { 69 | t.Errorf("Expected obj %v, got %v.", tc.expected, result) 70 | } 71 | } 72 | } 73 | 74 | func TestMakePageObj(t *testing.T) { 75 | p := S3Proxy{} 76 | listOutput := s3.ListObjectsV2Output{ 77 | KeyCount: aws.Int64(20), 78 | NextContinuationToken: aws.String("next_token"), 79 | MaxKeys: aws.Int64(20), 80 | CommonPrefixes: []*s3.CommonPrefix{ 81 | &s3.CommonPrefix{ 82 | Prefix: aws.String("/mydir"), 83 | }, 84 | &s3.CommonPrefix{ 85 | Prefix: aws.String("/otherdir"), 86 | }, 87 | }, 88 | Contents: []*s3.Object{ 89 | &s3.Object{ 90 | Key: aws.String("/path/to/myobj"), 91 | Size: aws.Int64(1024), 92 | LastModified: aws.Time(time.Date(1845, time.November, 10, 23, 0, 0, 0, time.UTC)), 93 | }, 94 | }, 95 | } 96 | 97 | result := p.MakePageObj(&listOutput) 98 | expected := PageObj{ 99 | Count: 20, 100 | MoreLink: "?max=20&next=next_token", 101 | Items: []Item{ 102 | Item{ 103 | Url: "./mydir/", 104 | IsDir: true, 105 | Name: "mydir", 106 | }, 107 | Item{ 108 | Url: "./otherdir/", 109 | IsDir: true, 110 | Name: "otherdir", 111 | }, 112 | Item{ 113 | Url: "./myobj", 114 | Key: "/path/to/myobj", 115 | IsDir: false, 116 | Name: "myobj", 117 | Size: "1.0 kB", 118 | LastModified: "a long while ago", 119 | }, 120 | }, 121 | } 122 | 123 | if !reflect.DeepEqual(expected, result) { 124 | t.Errorf("Expected obj %v, got %v.", expected, result) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /caddyfile.go: -------------------------------------------------------------------------------- 1 | package caddys3proxy 2 | 3 | import ( 4 | "strconv" 5 | 6 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" 7 | "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile" 8 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" 9 | ) 10 | 11 | func init() { 12 | httpcaddyfile.RegisterHandlerDirective("s3proxy", parseCaddyfile) 13 | } 14 | 15 | // parseCaddyfile parses the s3proxy directive. It enables the proxying 16 | // requests to S3 and configures it with this syntax: 17 | // 18 | // s3proxy [] { 19 | // root 20 | // region 21 | // profile 22 | // bucket 23 | // index 24 | // hide 25 | // endpoint 26 | // enable_put 27 | // enable_delete 28 | // force_path_style 29 | // use_accelerate 30 | // errors [] [|pass_through] 31 | // browse [