Last active
November 1, 2020 21:53
-
-
Save salrashid123/c894e3029be76243761709cf834c7ed1 to your computer and use it in GitHub Desktop.
Impersonate and Downscope GCP credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"time" | |
"cloud.google.com/go/storage" | |
sal "github.com/salrashid123/oauth2/downscoped" | |
salimp "github.com/salrashid123/oauth2/impersonate" | |
"google.golang.org/api/iterator" | |
"google.golang.org/api/option" | |
"golang.org/x/oauth2/google" | |
) | |
const ( | |
serviceAccountFile = "/path/to/svc_account.json" | |
) | |
var ( | |
projectID = "fabled-ray-104117" | |
bucketName = "fabled-ray-104117-bucket" | |
folder = "" | |
) | |
func main() { | |
ctx := context.Background() | |
defaultTokenSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/iam") | |
if err != nil { | |
log.Fatal(err) | |
} | |
targetPrincipal := "impersonated-account@fabled-ray-104117.iam.gserviceaccount.com" | |
lifetime := 30 * time.Second | |
delegates := []string{} | |
targetScopes := []string{"https://www.googleapis.com/auth/devstorage.read_only", | |
"https://www.googleapis.com/auth/cloud-platform"} | |
impersonatedTokenSource, err := salimp.ImpersonatedTokenSource( | |
&salimp.ImpersonatedTokenConfig{ | |
RootTokenSource: defaultTokenSource, | |
TargetPrincipal: targetPrincipal, | |
Lifetime: lifetime, | |
Delegates: delegates, | |
TargetScopes: targetScopes, | |
}, | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
downScopedTokenSource, err := sal.DownScopedTokenSource( | |
&sal.DownScopedTokenConfig{ | |
RootTokenSource: impersonatedTokenSource, | |
DownscopedOptions: sal.DownscopedOptions{ | |
AccessBoundary: sal.AccessBoundary{ | |
AccessBoundaryRules: []sal.AccessBoundaryRule{ | |
sal.AccessBoundaryRule{ | |
AvailableResource: "//storage.googleapis.com/projects/_/buckets/" + bucketName, | |
AvailablePermissions: []string{ | |
"inRole:roles/storage.objectViewer", | |
}, | |
AvailabilityCondition: sal.AvailabilityCondition{ | |
Title: "obj-prefixes", | |
Expression: "resource.name.startsWith(\"projects/_/buckets/your_bucket/objects/foo.txt\")", | |
}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
) | |
storageClient, err := storage.NewClient(ctx, option.WithTokenSource(downScopedTokenSource)) | |
if err != nil { | |
log.Fatalf("Could not create storage Client: %v", err) | |
} | |
it := storageClient.Bucket(bucketName).Objects(ctx, &storage.Query{ | |
Prefix: folder, | |
}) | |
for { | |
attrs, err := it.Next() | |
if err == iterator.Done { | |
break | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(attrs.Name) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment