serviceaccount

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2024 License: MIT Imports: 12 Imported by: 1

README

Here's a basic README.md for your serviceaccount package that explains the purpose, how to install, use, and run tests.

# Google Service Account Authentication

This Go package simplifies the process of generating authenticated HTTP clients using Google Service Accounts. It handles signing JWTs, exchanging them for OAuth2 access tokens, and generating authenticated HTTP clients that can interact with Google Cloud services.

## Features
- Sign JWTs using Google IAM Service
- Generate OAuth2 tokens from signed JWTs
- Create authenticated HTTP clients for accessing Google services

## Installation

To use this package in your Go project, you can install it with `go get`:

```bash
go get github.com/duizendstra/go/google/auth/serviceaccount

Ensure that you have the required dependencies installed in your project:

go mod tidy

Usage

Generate an Authenticated HTTP Client

You can use this package to generate an authenticated HTTP client using a Google Service Account. Here's an example of how to use it:

package main

import (
    "context"
    "fmt"
    "github.com/duizendstra/go/google/auth/serviceaccount"
    "github.com/duizendstra/go/google/logging"
)

func main() {
    ctx := context.Background()
    logger := logging.NewStructuredLogger("test-project", "test-component", nil, nil)
    iamClient := &serviceaccount.GoogleIAMServiceClient{}
    
    // Replace with your service account details
    serviceAccount := "your-service-account@your-project.iam.gserviceaccount.com"
    userEmail := "user@example.com"
    scopes := "https://www.googleapis.com/auth/cloud-platform"
    
    client, err := serviceaccount.GenerateGoogleHTTPClient(ctx, logger, iamClient, serviceAccount, userEmail, scopes)
    if err != nil {
        logger.LogError(ctx, "Failed to generate HTTP client", "error", err)
        return
    }

    fmt.Println("Successfully created authenticated HTTP client!")
}

JWT Claims

When generating the signed JWT, the following claims are used:

  • iss: The service account email address
  • sub: The user email address
  • scope: The scopes required for accessing Google Cloud resources
  • aud: The audience, which is the Google token endpoint
  • iat: The issued-at time (current time in seconds)
  • exp: The expiration time (set to 1 hour after iat)

Logging

The package uses structured logging with a logger interface, allowing you to log errors and events during the process of creating and signing JWTs, and exchanging tokens.

Error Handling

The package includes error handling for different stages:

  • Creating the JWT assertion
  • Signing the JWT using Google IAM Service
  • Exchanging the signed JWT for an access token
  • Handling non-OK HTTP responses from the token endpoint

Running Tests

To run the tests for this package, simply use the Go testing tool:

go test ./...

The tests include:

  • Mocked IAM service client for JWT signing
  • Mock HTTP server to simulate Google token endpoints
  • Various test cases to cover valid and invalid input scenarios

License

This project is licensed under the MIT License. See the LICENSE file for details.


For any issues or questions, feel free to contact Jasper Duizendstra.

Documentation

Overview

Copyright 2024 Jasper Duizendstra

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateGoogleHTTPClient

func GenerateGoogleHTTPClient(ctx context.Context, logger *structured.StructuredLogger, iamClient IAMServiceClient, targetServiceAccount, userEmail, scopes string, tokenURL ...string) (*http.Client, error)

GenerateGoogleHTTPClient creates an authenticated HTTP client for GCP services.

Types

type GoogleIAMServiceClient

type GoogleIAMServiceClient struct{}

GoogleIAMServiceClient is an implementation of IAMServiceClient that talks to the real IAM service.

func (*GoogleIAMServiceClient) SignJwt

func (c *GoogleIAMServiceClient) SignJwt(ctx context.Context, name string, payload string) (*iam.SignJwtResponse, error)

SignJwt creates a signed JWT by calling Google's IAM service.

type IAMServiceClient

type IAMServiceClient interface {
	SignJwt(ctx context.Context, name string, payload string) (*iam.SignJwtResponse, error)
}

IAMServiceClient defines the interface for the IAM service operations.

type JWTClaims

type JWTClaims struct {
	Iss   string `json:"iss"`
	Sub   string `json:"sub"`
	Scope string `json:"scope"`
	Aud   string `json:"aud"`
	Iat   int64  `json:"iat"`
	Exp   int64  `json:"exp"`
}

JWTClaims represents the claims needed for creating a JWT assertion.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL