2016-01-25 20:29:20 -05:00
/ *
2019-04-09 14:39:42 -04:00
* MinIO Cloud Storage , ( C ) 2016 - 2019 MinIO , Inc .
2016-01-25 20:29:20 -05:00
*
* Licensed under the Apache License , Version 2.0 ( the "License" ) ;
* you may not use this file except in compliance with the License .
* You may obtain a copy of the License at
*
* http : //www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing , software
* distributed under the License is distributed on an "AS IS" BASIS ,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , either express or implied .
* See the License for the specific language governing permissions and
* limitations under the License .
* /
2016-08-18 19:23:42 -04:00
package cmd
2016-01-23 22:44:32 -05:00
import (
2017-02-09 02:39:08 -05:00
"archive/zip"
2018-03-15 16:27:16 -04:00
"context"
2016-08-30 13:04:50 -04:00
"encoding/json"
2016-01-23 22:44:32 -05:00
"fmt"
2017-05-10 12:54:24 -04:00
"io"
2016-01-23 22:44:32 -05:00
"net/http"
2018-06-05 13:48:51 -04:00
"net/url"
2016-02-04 01:46:45 -05:00
"os"
2016-02-22 01:38:38 -05:00
"path"
2016-02-04 01:46:45 -05:00
"runtime"
"strconv"
2016-09-23 04:24:49 -04:00
"strings"
2018-09-27 23:36:17 -04:00
"sync"
2016-01-23 22:44:32 -05:00
"time"
2018-03-15 16:27:16 -04:00
humanize "github.com/dustin/go-humanize"
2018-09-27 23:36:17 -04:00
snappy "github.com/golang/snappy"
2016-03-31 09:57:29 -04:00
"github.com/gorilla/mux"
2016-02-12 21:55:17 -05:00
"github.com/gorilla/rpc/v2/json2"
2018-04-24 18:53:30 -04:00
miniogopolicy "github.com/minio/minio-go/pkg/policy"
2018-06-05 13:48:51 -04:00
"github.com/minio/minio-go/pkg/s3utils"
2019-03-12 20:57:08 -04:00
"github.com/minio/minio-go/pkg/set"
2017-01-23 21:07:22 -05:00
"github.com/minio/minio/browser"
2018-08-17 15:52:14 -04:00
"github.com/minio/minio/cmd/crypto"
2018-04-05 18:04:40 -04:00
"github.com/minio/minio/cmd/logger"
2017-10-31 14:54:32 -04:00
"github.com/minio/minio/pkg/auth"
2018-05-11 15:02:30 -04:00
"github.com/minio/minio/pkg/dns"
2018-03-15 16:03:41 -04:00
"github.com/minio/minio/pkg/event"
2018-10-05 14:20:00 -04:00
"github.com/minio/minio/pkg/handlers"
2017-10-22 01:30:34 -04:00
"github.com/minio/minio/pkg/hash"
2019-02-27 20:46:55 -05:00
iampolicy "github.com/minio/minio/pkg/iam/policy"
2018-08-17 15:52:14 -04:00
"github.com/minio/minio/pkg/ioutil"
2018-04-24 18:53:30 -04:00
"github.com/minio/minio/pkg/policy"
2016-01-23 22:44:32 -05:00
)
2016-04-08 02:44:08 -04:00
// WebGenericArgs - empty struct for calls that don't accept arguments
2016-03-21 14:15:08 -04:00
// for ex. ServerInfo, GenerateAuth
2016-04-08 02:44:08 -04:00
type WebGenericArgs struct { }
2016-03-21 14:15:08 -04:00
2016-04-08 02:44:08 -04:00
// WebGenericRep - reply structure for calls for which reply is success/failure
2016-02-19 03:00:32 -05:00
// for ex. RemoveObject MakeBucket
2016-04-08 02:44:08 -04:00
type WebGenericRep struct {
2016-02-19 03:00:32 -05:00
UIVersion string ` json:"uiVersion" `
}
// ServerInfoRep - server info reply.
type ServerInfoRep struct {
2017-05-25 00:09:23 -04:00
MinioVersion string
MinioMemory string
MinioPlatform string
MinioRuntime string
MinioGlobalInfo map [ string ] interface { }
UIVersion string ` json:"uiVersion" `
2016-02-19 03:00:32 -05:00
}
2016-02-04 01:46:45 -05:00
// ServerInfo - get server info.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) ServerInfo ( r * http . Request , args * WebGenericArgs , reply * ServerInfoRep ) error {
2018-10-17 19:23:09 -04:00
_ , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
2016-02-04 01:46:45 -05:00
}
host , err := os . Hostname ( )
if err != nil {
host = ""
}
memstats := & runtime . MemStats { }
runtime . ReadMemStats ( memstats )
mem := fmt . Sprintf ( "Used: %s | Allocated: %s | Used-Heap: %s | Allocated-Heap: %s" ,
humanize . Bytes ( memstats . Alloc ) ,
humanize . Bytes ( memstats . TotalAlloc ) ,
humanize . Bytes ( memstats . HeapAlloc ) ,
humanize . Bytes ( memstats . HeapSys ) )
platform := fmt . Sprintf ( "Host: %s | OS: %s | Arch: %s" ,
host ,
runtime . GOOS ,
runtime . GOARCH )
goruntime := fmt . Sprintf ( "Version: %s | CPUs: %s" , runtime . Version ( ) , strconv . Itoa ( runtime . NumCPU ( ) ) )
2016-08-03 16:47:03 -04:00
2016-08-18 19:23:42 -04:00
reply . MinioVersion = Version
2017-05-25 00:09:23 -04:00
reply . MinioGlobalInfo = getGlobalInfo ( )
2018-10-17 19:23:09 -04:00
// If ENV creds are not set and incoming user is not owner
// disable changing credentials.
v , ok := reply . MinioGlobalInfo [ "isEnvCreds" ] . ( bool )
if ok && ! v {
reply . MinioGlobalInfo [ "isEnvCreds" ] = ! owner
}
2018-12-19 08:13:47 -05:00
// if etcd is set disallow changing credentials through UI
if globalEtcdClient != nil {
reply . MinioGlobalInfo [ "isEnvCreds" ] = true
}
2018-10-17 19:23:09 -04:00
2016-02-08 15:40:22 -05:00
reply . MinioMemory = mem
reply . MinioPlatform = platform
reply . MinioRuntime = goruntime
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-02-04 01:46:45 -05:00
return nil
}
2016-05-26 17:13:10 -04:00
// StorageInfoRep - contains storage usage statistics.
type StorageInfoRep struct {
StorageInfo StorageInfo ` json:"storageInfo" `
UIVersion string ` json:"uiVersion" `
}
// StorageInfo - web call to gather storage usage statistics.
2019-04-18 02:16:27 -04:00
func ( web * webAPIHandlers ) StorageInfo ( r * http . Request , args * WebGenericArgs , reply * StorageInfoRep ) error {
2016-07-31 17:11:14 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2018-10-17 19:23:09 -04:00
_ , _ , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
2016-07-31 17:11:14 -04:00
}
2018-03-15 16:27:16 -04:00
reply . StorageInfo = objectAPI . StorageInfo ( context . Background ( ) )
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-05-26 17:13:10 -04:00
return nil
}
2016-02-19 03:00:32 -05:00
// MakeBucketArgs - make bucket args.
type MakeBucketArgs struct {
BucketName string ` json:"bucketName" `
}
2017-03-03 06:01:42 -05:00
// MakeBucket - creates a new bucket.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) MakeBucket ( r * http . Request , args * MakeBucketArgs , reply * WebGenericRep ) error {
2016-07-31 17:11:14 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2019-04-09 11:17:41 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
2018-10-17 19:23:09 -04:00
if authErr != nil {
return toJSONError ( authErr )
}
2018-12-19 08:13:47 -05:00
2019-04-09 11:17:41 -04:00
// For authenticated users apply IAM policy.
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
Action : iampolicy . CreateBucketAction ,
BucketName : args . BucketName ,
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
IsOwner : owner ,
} ) {
2018-10-17 19:23:09 -04:00
return toJSONError ( errAccessDenied )
2016-07-31 17:11:14 -04:00
}
2017-03-03 06:01:42 -05:00
2017-09-01 15:16:54 -04:00
// Check if bucket is a reserved bucket name or invalid.
2019-03-05 13:42:32 -05:00
if isReservedOrInvalidBucket ( args . BucketName , true ) {
2017-09-01 15:16:54 -04:00
return toJSONError ( errInvalidBucketName )
2017-03-03 06:01:42 -05:00
}
2018-05-01 13:36:37 -04:00
if globalDNSConfig != nil {
if _ , err := globalDNSConfig . Get ( args . BucketName ) ; err != nil {
2018-07-12 17:12:40 -04:00
if err == dns . ErrNoEntriesFound {
2018-05-01 13:36:37 -04:00
// Proceed to creating a bucket.
if err = objectAPI . MakeBucketWithLocation ( context . Background ( ) , args . BucketName , globalServerConfig . GetRegion ( ) ) ; err != nil {
return toJSONError ( err )
}
if err = globalDNSConfig . Put ( args . BucketName ) ; err != nil {
objectAPI . DeleteBucket ( context . Background ( ) , args . BucketName )
return toJSONError ( err )
}
reply . UIVersion = browser . UIVersion
return nil
}
return toJSONError ( err )
}
return toJSONError ( errBucketAlreadyExists )
}
2018-03-15 16:27:16 -04:00
if err := objectAPI . MakeBucketWithLocation ( context . Background ( ) , args . BucketName , globalServerConfig . GetRegion ( ) ) ; err != nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( err , args . BucketName )
2016-02-12 21:55:17 -05:00
}
2017-03-03 06:01:42 -05:00
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-02-12 21:55:17 -05:00
return nil
2016-01-25 01:26:53 -05:00
}
2017-12-29 08:15:44 -05:00
// RemoveBucketArgs - remove bucket args.
type RemoveBucketArgs struct {
BucketName string ` json:"bucketName" `
}
// DeleteBucket - removes a bucket, must be empty.
func ( web * webAPIHandlers ) DeleteBucket ( r * http . Request , args * RemoveBucketArgs , reply * WebGenericRep ) error {
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
return toJSONError ( errServerNotInitialized )
}
2019-04-09 11:17:41 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
2018-10-17 19:23:09 -04:00
if authErr != nil {
return toJSONError ( authErr )
}
2018-12-19 08:13:47 -05:00
2019-04-09 11:17:41 -04:00
// For authenticated users apply IAM policy.
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
Action : iampolicy . DeleteBucketAction ,
BucketName : args . BucketName ,
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
IsOwner : owner ,
} ) {
2018-10-17 19:23:09 -04:00
return toJSONError ( errAccessDenied )
2017-12-29 08:15:44 -05:00
}
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-12-19 08:13:47 -05:00
reply . UIVersion = browser . UIVersion
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
return toJSONError ( err , args . BucketName )
}
core , err := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if err != nil {
return toJSONError ( err , args . BucketName )
}
if err = core . RemoveBucket ( args . BucketName ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
return nil
}
2018-04-24 18:53:30 -04:00
ctx := context . Background ( )
2018-03-28 17:14:06 -04:00
deleteBucket := objectAPI . DeleteBucket
if web . CacheAPI ( ) != nil {
deleteBucket = web . CacheAPI ( ) . DeleteBucket
}
2018-04-24 18:53:30 -04:00
if err := deleteBucket ( ctx , args . BucketName ) ; err != nil {
2017-12-29 08:15:44 -05:00
return toJSONError ( err , args . BucketName )
}
2018-04-24 18:53:30 -04:00
globalNotificationSys . RemoveNotification ( args . BucketName )
globalPolicySys . Remove ( args . BucketName )
2018-07-03 14:09:36 -04:00
globalNotificationSys . DeleteBucket ( ctx , args . BucketName )
2018-04-24 18:53:30 -04:00
2018-05-01 13:36:37 -04:00
if globalDNSConfig != nil {
if err := globalDNSConfig . Delete ( args . BucketName ) ; err != nil {
// Deleting DNS entry failed, attempt to create the bucket again.
objectAPI . MakeBucketWithLocation ( ctx , args . BucketName , "" )
return toJSONError ( err )
}
}
2017-12-29 08:15:44 -05:00
return nil
}
2016-02-19 03:00:32 -05:00
// ListBucketsRep - list buckets response
type ListBucketsRep struct {
objectAPI: Fix object API interface, remove unnecessary structs.
ObjectAPI changes.
```
ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsInfo, *probe.Error)
ListMultipartUploads(bucket, objectPrefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (ListMultipartsInfo, *probe.Error)
ListObjectParts(bucket, object, uploadID string, partNumberMarker, maxParts int) (ListPartsInfo, *probe.Error)
CompleteMultipartUpload(bucket string, object string, uploadID string, parts []completePart) (ObjectInfo, *probe.Error)
```
2016-04-03 04:34:20 -04:00
Buckets [ ] WebBucketInfo ` json:"buckets" `
UIVersion string ` json:"uiVersion" `
2016-02-19 03:00:32 -05:00
}
objectAPI: Fix object API interface, remove unnecessary structs.
ObjectAPI changes.
```
ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsInfo, *probe.Error)
ListMultipartUploads(bucket, objectPrefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (ListMultipartsInfo, *probe.Error)
ListObjectParts(bucket, object, uploadID string, partNumberMarker, maxParts int) (ListPartsInfo, *probe.Error)
CompleteMultipartUpload(bucket string, object string, uploadID string, parts []completePart) (ObjectInfo, *probe.Error)
```
2016-04-03 04:34:20 -04:00
// WebBucketInfo container for list buckets metadata.
type WebBucketInfo struct {
2016-02-19 03:00:32 -05:00
// The name of the bucket.
Name string ` json:"name" `
// Date the bucket was created.
CreationDate time . Time ` json:"creationDate" `
}
2016-01-23 22:44:32 -05:00
// ListBuckets - list buckets api.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) ListBuckets ( r * http . Request , args * WebGenericArgs , reply * ListBucketsRep ) error {
2016-07-31 17:11:14 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2018-03-28 17:14:06 -04:00
listBuckets := objectAPI . ListBuckets
if web . CacheAPI ( ) != nil {
listBuckets = web . CacheAPI ( ) . ListBuckets
}
2018-10-09 17:00:01 -04:00
2018-12-10 12:27:22 -05:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
2017-01-11 16:26:42 -05:00
return toJSONError ( authErr )
2016-07-31 17:11:14 -04:00
}
2018-10-09 17:00:01 -04:00
2019-01-20 02:20:01 -05:00
// Set prefix value for "s3:prefix" policy conditionals.
r . Header . Set ( "prefix" , "" )
// Set delimiter value for "s3:delimiter" policy conditionals.
r . Header . Set ( "delimiter" , slashSeparator )
2018-05-01 13:36:37 -04:00
// If etcd, dns federation configured list buckets from etcd.
if globalDNSConfig != nil {
dnsBuckets , err := globalDNSConfig . List ( )
2019-03-12 20:57:08 -04:00
if err != nil && err != dns . ErrNoEntriesFound {
2018-05-01 13:36:37 -04:00
return toJSONError ( err )
}
2019-03-12 20:57:08 -04:00
bucketSet := set . NewStringSet ( )
2018-05-01 13:36:37 -04:00
for _ , dnsRecord := range dnsBuckets {
2019-03-12 20:57:08 -04:00
if bucketSet . Contains ( dnsRecord . Key ) {
continue
}
2018-12-13 23:15:09 -05:00
2018-12-10 12:27:22 -05:00
if globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . ListBucketAction ,
2019-03-12 20:57:08 -04:00
BucketName : dnsRecord . Key ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-12-10 12:27:22 -05:00
IsOwner : owner ,
ObjectName : "" ,
} ) {
reply . Buckets = append ( reply . Buckets , WebBucketInfo {
2019-03-12 20:57:08 -04:00
Name : dnsRecord . Key ,
2018-12-10 12:27:22 -05:00
CreationDate : dnsRecord . CreationDate ,
} )
2019-03-12 20:57:08 -04:00
bucketSet . Add ( dnsRecord . Key )
2018-12-10 12:27:22 -05:00
}
2018-05-01 13:36:37 -04:00
}
} else {
buckets , err := listBuckets ( context . Background ( ) )
if err != nil {
return toJSONError ( err )
}
for _ , bucket := range buckets {
2018-12-10 12:27:22 -05:00
if globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . ListBucketAction ,
2018-12-10 12:27:22 -05:00
BucketName : bucket . Name ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-12-10 12:27:22 -05:00
IsOwner : owner ,
ObjectName : "" ,
} ) {
reply . Buckets = append ( reply . Buckets , WebBucketInfo {
Name : bucket . Name ,
CreationDate : bucket . Created ,
} )
}
2018-05-01 13:36:37 -04:00
}
2016-01-23 22:44:32 -05:00
}
2018-05-01 13:36:37 -04:00
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-01-23 22:44:32 -05:00
return nil
}
2016-02-19 03:00:32 -05:00
// ListObjectsArgs - list object args.
type ListObjectsArgs struct {
BucketName string ` json:"bucketName" `
Prefix string ` json:"prefix" `
2017-02-11 01:54:42 -05:00
Marker string ` json:"marker" `
2016-02-19 03:00:32 -05:00
}
// ListObjectsRep - list objects response.
type ListObjectsRep struct {
2017-02-11 01:54:42 -05:00
Objects [ ] WebObjectInfo ` json:"objects" `
NextMarker string ` json:"nextmarker" `
IsTruncated bool ` json:"istruncated" `
Writable bool ` json:"writable" ` // Used by client to show "upload file" button.
UIVersion string ` json:"uiVersion" `
2016-02-19 03:00:32 -05:00
}
objectAPI: Fix object API interface, remove unnecessary structs.
ObjectAPI changes.
```
ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsInfo, *probe.Error)
ListMultipartUploads(bucket, objectPrefix, keyMarker, uploadIDMarker, delimiter string, maxUploads int) (ListMultipartsInfo, *probe.Error)
ListObjectParts(bucket, object, uploadID string, partNumberMarker, maxParts int) (ListPartsInfo, *probe.Error)
CompleteMultipartUpload(bucket string, object string, uploadID string, parts []completePart) (ObjectInfo, *probe.Error)
```
2016-04-03 04:34:20 -04:00
// WebObjectInfo container for list objects metadata.
type WebObjectInfo struct {
2016-02-19 03:00:32 -05:00
// Name of the object
Key string ` json:"name" `
// Date and time the object was last modified.
LastModified time . Time ` json:"lastModified" `
// Size in bytes of the object.
Size int64 ` json:"size" `
// ContentType is mime type of the object.
ContentType string ` json:"contentType" `
}
2016-01-23 22:44:32 -05:00
// ListObjects - list objects api.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) ListObjects ( r * http . Request , args * ListObjectsArgs , reply * ListObjectsRep ) error {
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-11-02 17:45:11 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2018-10-09 17:00:01 -04:00
2018-03-28 17:14:06 -04:00
listObjects := objectAPI . ListObjects
if web . CacheAPI ( ) != nil {
listObjects = web . CacheAPI ( ) . ListObjects
}
2018-04-24 18:53:30 -04:00
2018-12-19 08:13:47 -05:00
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
return toJSONError ( err , args . BucketName )
}
core , err := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if err != nil {
return toJSONError ( err , args . BucketName )
}
result , err := core . ListObjects ( args . BucketName , args . Prefix , args . Marker , slashSeparator , 1000 )
if err != nil {
return toJSONError ( err , args . BucketName )
}
reply . NextMarker = result . NextMarker
reply . IsTruncated = result . IsTruncated
for _ , obj := range result . Contents {
reply . Objects = append ( reply . Objects , WebObjectInfo {
Key : obj . Key ,
LastModified : obj . LastModified ,
Size : obj . Size ,
ContentType : obj . ContentType ,
} )
}
for _ , p := range result . CommonPrefixes {
reply . Objects = append ( reply . Objects , WebObjectInfo {
Key : p . Prefix ,
} )
}
return nil
}
2018-10-09 17:00:01 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
if authErr == errNoAuthToken {
2019-01-20 02:20:01 -05:00
// Set prefix value for "s3:prefix" policy conditionals.
r . Header . Set ( "prefix" , args . Prefix )
// Set delimiter value for "s3:delimiter" policy conditionals.
r . Header . Set ( "delimiter" , slashSeparator )
2018-12-13 23:15:09 -05:00
2018-10-09 17:00:01 -04:00
// Check if anonymous (non-owner) has access to download objects.
readable := globalPolicySys . IsAllowed ( policy . Args {
2018-12-13 23:15:09 -05:00
Action : policy . ListBucketAction ,
2018-10-09 17:00:01 -04:00
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , "" ) ,
2018-10-09 17:00:01 -04:00
IsOwner : false ,
} )
// Check if anonymous (non-owner) has access to upload objects.
writable := globalPolicySys . IsAllowed ( policy . Args {
Action : policy . PutObjectAction ,
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , "" ) ,
2018-10-09 17:00:01 -04:00
IsOwner : false ,
ObjectName : args . Prefix + "/" ,
} )
2018-04-24 18:53:30 -04:00
2018-10-09 17:00:01 -04:00
reply . Writable = writable
if ! readable {
// Error out if anonymous user (non-owner) has no access to download or upload objects
if ! writable {
2018-10-17 19:23:09 -04:00
return errAccessDenied
2018-10-09 17:00:01 -04:00
}
// return empty object list if access is write only
return nil
}
} else {
2018-04-24 18:53:30 -04:00
return toJSONError ( authErr )
}
2018-10-09 17:00:01 -04:00
}
// For authenticated users apply IAM policy.
if authErr == nil {
2019-01-20 02:20:01 -05:00
// Set prefix value for "s3:prefix" policy conditionals.
r . Header . Set ( "prefix" , args . Prefix )
// Set delimiter value for "s3:delimiter" policy conditionals.
r . Header . Set ( "delimiter" , slashSeparator )
2018-12-13 23:15:09 -05:00
2018-10-09 17:00:01 -04:00
readable := globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . ListBucketAction ,
2018-10-09 17:00:01 -04:00
BucketName : args . BucketName ,
2019-01-30 03:51:09 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-09 17:00:01 -04:00
IsOwner : owner ,
} )
writable := globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . PutObjectAction ,
2018-10-09 17:00:01 -04:00
BucketName : args . BucketName ,
2019-01-30 03:51:09 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-09 17:00:01 -04:00
IsOwner : owner ,
ObjectName : args . Prefix + "/" ,
} )
2018-04-24 18:53:30 -04:00
2018-08-31 16:20:27 -04:00
reply . Writable = writable
if ! readable {
// Error out if anonymous user (non-owner) has no access to download or upload objects
if ! writable {
2018-10-17 19:23:09 -04:00
return errAccessDenied
2018-08-31 16:20:27 -04:00
}
// return empty object list if access is write only
return nil
2018-04-24 18:53:30 -04:00
}
2016-01-23 22:44:32 -05:00
}
2018-04-24 18:53:30 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-03-28 17:14:06 -04:00
lo , err := listObjects ( context . Background ( ) , args . BucketName , args . Prefix , args . Marker , slashSeparator , 1000 )
2017-02-11 01:54:42 -05:00
if err != nil {
return & json2 . Error { Message : err . Error ( ) }
2016-01-23 22:44:32 -05:00
}
2018-08-17 15:52:14 -04:00
for i := range lo . Objects {
if crypto . IsEncrypted ( lo . Objects [ i ] . UserDefined ) {
lo . Objects [ i ] . Size , err = lo . Objects [ i ] . DecryptedSize ( )
if err != nil {
return toJSONError ( err )
}
}
}
2017-02-11 01:54:42 -05:00
reply . NextMarker = lo . NextMarker
reply . IsTruncated = lo . IsTruncated
for _ , obj := range lo . Objects {
reply . Objects = append ( reply . Objects , WebObjectInfo {
Key : obj . Name ,
LastModified : obj . ModTime ,
Size : obj . Size ,
ContentType : obj . ContentType ,
} )
}
for _ , prefix := range lo . Prefixes {
reply . Objects = append ( reply . Objects , WebObjectInfo {
Key : prefix ,
} )
}
2016-01-23 22:44:32 -05:00
return nil
}
2017-04-27 02:27:48 -04:00
// RemoveObjectArgs - args to remove an object, JSON will look like.
//
// {
// "bucketname": "testbucket",
// "objects": [
// "photos/hawaii/",
// "photos/maldives/",
// "photos/sanjose.jpg"
// ]
// }
2016-02-19 03:00:32 -05:00
type RemoveObjectArgs struct {
2017-04-27 02:27:48 -04:00
Objects [ ] string ` json:"objects" ` // Contains objects, prefixes.
BucketName string ` json:"bucketname" ` // Contains bucket name.
2016-02-19 03:00:32 -05:00
}
2017-04-27 02:27:48 -04:00
// RemoveObject - removes an object, or all the objects at a given prefix.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) RemoveObject ( r * http . Request , args * RemoveObjectArgs , reply * WebGenericRep ) error {
2016-07-31 17:11:14 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2018-03-28 17:14:06 -04:00
listObjects := objectAPI . ListObjects
if web . CacheAPI ( ) != nil {
listObjects = web . CacheAPI ( ) . ListObjects
}
2018-10-17 19:23:09 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
2016-07-31 17:11:14 -04:00
}
2017-04-27 02:27:48 -04:00
2017-02-28 22:07:28 -05:00
if args . BucketName == "" || len ( args . Objects ) == 0 {
2017-04-27 02:27:48 -04:00
return toJSONError ( errInvalidArgument )
2017-02-28 22:07:28 -05:00
}
2017-04-27 02:27:48 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-12-19 08:13:47 -05:00
reply . UIVersion = browser . UIVersion
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
return toJSONError ( err , args . BucketName )
}
core , err := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if err != nil {
return toJSONError ( err , args . BucketName )
}
objectsCh := make ( chan string )
// Send object names that are needed to be removed to objectsCh
go func ( ) {
defer close ( objectsCh )
for _ , objectName := range args . Objects {
objectsCh <- objectName
}
} ( )
for resp := range core . RemoveObjects ( args . BucketName , objectsCh ) {
if resp . Err != nil {
return toJSONError ( resp . Err , args . BucketName , resp . ObjectName )
}
}
return nil
}
2017-02-28 22:07:28 -05:00
var err error
2017-04-27 02:27:48 -04:00
next :
for _ , objectName := range args . Objects {
// If not a directory, remove the object.
if ! hasSuffix ( objectName , slashSeparator ) && objectName != "" {
2018-06-06 21:10:51 -04:00
// Deny if WORM is enabled
if globalWORMEnabled {
2018-09-10 12:42:43 -04:00
if _ , err = objectAPI . GetObjectInfo ( context . Background ( ) , args . BucketName , objectName , ObjectOptions { } ) ; err == nil {
2018-06-06 21:10:51 -04:00
return toJSONError ( errMethodNotAllowed )
}
}
2018-10-17 19:23:09 -04:00
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . DeleteObjectAction ,
2018-10-17 19:23:09 -04:00
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-17 19:23:09 -04:00
IsOwner : owner ,
ObjectName : objectName ,
} ) {
return toJSONError ( errAccessDenied )
}
2018-12-19 08:13:47 -05:00
if err = deleteObject ( context . Background ( ) , objectAPI , web . CacheAPI ( ) , args . BucketName , objectName , r ) ; err != nil {
2017-04-27 02:27:48 -04:00
break next
2017-02-28 22:07:28 -05:00
}
continue
}
2017-04-27 02:27:48 -04:00
2018-10-17 19:23:09 -04:00
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . DeleteObjectAction ,
2018-10-17 19:23:09 -04:00
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-17 19:23:09 -04:00
IsOwner : owner ,
ObjectName : objectName ,
} ) {
return toJSONError ( errAccessDenied )
}
2017-02-28 22:07:28 -05:00
// For directories, list the contents recursively and remove.
marker := ""
for {
var lo ListObjectsInfo
2018-03-28 17:14:06 -04:00
lo , err = listObjects ( context . Background ( ) , args . BucketName , objectName , marker , "" , 1000 )
2017-02-28 22:07:28 -05:00
if err != nil {
2017-04-27 02:27:48 -04:00
break next
2017-02-28 22:07:28 -05:00
}
marker = lo . NextMarker
for _ , obj := range lo . Objects {
2018-12-19 08:13:47 -05:00
err = deleteObject ( context . Background ( ) , objectAPI , web . CacheAPI ( ) , args . BucketName , obj . Name , r )
2017-02-28 22:07:28 -05:00
if err != nil {
2017-04-27 02:27:48 -04:00
break next
2017-02-28 22:07:28 -05:00
}
}
if ! lo . IsTruncated {
break
}
2016-11-10 18:02:03 -05:00
}
2016-02-12 21:55:17 -05:00
}
2016-11-10 10:42:55 -05:00
2017-02-28 22:07:28 -05:00
if err != nil && ! isErrObjectNotFound ( err ) {
// Ignore object not found error.
return toJSONError ( err , args . BucketName , "" )
}
2016-11-10 10:42:55 -05:00
2016-02-12 21:55:17 -05:00
return nil
2016-02-05 09:16:36 -05:00
}
2016-02-19 03:00:32 -05:00
// LoginArgs - login arguments.
type LoginArgs struct {
Username string ` json:"username" form:"username" `
Password string ` json:"password" form:"password" `
}
// LoginRep - login reply.
type LoginRep struct {
Token string ` json:"token" `
UIVersion string ` json:"uiVersion" `
}
2016-01-23 22:44:32 -05:00
// Login - user login handler.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) Login ( r * http . Request , args * LoginArgs , reply * LoginRep ) error {
2016-12-27 11:28:10 -05:00
token , err := authenticateWeb ( args . Username , args . Password )
2016-07-12 00:57:40 -04:00
if err != nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( err )
2016-07-12 00:57:40 -04:00
}
reply . Token = token
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-07-12 00:57:40 -04:00
return nil
2016-01-23 22:44:32 -05:00
}
2016-03-21 14:15:08 -04:00
// GenerateAuthReply - reply for GenerateAuth
type GenerateAuthReply struct {
AccessKey string ` json:"accessKey" `
SecretKey string ` json:"secretKey" `
UIVersion string ` json:"uiVersion" `
}
2016-04-12 15:45:15 -04:00
func ( web webAPIHandlers ) GenerateAuth ( r * http . Request , args * WebGenericArgs , reply * GenerateAuthReply ) error {
2018-10-17 19:23:09 -04:00
_ , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
}
if ! owner {
return toJSONError ( errAccessDenied )
2016-03-21 14:15:08 -04:00
}
2018-04-19 20:24:43 -04:00
cred , err := auth . GetNewCredentials ( )
2018-06-14 13:17:07 -04:00
if err != nil {
return toJSONError ( err )
}
2016-12-26 13:21:23 -05:00
reply . AccessKey = cred . AccessKey
reply . SecretKey = cred . SecretKey
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-03-21 14:15:08 -04:00
return nil
}
// SetAuthArgs - argument for SetAuth
type SetAuthArgs struct {
AccessKey string ` json:"accessKey" `
SecretKey string ` json:"secretKey" `
}
// SetAuthReply - reply for SetAuth
type SetAuthReply struct {
2016-10-17 23:18:08 -04:00
Token string ` json:"token" `
UIVersion string ` json:"uiVersion" `
PeerErrMsgs map [ string ] string ` json:"peerErrMsgs" `
2016-03-21 14:15:08 -04:00
}
// SetAuth - Set accessKey and secretKey credentials.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) SetAuth ( r * http . Request , args * SetAuthArgs , reply * SetAuthReply ) error {
2018-10-17 19:23:09 -04:00
_ , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
2016-03-21 14:15:08 -04:00
}
2016-11-22 14:12:38 -05:00
2017-02-07 15:51:43 -05:00
// If creds are set through ENV disallow changing credentials.
2018-12-19 08:13:47 -05:00
if globalIsEnvCreds || globalWORMEnabled || ! owner || globalEtcdClient != nil {
2017-02-07 15:51:43 -05:00
return toJSONError ( errChangeCredNotAllowed )
}
2017-10-31 14:54:32 -04:00
creds , err := auth . CreateCredentials ( args . AccessKey , args . SecretKey )
2017-03-16 03:16:06 -04:00
if err != nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( err )
2016-03-21 14:15:08 -04:00
}
2016-11-22 14:12:38 -05:00
2018-01-31 11:15:54 -05:00
// Acquire lock before updating global configuration.
globalServerConfigMu . Lock ( )
defer globalServerConfigMu . Unlock ( )
2018-06-06 04:51:56 -04:00
// Update credentials in memory
2017-11-29 16:12:47 -05:00
prevCred := globalServerConfig . SetCredential ( creds )
2017-01-26 19:51:51 -05:00
2018-02-02 21:18:52 -05:00
// Persist updated credentials.
2018-09-06 11:03:18 -04:00
if err = saveServerConfig ( context . Background ( ) , newObjectLayerFn ( ) , globalServerConfig ) ; err != nil {
2018-02-02 21:18:52 -05:00
// Save the current creds when failed to update.
2017-11-29 16:12:47 -05:00
globalServerConfig . SetCredential ( prevCred )
2018-06-06 04:51:56 -04:00
logger . LogIf ( context . Background ( ) , err )
return toJSONError ( err )
2016-10-17 23:18:08 -04:00
}
2019-03-20 21:09:57 -04:00
reply . Token , err = authenticateWeb ( creds . AccessKey , creds . SecretKey )
if err != nil {
return toJSONError ( err )
2016-03-21 14:15:08 -04:00
}
2019-03-20 21:09:57 -04:00
reply . UIVersion = browser . UIVersion
2016-10-17 23:18:08 -04:00
2016-03-21 14:15:08 -04:00
return nil
}
2016-03-31 09:57:29 -04:00
// GetAuthReply - Reply current credentials.
type GetAuthReply struct {
AccessKey string ` json:"accessKey" `
SecretKey string ` json:"secretKey" `
UIVersion string ` json:"uiVersion" `
}
// GetAuth - return accessKey and secretKey credentials.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) GetAuth ( r * http . Request , args * WebGenericArgs , reply * GetAuthReply ) error {
2018-10-17 19:23:09 -04:00
_ , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
}
if ! owner {
return toJSONError ( errAccessDenied )
2016-03-31 09:57:29 -04:00
}
2017-11-29 16:12:47 -05:00
creds := globalServerConfig . GetCredential ( )
2016-12-26 13:21:23 -05:00
reply . AccessKey = creds . AccessKey
reply . SecretKey = creds . SecretKey
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2016-03-31 09:57:29 -04:00
return nil
}
2017-07-24 15:46:37 -04:00
// URLTokenReply contains the reply for CreateURLToken.
type URLTokenReply struct {
Token string ` json:"token" `
UIVersion string ` json:"uiVersion" `
}
// CreateURLToken creates a URL token (short-lived) for GET requests.
func ( web * webAPIHandlers ) CreateURLToken ( r * http . Request , args * WebGenericArgs , reply * URLTokenReply ) error {
2018-10-17 19:23:09 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
2017-07-24 15:46:37 -04:00
}
2017-11-29 16:12:47 -05:00
creds := globalServerConfig . GetCredential ( )
2018-10-17 19:23:09 -04:00
if ! owner {
var ok bool
creds , ok = globalIAMSys . GetUser ( claims . Subject )
if ! ok {
return toJSONError ( errInvalidAccessKeyID )
}
}
2017-07-24 15:46:37 -04:00
token , err := authenticateURL ( creds . AccessKey , creds . SecretKey )
if err != nil {
return toJSONError ( err )
}
reply . Token = token
reply . UIVersion = browser . UIVersion
return nil
}
2016-03-31 09:57:29 -04:00
// Upload - file upload handler.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) Upload ( w http . ResponseWriter , r * http . Request ) {
2018-10-12 15:25:59 -04:00
ctx := newContext ( r , w , "WebUpload" )
2018-11-21 23:03:24 -05:00
defer logger . AuditLog ( w , r , "WebUpload" , mustGetClaimsFromToken ( r ) )
2018-10-12 15:25:59 -04:00
2016-11-02 17:45:11 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
writeWebErrorResponse ( w , errServerNotInitialized )
return
}
2016-03-31 09:57:29 -04:00
vars := mux . Vars ( r )
bucket := vars [ "bucket" ]
object := vars [ "object" ]
2016-07-28 00:11:15 -04:00
2018-10-09 17:00:01 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
if authErr == errNoAuthToken {
// Check if anonymous (non-owner) has access to upload objects.
if ! globalPolicySys . IsAllowed ( policy . Args {
Action : policy . PutObjectAction ,
BucketName : bucket ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , "" ) ,
2018-10-09 17:00:01 -04:00
IsOwner : false ,
ObjectName : object ,
} ) {
writeWebErrorResponse ( w , errAuthentication )
return
}
} else {
writeWebErrorResponse ( w , authErr )
2018-04-24 18:53:30 -04:00
return
}
2018-10-09 17:00:01 -04:00
}
2018-04-24 18:53:30 -04:00
2018-10-09 17:00:01 -04:00
// For authenticated users apply IAM policy.
if authErr == nil {
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . PutObjectAction ,
2018-04-24 18:53:30 -04:00
BucketName : bucket ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-09 17:00:01 -04:00
IsOwner : owner ,
2018-04-24 18:53:30 -04:00
ObjectName : object ,
} ) {
writeWebErrorResponse ( w , errAuthentication )
return
}
2017-01-11 16:26:42 -05:00
}
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( bucket , false ) {
writeWebErrorResponse ( w , errInvalidBucketName )
return
}
2018-12-14 16:35:48 -05:00
if globalAutoEncryption && ! crypto . SSEC . IsRequested ( r . Header ) {
r . Header . Add ( crypto . SSEHeader , crypto . SSEAlgorithmAES256 )
}
2017-01-11 16:26:42 -05:00
2017-02-02 13:45:00 -05:00
// Require Content-Length to be set in the request
size := r . ContentLength
if size < 0 {
writeWebErrorResponse ( w , errSizeUnspecified )
return
}
2016-07-28 00:11:15 -04:00
// Extract incoming metadata if any.
2018-07-10 23:27:10 -04:00
metadata , err := extractMetadata ( context . Background ( ) , r )
2017-07-05 19:56:10 -04:00
if err != nil {
2019-02-13 19:07:21 -05:00
writeErrorResponse ( ctx , w , toAPIError ( ctx , err ) , r . URL , guessIsBrowserReq ( r ) )
2017-07-05 19:56:10 -04:00
return
}
2016-07-28 00:11:15 -04:00
2018-12-14 16:35:48 -05:00
var pReader * PutObjReader
var reader io . Reader = r . Body
2018-09-27 23:36:17 -04:00
actualSize := size
2018-12-14 16:35:48 -05:00
hashReader , err := hash . NewReader ( reader , size , "" , "" , actualSize )
if err != nil {
writeWebErrorResponse ( w , err )
return
}
2018-09-27 23:36:17 -04:00
if objectAPI . IsCompressionSupported ( ) && isCompressible ( r . Header , object ) && size > 0 {
// Storing the compression metadata.
metadata [ ReservedMetadataPrefix + "compression" ] = compressionAlgorithmV1
metadata [ ReservedMetadataPrefix + "actual-size" ] = strconv . FormatInt ( size , 10 )
2019-03-05 11:35:37 -05:00
actualReader , err := hash . NewReader ( reader , size , "" , "" , actualSize )
2018-09-27 23:36:17 -04:00
if err != nil {
writeWebErrorResponse ( w , err )
return
}
2018-09-28 03:44:59 -04:00
2018-09-27 23:36:17 -04:00
// Set compression metrics.
size = - 1 // Since compressed size is un-predictable.
2019-03-05 11:35:37 -05:00
reader = newSnappyCompressReader ( actualReader )
2018-12-14 16:35:48 -05:00
hashReader , err = hash . NewReader ( reader , size , "" , "" , actualSize )
if err != nil {
writeWebErrorResponse ( w , err )
return
}
2018-09-27 23:36:17 -04:00
}
2018-12-14 16:35:48 -05:00
pReader = NewPutObjReader ( hashReader , nil , nil )
2019-01-05 17:16:43 -05:00
// get gateway encryption options
var opts ObjectOptions
2019-02-09 00:31:06 -05:00
opts , err = putOpts ( ctx , r , bucket , object , metadata )
2019-01-05 17:16:43 -05:00
if err != nil {
2019-02-12 04:25:52 -05:00
writeErrorResponseHeadersOnly ( w , toAPIError ( ctx , err ) )
2019-01-05 17:16:43 -05:00
return
}
2018-12-14 16:35:48 -05:00
if objectAPI . IsEncryptionSupported ( ) {
if hasServerSideEncryptionHeader ( r . Header ) && ! hasSuffix ( object , slashSeparator ) { // handle SSE requests
rawReader := hashReader
var objectEncryptionKey [ ] byte
reader , objectEncryptionKey , err = EncryptRequest ( hashReader , r , bucket , object , metadata )
if err != nil {
2019-02-13 19:07:21 -05:00
writeErrorResponse ( ctx , w , toAPIError ( ctx , err ) , r . URL , guessIsBrowserReq ( r ) )
2018-12-14 16:35:48 -05:00
return
}
info := ObjectInfo { Size : size }
hashReader , err = hash . NewReader ( reader , info . EncryptedSize ( ) , "" , "" , size ) // do not try to verify encrypted content
if err != nil {
2019-02-13 19:07:21 -05:00
writeErrorResponse ( ctx , w , toAPIError ( ctx , err ) , r . URL , guessIsBrowserReq ( r ) )
2018-12-14 16:35:48 -05:00
return
}
pReader = NewPutObjReader ( rawReader , hashReader , objectEncryptionKey )
}
2017-10-22 01:30:34 -04:00
}
2018-12-19 08:13:47 -05:00
2018-12-14 16:35:48 -05:00
// Ensure that metadata does not contain sensitive information
crypto . RemoveSensitiveEntries ( metadata )
2018-06-06 21:10:51 -04:00
// Deny if WORM is enabled
if globalWORMEnabled {
2018-10-12 15:25:59 -04:00
if _ , err = objectAPI . GetObjectInfo ( ctx , bucket , object , opts ) ; err == nil {
2018-06-06 21:10:51 -04:00
writeWebErrorResponse ( w , errMethodNotAllowed )
return
}
}
2018-12-14 16:35:48 -05:00
putObject := objectAPI . PutObject
if ! hasServerSideEncryptionHeader ( r . Header ) && web . CacheAPI ( ) != nil {
putObject = web . CacheAPI ( ) . PutObject
}
2019-02-09 00:31:06 -05:00
objInfo , err := putObject ( context . Background ( ) , bucket , object , pReader , opts )
2016-07-28 00:11:15 -04:00
if err != nil {
2016-12-10 19:15:12 -05:00
writeWebErrorResponse ( w , err )
2016-07-28 00:11:15 -04:00
return
}
2018-12-14 16:35:48 -05:00
if objectAPI . IsEncryptionSupported ( ) {
if crypto . IsEncrypted ( objInfo . UserDefined ) {
switch {
case crypto . S3 . IsEncrypted ( objInfo . UserDefined ) :
w . Header ( ) . Set ( crypto . SSEHeader , crypto . SSEAlgorithmAES256 )
case crypto . SSEC . IsRequested ( r . Header ) :
w . Header ( ) . Set ( crypto . SSECAlgorithm , r . Header . Get ( crypto . SSECAlgorithm ) )
w . Header ( ) . Set ( crypto . SSECKeyMD5 , r . Header . Get ( crypto . SSECKeyMD5 ) )
}
}
}
2016-07-28 00:11:15 -04:00
2016-09-29 01:46:19 -04:00
// Notify object created event.
2018-03-15 16:03:41 -04:00
sendEvent ( eventArgs {
2018-11-02 21:40:08 -04:00
EventName : event . ObjectCreatedPut ,
BucketName : bucket ,
Object : objInfo ,
ReqParams : extractReqParams ( r ) ,
RespElements : extractRespElements ( w ) ,
UserAgent : r . UserAgent ( ) ,
2019-03-25 14:45:42 -04:00
Host : handlers . GetSourceIP ( r ) ,
2016-09-29 01:46:19 -04:00
} )
2016-03-31 09:57:29 -04:00
}
// Download - file download handler.
2016-04-12 15:45:15 -04:00
func ( web * webAPIHandlers ) Download ( w http . ResponseWriter , r * http . Request ) {
2018-10-12 15:25:59 -04:00
ctx := newContext ( r , w , "WebDownload" )
2018-11-21 23:03:24 -05:00
defer logger . AuditLog ( w , r , "WebDownload" , mustGetClaimsFromToken ( r ) )
2018-10-12 15:25:59 -04:00
2016-11-02 17:45:11 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
writeWebErrorResponse ( w , errServerNotInitialized )
return
}
2016-03-31 09:57:29 -04:00
vars := mux . Vars ( r )
bucket := vars [ "bucket" ]
object := vars [ "object" ]
2016-12-27 11:28:10 -05:00
token := r . URL . Query ( ) . Get ( "token" )
2016-07-12 00:57:40 -04:00
2018-10-09 17:00:01 -04:00
claims , owner , authErr := webTokenAuthenticate ( token )
if authErr != nil {
if authErr == errNoAuthToken {
// Check if anonymous (non-owner) has access to download objects.
if ! globalPolicySys . IsAllowed ( policy . Args {
Action : policy . GetObjectAction ,
BucketName : bucket ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , "" ) ,
2018-10-09 17:00:01 -04:00
IsOwner : false ,
ObjectName : object ,
} ) {
writeWebErrorResponse ( w , errAuthentication )
return
}
} else {
writeWebErrorResponse ( w , authErr )
return
}
}
// For authenticated users apply IAM policy.
if authErr == nil {
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . GetObjectAction ,
2018-04-24 18:53:30 -04:00
BucketName : bucket ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-09 17:00:01 -04:00
IsOwner : owner ,
2018-04-24 18:53:30 -04:00
ObjectName : object ,
} ) {
writeWebErrorResponse ( w , errAuthentication )
return
}
2016-03-31 09:57:29 -04:00
}
2018-09-27 23:36:17 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( bucket , false ) {
writeWebErrorResponse ( w , errInvalidBucketName )
return
}
2018-12-13 23:15:09 -05:00
getObjectNInfo := objectAPI . GetObjectNInfo
2018-08-17 15:52:14 -04:00
if web . CacheAPI ( ) != nil {
2018-12-13 23:15:09 -05:00
getObjectNInfo = web . CacheAPI ( ) . GetObjectNInfo
2018-08-17 15:52:14 -04:00
}
2018-12-13 23:15:09 -05:00
var opts ObjectOptions
gr , err := getObjectNInfo ( ctx , bucket , object , nil , r . Header , readLock , opts )
2018-08-17 15:52:14 -04:00
if err != nil {
writeWebErrorResponse ( w , err )
return
}
2018-12-13 23:15:09 -05:00
defer gr . Close ( )
objInfo := gr . ObjInfo
2018-08-17 15:52:14 -04:00
if objectAPI . IsEncryptionSupported ( ) {
2018-11-14 20:36:41 -05:00
if _ , err = DecryptObjectInfo ( & objInfo , r . Header ) ; err != nil {
2018-08-24 10:56:24 -04:00
writeWebErrorResponse ( w , err )
2018-08-17 15:52:14 -04:00
return
}
2018-12-13 23:15:09 -05:00
}
// Set encryption response headers
if objectAPI . IsEncryptionSupported ( ) {
2018-09-20 22:22:09 -04:00
if crypto . IsEncrypted ( objInfo . UserDefined ) {
2018-12-13 23:15:09 -05:00
switch {
case crypto . S3 . IsEncrypted ( objInfo . UserDefined ) :
w . Header ( ) . Set ( crypto . SSEHeader , crypto . SSEAlgorithmAES256 )
case crypto . SSEC . IsEncrypted ( objInfo . UserDefined ) :
w . Header ( ) . Set ( crypto . SSECAlgorithm , r . Header . Get ( crypto . SSECAlgorithm ) )
w . Header ( ) . Set ( crypto . SSECKeyMD5 , r . Header . Get ( crypto . SSECKeyMD5 ) )
}
2018-09-20 22:22:09 -04:00
}
2018-08-17 15:52:14 -04:00
}
2018-09-28 03:44:59 -04:00
2018-12-13 23:15:09 -05:00
if err = setObjectHeaders ( w , objInfo , nil ) ; err != nil {
writeWebErrorResponse ( w , err )
return
2018-09-27 23:36:17 -04:00
}
2018-08-17 15:52:14 -04:00
2018-12-13 23:15:09 -05:00
// Add content disposition.
w . Header ( ) . Set ( "Content-Disposition" , fmt . Sprintf ( "attachment; filename=\"%s\"" , path . Base ( objInfo . Name ) ) )
2018-09-27 23:36:17 -04:00
2018-12-13 23:15:09 -05:00
setHeadGetRespHeaders ( w , r . URL . Query ( ) )
2018-08-17 15:52:14 -04:00
2018-12-13 23:15:09 -05:00
httpWriter := ioutil . WriteOnClose ( w )
2016-03-31 09:57:29 -04:00
2018-12-13 23:15:09 -05:00
// Write object content to response body
if _ , err = io . Copy ( httpWriter , gr ) ; err != nil {
if ! httpWriter . HasWritten ( ) { // write error response only if no data or headers has been written to client yet
writeWebErrorResponse ( w , err )
2018-09-27 23:36:17 -04:00
}
fs: Break fs package to top-level and introduce ObjectAPI interface.
ObjectAPI interface brings in changes needed for XL ObjectAPI layer.
The new interface for any ObjectAPI layer is as below
```
// ObjectAPI interface.
type ObjectAPI interface {
// Bucket resource API.
DeleteBucket(bucket string) *probe.Error
ListBuckets() ([]BucketInfo, *probe.Error)
MakeBucket(bucket string) *probe.Error
GetBucketInfo(bucket string) (BucketInfo, *probe.Error)
// Bucket query API.
ListObjects(bucket, prefix, marker, delimiter string, maxKeys int) (ListObjectsResult, *probe.Error)
ListMultipartUploads(bucket string, resources BucketMultipartResourcesMetadata) (BucketMultipartResourcesMetadata, *probe.Error)
// Object resource API.
GetObject(bucket, object string, startOffset int64) (io.ReadCloser, *probe.Error)
GetObjectInfo(bucket, object string) (ObjectInfo, *probe.Error)
PutObject(bucket string, object string, size int64, data io.Reader, metadata map[string]string) (ObjectInfo, *probe.Error)
DeleteObject(bucket, object string) *probe.Error
// Object query API.
NewMultipartUpload(bucket, object string) (string, *probe.Error)
PutObjectPart(bucket, object, uploadID string, partID int, size int64, data io.Reader, md5Hex string) (string, *probe.Error)
ListObjectParts(bucket, object string, resources ObjectResourcesMetadata) (ObjectResourcesMetadata, *probe.Error)
CompleteMultipartUpload(bucket string, object string, uploadID string, parts []CompletePart) (ObjectInfo, *probe.Error)
AbortMultipartUpload(bucket, object, uploadID string) *probe.Error
}
```
2016-03-30 19:15:28 -04:00
return
2016-03-31 09:57:29 -04:00
}
2018-12-13 23:15:09 -05:00
2018-08-17 15:52:14 -04:00
if err = httpWriter . Close ( ) ; err != nil {
2018-12-13 23:15:09 -05:00
if ! httpWriter . HasWritten ( ) { // write error response only if no data or headers has been written to client yet
2018-08-17 15:52:14 -04:00
writeWebErrorResponse ( w , err )
return
}
}
2018-10-05 14:20:00 -04:00
// Notify object accessed via a GET request.
sendEvent ( eventArgs {
EventName : event . ObjectAccessedGet ,
BucketName : bucket ,
Object : objInfo ,
ReqParams : extractReqParams ( r ) ,
RespElements : extractRespElements ( w ) ,
UserAgent : r . UserAgent ( ) ,
2019-03-25 14:45:42 -04:00
Host : handlers . GetSourceIP ( r ) ,
2018-10-05 14:20:00 -04:00
} )
2016-03-31 09:57:29 -04:00
}
2017-02-09 02:39:08 -05:00
// DownloadZipArgs - Argument for downloading a bunch of files as a zip file.
// JSON will look like:
// '{"bucketname":"testbucket","prefix":"john/pics/","objects":["hawaii/","maldives/","sanjose.jpg"]}'
type DownloadZipArgs struct {
Objects [ ] string ` json:"objects" ` // can be files or sub-directories
Prefix string ` json:"prefix" ` // current directory in the browser-ui
BucketName string ` json:"bucketname" ` // bucket name.
}
// Takes a list of objects and creates a zip file that sent as the response body.
func ( web * webAPIHandlers ) DownloadZip ( w http . ResponseWriter , r * http . Request ) {
2019-03-25 14:45:42 -04:00
host := handlers . GetSourceIP ( r )
2018-10-05 14:20:00 -04:00
2018-10-12 15:25:59 -04:00
ctx := newContext ( r , w , "WebDownloadZip" )
2018-11-21 23:03:24 -05:00
defer logger . AuditLog ( w , r , "WebDownloadZip" , mustGetClaimsFromToken ( r ) )
2018-10-12 15:25:59 -04:00
2018-09-27 23:36:17 -04:00
var wg sync . WaitGroup
2017-02-09 02:39:08 -05:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
writeWebErrorResponse ( w , errServerNotInitialized )
return
}
2018-10-09 17:00:01 -04:00
2017-05-10 12:54:24 -04:00
// Auth is done after reading the body to accommodate for anonymous requests
// when bucket policy is enabled.
2017-02-09 02:39:08 -05:00
var args DownloadZipArgs
2017-05-10 12:54:24 -04:00
tenKB := 10 * 1024 // To limit r.Body to take care of misbehaving anonymous client.
decodeErr := json . NewDecoder ( io . LimitReader ( r . Body , int64 ( tenKB ) ) ) . Decode ( & args )
2017-02-09 02:39:08 -05:00
if decodeErr != nil {
writeWebErrorResponse ( w , decodeErr )
return
}
2017-05-10 12:54:24 -04:00
token := r . URL . Query ( ) . Get ( "token" )
2018-10-09 17:00:01 -04:00
claims , owner , authErr := webTokenAuthenticate ( token )
if authErr != nil {
if authErr == errNoAuthToken {
for _ , object := range args . Objects {
// Check if anonymous (non-owner) has access to download objects.
if ! globalPolicySys . IsAllowed ( policy . Args {
Action : policy . GetObjectAction ,
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , "" ) ,
2018-10-09 17:00:01 -04:00
IsOwner : false ,
ObjectName : pathJoin ( args . Prefix , object ) ,
} ) {
writeWebErrorResponse ( w , errAuthentication )
return
}
}
} else {
writeWebErrorResponse ( w , authErr )
return
}
}
// For authenticated users apply IAM policy.
if authErr == nil {
2017-05-10 12:54:24 -04:00
for _ , object := range args . Objects {
2018-10-09 17:00:01 -04:00
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
2018-12-13 23:15:09 -05:00
Action : iampolicy . GetObjectAction ,
2018-04-24 18:53:30 -04:00
BucketName : args . BucketName ,
2019-01-20 23:57:14 -05:00
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
2018-10-09 17:00:01 -04:00
IsOwner : owner ,
2018-04-24 18:53:30 -04:00
ObjectName : pathJoin ( args . Prefix , object ) ,
} ) {
2017-05-10 12:54:24 -04:00
writeWebErrorResponse ( w , errAuthentication )
return
}
}
}
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
writeWebErrorResponse ( w , errInvalidBucketName )
return
}
2018-10-09 17:00:01 -04:00
getObject := objectAPI . GetObject
if web . CacheAPI ( ) != nil {
getObject = web . CacheAPI ( ) . GetObject
}
listObjects := objectAPI . ListObjects
if web . CacheAPI ( ) != nil {
listObjects = web . CacheAPI ( ) . ListObjects
}
2017-02-09 02:39:08 -05:00
archive := zip . NewWriter ( w )
defer archive . Close ( )
2018-10-09 17:00:01 -04:00
2018-03-28 17:14:06 -04:00
getObjectInfo := objectAPI . GetObjectInfo
if web . CacheAPI ( ) != nil {
getObjectInfo = web . CacheAPI ( ) . GetObjectInfo
}
2018-09-10 12:42:43 -04:00
opts := ObjectOptions { }
2018-09-27 23:36:17 -04:00
var length int64
2017-02-09 02:39:08 -05:00
for _ , object := range args . Objects {
// Writes compressed object file to the response.
zipit := func ( objectName string ) error {
2018-10-12 15:25:59 -04:00
info , err := getObjectInfo ( ctx , args . BucketName , objectName , opts )
2017-02-09 02:39:08 -05:00
if err != nil {
return err
}
2018-09-27 23:36:17 -04:00
length = info . Size
2018-08-17 15:52:14 -04:00
if objectAPI . IsEncryptionSupported ( ) {
2018-11-14 20:36:41 -05:00
if _ , err = DecryptObjectInfo ( & info , r . Header ) ; err != nil {
2018-08-24 10:56:24 -04:00
writeWebErrorResponse ( w , err )
2018-08-17 15:52:14 -04:00
return err
}
2018-09-20 22:22:09 -04:00
if crypto . IsEncrypted ( info . UserDefined ) {
length , _ = info . DecryptedSize ( )
}
2018-08-17 15:52:14 -04:00
}
2018-09-27 23:36:17 -04:00
length = info . Size
var actualSize int64
if info . IsCompressed ( ) {
// Read the decompressed size from the meta.json.
actualSize = info . GetActualSize ( )
// Set the info.Size to the actualSize.
info . Size = actualSize
}
2017-02-09 02:39:08 -05:00
header := & zip . FileHeader {
Name : strings . TrimPrefix ( objectName , args . Prefix ) ,
Method : zip . Deflate ,
2018-09-20 22:22:09 -04:00
UncompressedSize64 : uint64 ( length ) ,
UncompressedSize : uint32 ( length ) ,
2017-02-09 02:39:08 -05:00
}
2018-09-27 23:36:17 -04:00
zipWriter , err := archive . CreateHeader ( header )
2017-02-09 02:39:08 -05:00
if err != nil {
writeWebErrorResponse ( w , errUnexpected )
return err
}
2018-08-17 15:52:14 -04:00
var startOffset int64
var writer io . Writer
2018-09-27 23:36:17 -04:00
if info . IsCompressed ( ) {
// The decompress metrics are set.
snappyStartOffset := 0
snappyLength := actualSize
// Open a pipe for compression
// Where compressWriter is actually passed to the getObject
2018-09-28 03:44:59 -04:00
decompressReader , compressWriter := io . Pipe ( )
2018-09-27 23:36:17 -04:00
snappyReader := snappy . NewReader ( decompressReader )
// The limit is set to the actual size.
responseWriter := ioutil . LimitedWriter ( zipWriter , int64 ( snappyStartOffset ) , snappyLength )
wg . Add ( 1 ) //For closures.
go func ( ) {
defer wg . Done ( )
// Finally, writes to the client.
2018-09-28 03:44:59 -04:00
_ , perr := io . Copy ( responseWriter , snappyReader )
2018-09-27 23:36:17 -04:00
// Close the compressWriter if the data is read already.
// Closing the pipe, releases the writer passed to the getObject.
2018-09-28 03:44:59 -04:00
compressWriter . CloseWithError ( perr )
2018-09-27 23:36:17 -04:00
} ( )
writer = compressWriter
} else {
writer = zipWriter
}
2018-08-17 15:52:14 -04:00
if objectAPI . IsEncryptionSupported ( ) && crypto . S3 . IsEncrypted ( info . UserDefined ) {
// Response writer should be limited early on for decryption upto required length,
// additionally also skipping mod(offset)64KiB boundaries.
writer = ioutil . LimitedWriter ( writer , startOffset % ( 64 * 1024 ) , length )
2019-02-13 07:59:36 -05:00
writer , startOffset , length , err = DecryptBlocksRequest ( writer , r ,
args . BucketName , objectName , startOffset , length , info , false )
2018-08-17 15:52:14 -04:00
if err != nil {
writeWebErrorResponse ( w , err )
return err
}
}
httpWriter := ioutil . WriteOnClose ( writer )
2019-02-13 07:59:36 -05:00
if err = getObject ( ctx , args . BucketName , objectName , startOffset , length , httpWriter , "" , opts ) ; err != nil {
2018-09-27 23:36:17 -04:00
httpWriter . Close ( )
if info . IsCompressed ( ) {
// Wait for decompression go-routine to retire.
wg . Wait ( )
}
2018-08-17 15:52:14 -04:00
return err
}
if err = httpWriter . Close ( ) ; err != nil {
if ! httpWriter . HasWritten ( ) { // write error response only if no data has been written to client yet
writeWebErrorResponse ( w , err )
return err
}
}
2018-09-27 23:36:17 -04:00
if info . IsCompressed ( ) {
// Wait for decompression go-routine to retire.
wg . Wait ( )
}
2018-10-05 14:20:00 -04:00
// Notify object accessed via a GET request.
sendEvent ( eventArgs {
EventName : event . ObjectAccessedGet ,
BucketName : args . BucketName ,
Object : info ,
ReqParams : extractReqParams ( r ) ,
RespElements : extractRespElements ( w ) ,
UserAgent : r . UserAgent ( ) ,
Host : host ,
} )
2018-08-17 15:52:14 -04:00
return nil
2017-02-09 02:39:08 -05:00
}
2017-02-16 17:52:14 -05:00
if ! hasSuffix ( object , slashSeparator ) {
2017-02-09 02:39:08 -05:00
// If not a directory, compress the file and write it to response.
err := zipit ( pathJoin ( args . Prefix , object ) )
if err != nil {
return
}
continue
}
// For directories, list the contents recursively and write the objects as compressed
// date to the response writer.
marker := ""
for {
2018-03-28 17:14:06 -04:00
lo , err := listObjects ( context . Background ( ) , args . BucketName , pathJoin ( args . Prefix , object ) , marker , "" , 1000 )
2017-02-09 02:39:08 -05:00
if err != nil {
return
}
marker = lo . NextMarker
for _ , obj := range lo . Objects {
err = zipit ( obj . Name )
if err != nil {
return
}
}
if ! lo . IsTruncated {
break
}
}
}
}
2016-08-30 13:04:50 -04:00
// GetBucketPolicyArgs - get bucket policy args.
type GetBucketPolicyArgs struct {
BucketName string ` json:"bucketName" `
Prefix string ` json:"prefix" `
}
// GetBucketPolicyRep - get bucket policy reply.
type GetBucketPolicyRep struct {
2018-04-24 18:53:30 -04:00
UIVersion string ` json:"uiVersion" `
Policy miniogopolicy . BucketPolicy ` json:"policy" `
2016-08-30 13:04:50 -04:00
}
2017-06-19 22:45:13 -04:00
// GetBucketPolicy - get bucket policy for the requested prefix.
2016-08-30 13:04:50 -04:00
func ( web * webAPIHandlers ) GetBucketPolicy ( r * http . Request , args * GetBucketPolicyArgs , reply * GetBucketPolicyRep ) error {
2016-08-30 22:22:27 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-08-30 22:22:27 -04:00
}
2016-11-02 17:45:11 -04:00
2019-04-09 11:17:41 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
2018-10-17 19:23:09 -04:00
if authErr != nil {
return toJSONError ( authErr )
}
2019-04-09 11:17:41 -04:00
// For authenticated users apply IAM policy.
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
Action : iampolicy . GetBucketPolicyAction ,
BucketName : args . BucketName ,
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
IsOwner : owner ,
} ) {
2018-10-17 19:23:09 -04:00
return toJSONError ( errAccessDenied )
2016-11-02 17:45:11 -04:00
}
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-12-19 08:13:47 -05:00
var policyInfo = & miniogopolicy . BucketAccessPolicy { Version : "2012-10-17" }
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
2017-06-19 22:45:13 -04:00
return toJSONError ( err , args . BucketName )
}
2018-12-19 08:13:47 -05:00
client , rerr := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if rerr != nil {
return toJSONError ( rerr , args . BucketName )
}
policyStr , err := client . GetBucketPolicy ( args . BucketName )
if err != nil {
return toJSONError ( rerr , args . BucketName )
}
bucketPolicy , err := policy . ParseConfig ( strings . NewReader ( policyStr ) , args . BucketName )
if err != nil {
return toJSONError ( rerr , args . BucketName )
}
policyInfo , err = PolicyToBucketAccessPolicy ( bucketPolicy )
if err != nil {
// This should not happen.
return toJSONError ( err , args . BucketName )
}
} else {
bucketPolicy , err := objectAPI . GetBucketPolicy ( context . Background ( ) , args . BucketName )
if err != nil {
if _ , ok := err . ( BucketPolicyNotFound ) ; ! ok {
return toJSONError ( err , args . BucketName )
}
return err
}
2016-08-30 13:04:50 -04:00
2018-12-19 08:13:47 -05:00
policyInfo , err = PolicyToBucketAccessPolicy ( bucketPolicy )
if err != nil {
// This should not happen.
return toJSONError ( err , args . BucketName )
}
2018-04-24 18:53:30 -04:00
}
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2018-04-24 18:53:30 -04:00
reply . Policy = miniogopolicy . GetPolicy ( policyInfo . Statements , args . BucketName , args . Prefix )
2016-08-30 13:04:50 -04:00
return nil
}
2016-09-26 00:53:19 -04:00
// ListAllBucketPoliciesArgs - get all bucket policies.
type ListAllBucketPoliciesArgs struct {
2016-09-23 02:06:45 -04:00
BucketName string ` json:"bucketName" `
}
2017-03-16 15:21:58 -04:00
// BucketAccessPolicy - Collection of canned bucket policy at a given prefix.
type BucketAccessPolicy struct {
2018-04-24 18:53:30 -04:00
Bucket string ` json:"bucket" `
Prefix string ` json:"prefix" `
Policy miniogopolicy . BucketPolicy ` json:"policy" `
2016-09-26 00:53:19 -04:00
}
// ListAllBucketPoliciesRep - get all bucket policy reply.
type ListAllBucketPoliciesRep struct {
UIVersion string ` json:"uiVersion" `
2017-03-16 15:21:58 -04:00
Policies [ ] BucketAccessPolicy ` json:"policies" `
2016-09-23 02:06:45 -04:00
}
2018-04-24 18:53:30 -04:00
// ListAllBucketPolicies - get all bucket policy.
2016-09-26 00:53:19 -04:00
func ( web * webAPIHandlers ) ListAllBucketPolicies ( r * http . Request , args * ListAllBucketPoliciesArgs , reply * ListAllBucketPoliciesRep ) error {
2016-09-23 02:06:45 -04:00
objectAPI := web . ObjectAPI ( )
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2018-10-17 19:23:09 -04:00
_ , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
}
2019-04-09 11:17:41 -04:00
2018-10-17 19:23:09 -04:00
if ! owner {
return toJSONError ( errAccessDenied )
2016-09-23 02:06:45 -04:00
}
2018-04-24 18:53:30 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-12-19 08:13:47 -05:00
var policyInfo = new ( miniogopolicy . BucketAccessPolicy )
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
return toJSONError ( err , args . BucketName )
}
core , rerr := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if rerr != nil {
return toJSONError ( rerr , args . BucketName )
}
var policyStr string
policyStr , err = core . Client . GetBucketPolicy ( args . BucketName )
if err != nil {
return toJSONError ( err , args . BucketName )
}
if policyStr != "" {
if err = json . Unmarshal ( [ ] byte ( policyStr ) , policyInfo ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
}
} else {
bucketPolicy , err := objectAPI . GetBucketPolicy ( context . Background ( ) , args . BucketName )
if err != nil {
if _ , ok := err . ( BucketPolicyNotFound ) ; ! ok {
return toJSONError ( err , args . BucketName )
}
}
policyInfo , err = PolicyToBucketAccessPolicy ( bucketPolicy )
if err != nil {
2017-06-01 12:43:20 -04:00
return toJSONError ( err , args . BucketName )
}
2018-04-24 18:53:30 -04:00
}
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2018-04-24 18:53:30 -04:00
for prefix , policy := range miniogopolicy . GetPolicies ( policyInfo . Statements , args . BucketName , "" ) {
2018-02-27 22:14:49 -05:00
bucketName , objectPrefix := urlPath2BucketObjectName ( prefix )
objectPrefix = strings . TrimSuffix ( objectPrefix , "*" )
2017-03-16 15:21:58 -04:00
reply . Policies = append ( reply . Policies , BucketAccessPolicy {
2018-02-27 22:14:49 -05:00
Bucket : bucketName ,
Prefix : objectPrefix ,
2016-09-26 00:53:19 -04:00
Policy : policy ,
} )
}
2018-04-24 18:53:30 -04:00
2016-09-23 02:06:45 -04:00
return nil
}
2018-04-24 18:53:30 -04:00
// SetBucketPolicyWebArgs - set bucket policy args.
type SetBucketPolicyWebArgs struct {
2016-08-30 13:04:50 -04:00
BucketName string ` json:"bucketName" `
Prefix string ` json:"prefix" `
Policy string ` json:"policy" `
}
// SetBucketPolicy - set bucket policy.
2018-04-24 18:53:30 -04:00
func ( web * webAPIHandlers ) SetBucketPolicy ( r * http . Request , args * SetBucketPolicyWebArgs , reply * WebGenericRep ) error {
2016-09-22 19:35:12 -04:00
objectAPI := web . ObjectAPI ( )
2017-06-05 11:11:54 -04:00
reply . UIVersion = browser . UIVersion
2016-09-22 19:35:12 -04:00
if objectAPI == nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( errServerNotInitialized )
2016-11-02 17:45:11 -04:00
}
2019-04-09 11:17:41 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
2018-10-17 19:23:09 -04:00
if authErr != nil {
return toJSONError ( authErr )
}
2019-04-09 11:17:41 -04:00
// For authenticated users apply IAM policy.
if ! globalIAMSys . IsAllowed ( iampolicy . Args {
AccountName : claims . Subject ,
Action : iampolicy . PutBucketPolicyAction ,
BucketName : args . BucketName ,
ConditionValues : getConditionValues ( r , "" , claims . Subject ) ,
IsOwner : owner ,
} ) {
2018-10-17 19:23:09 -04:00
return toJSONError ( errAccessDenied )
2016-09-22 19:35:12 -04:00
}
2016-08-30 13:04:50 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2018-04-24 18:53:30 -04:00
policyType := miniogopolicy . BucketPolicy ( args . Policy )
if ! policyType . IsValidBucketPolicy ( ) {
2016-11-22 14:12:38 -05:00
return & json2 . Error {
Message : "Invalid policy type " + args . Policy ,
}
2016-08-30 13:04:50 -04:00
}
2018-04-24 18:53:30 -04:00
ctx := context . Background ( )
2018-12-19 08:13:47 -05:00
if isRemoteCallRequired ( context . Background ( ) , args . BucketName , objectAPI ) {
sr , err := globalDNSConfig . Get ( args . BucketName )
if err != nil {
if err == dns . ErrNoEntriesFound {
return toJSONError ( BucketNotFound {
Bucket : args . BucketName ,
} , args . BucketName )
}
2017-06-01 12:43:20 -04:00
return toJSONError ( err , args . BucketName )
}
2018-12-19 08:13:47 -05:00
core , rerr := getRemoteInstanceClient ( r , getHostFromSrv ( sr ) )
if rerr != nil {
return toJSONError ( rerr , args . BucketName )
}
var policyStr string
// Use the abstracted API instead of core, such that
// NoSuchBucketPolicy errors are automatically handled.
policyStr , err = core . Client . GetBucketPolicy ( args . BucketName )
if err != nil {
return toJSONError ( err , args . BucketName )
}
var policyInfo = & miniogopolicy . BucketAccessPolicy { Version : "2012-10-17" }
if policyStr != "" {
if err = json . Unmarshal ( [ ] byte ( policyStr ) , policyInfo ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
}
2017-06-01 12:43:20 -04:00
2018-12-19 08:13:47 -05:00
policyInfo . Statements = miniogopolicy . SetPolicy ( policyInfo . Statements , policyType , args . BucketName , args . Prefix )
if len ( policyInfo . Statements ) == 0 {
if err = core . SetBucketPolicy ( args . BucketName , "" ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
return nil
}
2018-04-24 18:53:30 -04:00
2018-12-19 08:13:47 -05:00
bucketPolicy , err := BucketAccessPolicyToPolicy ( policyInfo )
if err != nil {
// This should not happen.
return toJSONError ( err , args . BucketName )
}
2017-06-01 12:43:20 -04:00
2018-12-19 08:13:47 -05:00
policyData , err := json . Marshal ( bucketPolicy )
if err != nil {
2016-11-22 14:12:38 -05:00
return toJSONError ( err , args . BucketName )
2016-09-26 06:11:22 -04:00
}
2018-04-24 18:53:30 -04:00
2018-12-19 08:13:47 -05:00
if err = core . SetBucketPolicy ( args . BucketName , string ( policyData ) ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
2017-10-27 19:14:06 -04:00
2018-12-19 08:13:47 -05:00
} else {
bucketPolicy , err := objectAPI . GetBucketPolicy ( ctx , args . BucketName )
if err != nil {
if _ , ok := err . ( BucketPolicyNotFound ) ; ! ok {
return toJSONError ( err , args . BucketName )
}
}
policyInfo , err := PolicyToBucketAccessPolicy ( bucketPolicy )
if err != nil {
// This should not happen.
return toJSONError ( err , args . BucketName )
}
2018-02-27 22:14:49 -05:00
2018-12-19 08:13:47 -05:00
policyInfo . Statements = miniogopolicy . SetPolicy ( policyInfo . Statements , policyType , args . BucketName , args . Prefix )
if len ( policyInfo . Statements ) == 0 {
if err = objectAPI . DeleteBucketPolicy ( ctx , args . BucketName ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
globalPolicySys . Remove ( args . BucketName )
return nil
}
bucketPolicy , err = BucketAccessPolicyToPolicy ( policyInfo )
if err != nil {
// This should not happen.
return toJSONError ( err , args . BucketName )
}
2018-02-09 18:19:30 -05:00
2018-12-19 08:13:47 -05:00
// Parse validate and save bucket policy.
if err := objectAPI . SetBucketPolicy ( ctx , args . BucketName , bucketPolicy ) ; err != nil {
return toJSONError ( err , args . BucketName )
}
globalPolicySys . Set ( args . BucketName , * bucketPolicy )
globalNotificationSys . SetBucketPolicy ( ctx , args . BucketName , bucketPolicy )
}
2018-04-24 18:53:30 -04:00
2016-08-30 13:04:50 -04:00
return nil
}
2016-09-23 04:24:49 -04:00
// PresignedGetArgs - presigned-get API args.
type PresignedGetArgs struct {
// Host header required for signed headers.
HostName string ` json:"host" `
// Bucket name of the object to be presigned.
BucketName string ` json:"bucket" `
// Object name to be presigned.
ObjectName string ` json:"object" `
2016-11-22 14:12:38 -05:00
// Expiry in seconds.
Expiry int64 ` json:"expiry" `
2016-09-23 04:24:49 -04:00
}
// PresignedGetRep - presigned-get URL reply.
type PresignedGetRep struct {
2016-10-23 15:32:35 -04:00
UIVersion string ` json:"uiVersion" `
2016-09-23 04:24:49 -04:00
// Presigned URL of the object.
URL string ` json:"url" `
}
// PresignedGET - returns presigned-Get url.
func ( web * webAPIHandlers ) PresignedGet ( r * http . Request , args * PresignedGetArgs , reply * PresignedGetRep ) error {
2018-10-17 19:23:09 -04:00
claims , owner , authErr := webRequestAuthenticate ( r )
if authErr != nil {
return toJSONError ( authErr )
}
var creds auth . Credentials
if ! owner {
var ok bool
creds , ok = globalIAMSys . GetUser ( claims . Subject )
if ! ok {
return toJSONError ( errInvalidAccessKeyID )
}
} else {
creds = globalServerConfig . GetCredential ( )
2016-09-23 04:24:49 -04:00
}
2016-11-22 14:12:38 -05:00
2018-10-17 19:23:09 -04:00
region := globalServerConfig . GetRegion ( )
2016-09-23 04:24:49 -04:00
if args . BucketName == "" || args . ObjectName == "" {
2016-11-22 14:12:38 -05:00
return & json2 . Error {
Message : "Bucket and Object are mandatory arguments." ,
}
2016-09-23 04:24:49 -04:00
}
2018-10-17 19:23:09 -04:00
2019-04-04 02:10:37 -04:00
// Check if bucket is a reserved bucket name or invalid.
if isReservedOrInvalidBucket ( args . BucketName , false ) {
return toJSONError ( errInvalidBucketName )
}
2017-02-22 20:27:26 -05:00
reply . UIVersion = browser . UIVersion
2018-10-17 19:23:09 -04:00
reply . URL = presignedGet ( args . HostName , args . BucketName , args . ObjectName , args . Expiry , creds , region )
2016-09-23 04:24:49 -04:00
return nil
}
// Returns presigned url for GET method.
2018-10-17 19:23:09 -04:00
func presignedGet ( host , bucket , object string , expiry int64 , creds auth . Credentials , region string ) string {
accessKey := creds . AccessKey
secretKey := creds . SecretKey
2016-09-23 04:24:49 -04:00
2017-03-18 14:28:41 -04:00
date := UTCNow ( )
2016-11-11 00:57:15 -05:00
dateStr := date . Format ( iso8601Format )
2016-09-23 04:24:49 -04:00
credential := fmt . Sprintf ( "%s/%s" , accessKey , getScope ( date , region ) )
2016-11-22 14:12:38 -05:00
var expiryStr = "604800" // Default set to be expire in 7days.
if expiry < 604800 && expiry > 0 {
expiryStr = strconv . FormatInt ( expiry , 10 )
}
2018-06-05 13:48:51 -04:00
query := url . Values { }
query . Set ( "X-Amz-Algorithm" , signV4Algorithm )
query . Set ( "X-Amz-Credential" , credential )
query . Set ( "X-Amz-Date" , dateStr )
query . Set ( "X-Amz-Expires" , expiryStr )
query . Set ( "X-Amz-SignedHeaders" , "host" )
queryStr := s3utils . QueryEncode ( query )
2016-09-23 04:24:49 -04:00
path := "/" + path . Join ( bucket , object )
2017-04-05 20:00:24 -04:00
// "host" is the only header required to be signed for Presigned URLs.
extractedSignedHeaders := make ( http . Header )
extractedSignedHeaders . Set ( "host" , host )
2018-06-05 13:48:51 -04:00
canonicalRequest := getCanonicalRequest ( extractedSignedHeaders , unsignedPayload , queryStr , path , "GET" )
2017-02-06 16:09:09 -05:00
stringToSign := getStringToSign ( canonicalRequest , date , getScope ( date , region ) )
2019-02-27 20:46:55 -05:00
signingKey := getSigningKey ( secretKey , date , region , serviceS3 )
2016-09-23 04:24:49 -04:00
signature := getSignature ( signingKey , stringToSign )
// Construct the final presigned URL.
2018-06-05 13:48:51 -04:00
return host + s3utils . EncodePath ( path ) + "?" + queryStr + "&" + "X-Amz-Signature=" + signature
2016-09-23 04:24:49 -04:00
}
2016-11-22 14:12:38 -05:00
// toJSONError converts regular errors into more user friendly
// and consumable error message for the browser UI.
func toJSONError ( err error , params ... string ) ( jerr * json2 . Error ) {
apiErr := toWebAPIError ( err )
jerr = & json2 . Error {
Message : apiErr . Description ,
}
switch apiErr . Code {
2017-03-03 06:01:42 -05:00
// Reserved bucket name provided.
case "AllAccessDisabled" :
if len ( params ) > 0 {
jerr = & json2 . Error {
Message : fmt . Sprintf ( "All access to this bucket %s has been disabled." , params [ 0 ] ) ,
}
}
2016-11-22 14:12:38 -05:00
// Bucket name invalid with custom error message.
case "InvalidBucketName" :
if len ( params ) > 0 {
jerr = & json2 . Error {
2017-05-19 10:30:00 -04:00
Message : fmt . Sprintf ( "Bucket Name %s is invalid. Lowercase letters, period, hyphen, numerals are the only allowed characters and should be minimum 3 characters in length." , params [ 0 ] ) ,
2016-11-22 14:12:38 -05:00
}
}
// Bucket not found custom error message.
case "NoSuchBucket" :
if len ( params ) > 0 {
jerr = & json2 . Error {
Message : fmt . Sprintf ( "The specified bucket %s does not exist." , params [ 0 ] ) ,
}
}
// Object not found custom error message.
case "NoSuchKey" :
if len ( params ) > 1 {
jerr = & json2 . Error {
Message : fmt . Sprintf ( "The specified key %s does not exist" , params [ 1 ] ) ,
}
}
// Add more custom error messages here with more context.
}
return jerr
}
// toWebAPIError - convert into error into APIError.
func toWebAPIError ( err error ) APIError {
2019-03-18 10:46:20 -04:00
switch err {
case errServerNotInitialized :
2016-11-22 14:12:38 -05:00
return APIError {
Code : "XMinioServerNotInitialized" ,
HTTPStatusCode : http . StatusServiceUnavailable ,
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errAuthentication , auth . ErrInvalidAccessKeyLength , auth . ErrInvalidSecretKeyLength , errInvalidAccessKeyID :
2017-01-03 04:33:00 -05:00
return APIError {
Code : "AccessDenied" ,
HTTPStatusCode : http . StatusForbidden ,
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errSizeUnspecified :
2017-02-02 13:45:00 -05:00
return APIError {
Code : "InvalidRequest" ,
HTTPStatusCode : http . StatusBadRequest ,
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errChangeCredNotAllowed :
2017-02-07 15:51:43 -05:00
return APIError {
Code : "MethodNotAllowed" ,
HTTPStatusCode : http . StatusMethodNotAllowed ,
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errInvalidBucketName :
2017-03-03 06:01:42 -05:00
return APIError {
2017-09-01 15:16:54 -04:00
Code : "InvalidBucketName" ,
HTTPStatusCode : http . StatusBadRequest ,
2017-03-03 06:01:42 -05:00
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errInvalidArgument :
2017-04-27 02:27:48 -04:00
return APIError {
Code : "InvalidArgument" ,
HTTPStatusCode : http . StatusBadRequest ,
Description : err . Error ( ) ,
}
2019-03-18 10:46:20 -04:00
case errEncryptedObject :
2018-08-24 10:56:24 -04:00
return getAPIError ( ErrSSEEncryptedObject )
2019-03-18 10:46:20 -04:00
case errInvalidEncryptionParameters :
2018-08-24 10:56:24 -04:00
return getAPIError ( ErrInvalidEncryptionParameters )
2019-03-18 10:46:20 -04:00
case errObjectTampered :
2018-08-24 10:56:24 -04:00
return getAPIError ( ErrObjectTampered )
2019-03-18 10:46:20 -04:00
case errMethodNotAllowed :
2018-06-06 21:10:51 -04:00
return getAPIError ( ErrMethodNotAllowed )
2016-11-22 14:12:38 -05:00
}
2018-06-06 21:10:51 -04:00
2016-11-22 14:12:38 -05:00
// Convert error type to api error code.
switch err . ( type ) {
case StorageFull :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrStorageFull )
2016-11-22 14:12:38 -05:00
case BucketNotFound :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrNoSuchBucket )
2016-11-23 20:31:11 -05:00
case BucketExists :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrBucketAlreadyOwnedByYou )
2016-11-22 14:12:38 -05:00
case BucketNameInvalid :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrInvalidBucketName )
2017-10-22 01:30:34 -04:00
case hash . BadDigest :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrBadDigest )
2016-11-22 14:12:38 -05:00
case IncompleteBody :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrIncompleteBody )
2016-11-22 14:12:38 -05:00
case ObjectExistsAsDirectory :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrObjectExistsAsDirectory )
2016-11-22 14:12:38 -05:00
case ObjectNotFound :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrNoSuchKey )
2016-11-22 14:12:38 -05:00
case ObjectNameInvalid :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrNoSuchKey )
2016-11-22 14:12:38 -05:00
case InsufficientWriteQuorum :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrWriteQuorum )
2016-11-22 14:12:38 -05:00
case InsufficientReadQuorum :
2017-06-07 22:31:23 -04:00
return getAPIError ( ErrReadQuorum )
case NotImplemented :
return APIError {
Code : "NotImplemented" ,
HTTPStatusCode : http . StatusBadRequest ,
Description : "Functionality not implemented" ,
}
}
// Log unexpected and unhandled errors.
2018-04-05 18:04:40 -04:00
logger . LogIf ( context . Background ( ) , err )
2017-06-07 22:31:23 -04:00
return APIError {
Code : "InternalError" ,
HTTPStatusCode : http . StatusInternalServerError ,
Description : err . Error ( ) ,
2016-11-22 14:12:38 -05:00
}
}
// writeWebErrorResponse - set HTTP status code and write error description to the body.
func writeWebErrorResponse ( w http . ResponseWriter , err error ) {
apiErr := toWebAPIError ( err )
w . WriteHeader ( apiErr . HTTPStatusCode )
w . Write ( [ ] byte ( apiErr . Description ) )
}